From 9a1d78cef5e9e28a920374875fed6e598d8a3182 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 13:43:30 +0000 Subject: [PATCH 1/2] =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=EB=A5=BC=20?= =?UTF-8?q?=EA=B3=84=EC=95=BD=20=EC=8B=9C=EB=82=98=EB=A6=AC=EC=98=A4?= =?UTF-8?q?=EC=99=80=20=ED=8C=8C=EC=9D=BC=EB=8B=B9=20400=EC=A4=84=20?= =?UTF-8?q?=EC=83=81=ED=95=9C=EC=9C=BC=EB=A1=9C=20=EC=A4=84=EC=9D=B8?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 산문·HTML·문장 고정과 긴 회귀 파일을 대표 시나리오로 바꾸고, 가드 명령과 설치 경로는 데이터 파일을 테스트가 전부 실행하게 했다. CI는 파일 길이와 수집 케이스 300/999만 검사한다. Co-authored-by: Wooyeop Han --- .github/workflows/tests.yml | 2 + docs/architecture.md | 5 +- docs/development.md | 5 + tests/contracts/test_distribution.py | 103 - tests/contracts/test_install.py | 23 + tests/contracts/test_python_runtime.py | 207 -- tests/fixtures/guard_commands.json | 157 + tests/fixtures/install_paths.json | 19 + tests/fixtures/required_contracts.json | 17 + tests/integration/codex/test_codex.py | 623 ---- tests/integration/codex/test_codex_entry.py | 19 + tests/integration/distill/test_distill.py | 450 --- .../integration/distill/test_distill_entry.py | 20 + tests/integration/doctor/test_doctor.py | 501 --- tests/integration/doctor/test_doctor_entry.py | 11 + tests/integration/grok/test_grok_entry.py | 11 + .../integration/grok/test_grok_transcript.py | 416 --- tests/integration/grok/test_han_state.py | 533 --- tests/integration/grok/test_p4c.py | 53 - .../grok/test_process_discovery.py | 102 - tests/integration/hermes/test_attachments.py | 324 -- .../integration/hermes/test_claude_workers.py | 413 --- .../hermes/test_current_session.py | 232 -- .../integration/hermes/test_external_slots.py | 445 --- .../hermes/test_mission_operations.py | 72 - .../integration/hermes/test_native_bridge.py | 231 -- .../integration/hermes/test_native_workers.py | 331 -- tests/integration/hermes/test_posix_paths.py | 41 - tests/integration/hermes/test_runtime.py | 171 - .../hermes/test_worker_contracts.py | 59 - tests/integration/hermes/test_workers.py | 735 ---- tests/integration/hooks/test_grok_hooks.py | 201 -- .../hooks/test_guard_allow_write.py | 132 - .../hooks/test_guard_command_exceptions.py | 83 - tests/integration/hooks/test_guard_corpus.py | 18 + tests/integration/hooks/test_mission_entry.py | 787 ---- tests/integration/hooks/test_mission_guard.py | 1687 --------- .../integration/hooks/test_mission_policy.py | 168 - .../hooks/test_mission_transitions.py | 228 -- .../hooks/test_question_integrity.py | 284 -- .../integration/hooks/test_question_write.py | 46 + .../hooks/test_question_write_guard.py | 501 --- tests/integration/hooks/test_session_rules.py | 242 -- .../hooks/test_shared_allow_once_hooks.py | 94 - tests/integration/hooks/test_stale_p4.py | 165 - .../integration/hooks/test_subagent_allow.py | 313 -- tests/integration/mission/test_chaos.py | 235 -- .../mission/test_check_human_doc.py | 393 -- .../mission/test_execution_leases.py | 744 ---- tests/integration/mission/test_lab.py | 477 --- .../integration/mission/test_mission_flow.py | 19 + .../integration/mission/test_mission_state.py | 1386 -------- tests/integration/mission/test_observatory.py | 223 -- .../mission/test_p4c_close_stale.py | 113 - tests/integration/mission/test_plan_policy.py | 401 --- .../mission/test_portable_verification.py | 221 -- .../mission/test_question_authoring.py | 255 -- .../mission/test_question_blocks.py | 486 --- .../mission/test_question_readability.py | 628 ---- .../mission/test_question_record.py | 47 + .../mission/test_question_records.py | 1324 ------- .../mission/test_question_summary.py | 356 -- .../mission/test_reference_bundle.py | 148 - .../integration/mission/test_review_worker.py | 412 --- tests/integration/mission/test_routing.py | 85 - .../mission/test_state_efficiency.py | 451 --- tests/integration/mission/test_supervisor.py | 412 --- tests/integration/mission/test_unified_cli.py | 539 --- tests/integration/mission/test_unit_input.py | 125 - .../integration/mission/test_usage_report.py | 332 -- .../integration/mission/test_verification.py | 1985 ----------- .../mission/test_verification_reuse.py | 32 + tests/integration/slots/test_dashboard.py | 2039 +---------- .../slots/test_dashboard_discovery.py | 598 +--- .../slots/test_file_lock_concurrency.py | 233 -- .../slots/test_junction_detection.py | 53 - .../integration/slots/test_launch_backends.py | 163 - .../slots/test_observatory_dashboard.py | 71 - tests/integration/slots/test_p4_resolution.py | 156 - .../slots/test_platform_preparation.py | 242 -- .../integration/slots/test_portable_steps.py | 117 - tests/integration/slots/test_slot_safety.py | 47 + tests/integration/slots/test_slots.py | 3161 ----------------- tests/integration/workers/test_backends.py | 227 -- tests/integration/workers/test_context.py | 78 - tests/integration/workers/test_controller.py | 1276 ------- tests/integration/workers/test_edits.py | 175 - .../integration/workers/test_observations.py | 89 - tests/integration/workers/test_outcomes.py | 69 - tests/integration/workers/test_process.py | 59 - tests/integration/workers/test_profiles.py | 209 -- tests/integration/workers/test_store.py | 317 -- .../integration/workers/test_worker_policy.py | 109 - .../workers/test_worker_routing.py | 107 +- tests/support.py | 83 + tests/transition_support.py | 43 - tools/check_test_budget.py | 83 + 97 files changed, 745 insertions(+), 32168 deletions(-) delete mode 100644 tests/contracts/test_distribution.py create mode 100644 tests/contracts/test_install.py delete mode 100644 tests/contracts/test_python_runtime.py create mode 100644 tests/fixtures/guard_commands.json create mode 100644 tests/fixtures/install_paths.json create mode 100644 tests/fixtures/required_contracts.json delete mode 100644 tests/integration/codex/test_codex.py create mode 100644 tests/integration/codex/test_codex_entry.py delete mode 100644 tests/integration/distill/test_distill.py create mode 100644 tests/integration/distill/test_distill_entry.py delete mode 100644 tests/integration/doctor/test_doctor.py create mode 100644 tests/integration/doctor/test_doctor_entry.py create mode 100644 tests/integration/grok/test_grok_entry.py delete mode 100644 tests/integration/grok/test_grok_transcript.py delete mode 100644 tests/integration/grok/test_han_state.py delete mode 100644 tests/integration/grok/test_p4c.py delete mode 100644 tests/integration/grok/test_process_discovery.py delete mode 100644 tests/integration/hermes/test_attachments.py delete mode 100644 tests/integration/hermes/test_claude_workers.py delete mode 100644 tests/integration/hermes/test_current_session.py delete mode 100644 tests/integration/hermes/test_external_slots.py delete mode 100644 tests/integration/hermes/test_mission_operations.py delete mode 100644 tests/integration/hermes/test_native_bridge.py delete mode 100644 tests/integration/hermes/test_native_workers.py delete mode 100644 tests/integration/hermes/test_posix_paths.py delete mode 100644 tests/integration/hermes/test_runtime.py delete mode 100644 tests/integration/hermes/test_worker_contracts.py delete mode 100644 tests/integration/hermes/test_workers.py delete mode 100644 tests/integration/hooks/test_grok_hooks.py delete mode 100644 tests/integration/hooks/test_guard_allow_write.py delete mode 100644 tests/integration/hooks/test_guard_command_exceptions.py create mode 100644 tests/integration/hooks/test_guard_corpus.py delete mode 100644 tests/integration/hooks/test_mission_entry.py delete mode 100644 tests/integration/hooks/test_mission_guard.py delete mode 100644 tests/integration/hooks/test_mission_policy.py delete mode 100644 tests/integration/hooks/test_mission_transitions.py delete mode 100644 tests/integration/hooks/test_question_integrity.py create mode 100644 tests/integration/hooks/test_question_write.py delete mode 100644 tests/integration/hooks/test_question_write_guard.py delete mode 100644 tests/integration/hooks/test_session_rules.py delete mode 100644 tests/integration/hooks/test_shared_allow_once_hooks.py delete mode 100644 tests/integration/hooks/test_stale_p4.py delete mode 100644 tests/integration/hooks/test_subagent_allow.py delete mode 100644 tests/integration/mission/test_chaos.py delete mode 100644 tests/integration/mission/test_check_human_doc.py delete mode 100644 tests/integration/mission/test_execution_leases.py delete mode 100644 tests/integration/mission/test_lab.py create mode 100644 tests/integration/mission/test_mission_flow.py delete mode 100644 tests/integration/mission/test_mission_state.py delete mode 100644 tests/integration/mission/test_observatory.py delete mode 100644 tests/integration/mission/test_p4c_close_stale.py delete mode 100644 tests/integration/mission/test_plan_policy.py delete mode 100644 tests/integration/mission/test_portable_verification.py delete mode 100644 tests/integration/mission/test_question_authoring.py delete mode 100644 tests/integration/mission/test_question_blocks.py delete mode 100644 tests/integration/mission/test_question_readability.py create mode 100644 tests/integration/mission/test_question_record.py delete mode 100644 tests/integration/mission/test_question_records.py delete mode 100644 tests/integration/mission/test_question_summary.py delete mode 100644 tests/integration/mission/test_reference_bundle.py delete mode 100644 tests/integration/mission/test_review_worker.py delete mode 100644 tests/integration/mission/test_routing.py delete mode 100644 tests/integration/mission/test_state_efficiency.py delete mode 100644 tests/integration/mission/test_supervisor.py delete mode 100644 tests/integration/mission/test_unified_cli.py delete mode 100644 tests/integration/mission/test_unit_input.py delete mode 100644 tests/integration/mission/test_usage_report.py delete mode 100644 tests/integration/mission/test_verification.py create mode 100644 tests/integration/mission/test_verification_reuse.py delete mode 100644 tests/integration/slots/test_file_lock_concurrency.py delete mode 100644 tests/integration/slots/test_junction_detection.py delete mode 100644 tests/integration/slots/test_launch_backends.py delete mode 100644 tests/integration/slots/test_observatory_dashboard.py delete mode 100644 tests/integration/slots/test_p4_resolution.py delete mode 100644 tests/integration/slots/test_platform_preparation.py delete mode 100644 tests/integration/slots/test_portable_steps.py create mode 100644 tests/integration/slots/test_slot_safety.py delete mode 100644 tests/integration/slots/test_slots.py delete mode 100644 tests/integration/workers/test_backends.py delete mode 100644 tests/integration/workers/test_context.py delete mode 100644 tests/integration/workers/test_controller.py delete mode 100644 tests/integration/workers/test_edits.py delete mode 100644 tests/integration/workers/test_observations.py delete mode 100644 tests/integration/workers/test_outcomes.py delete mode 100644 tests/integration/workers/test_process.py delete mode 100644 tests/integration/workers/test_profiles.py delete mode 100644 tests/integration/workers/test_store.py delete mode 100644 tests/integration/workers/test_worker_policy.py create mode 100644 tests/support.py delete mode 100644 tests/transition_support.py create mode 100644 tools/check_test_budget.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f47abfe..3ca560e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -81,6 +81,8 @@ jobs: run: | python tools/generate_role_defaults.py python tools/generate_claude_profiles.py + - name: Check test file length, case limits, and contract coverage + run: python tools/check_test_budget.py - name: Run full synthetic suite if: ${{ !cancelled() }} id: pytest diff --git a/docs/architecture.md b/docs/architecture.md index edbfab9..9983416 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -144,8 +144,9 @@ POSIX의 개인 캐시 실행기는 원래 인터프리터 경로를 exec하여 6. Windows/macOS/Linux와 Python 3.11·3.13의 CI 결과를 확인한다. 로컬 결과와 미실행 환경을 구분한다. 7. 공개 경계 점검과 저장소 완료 절차에 따라 배포·설치본·실행 중 대시보드를 확인한다. -테스트는 정답이 아닌 현재 구현을 복제하지 않는다. 기존 테스트 삭제로 실패를 숨기지 않고, -위험한 동작인 상태 변경·동시 실행·경로 접근·검증 재사용을 실제 관찰 결과로 확인한다. +테스트는 정답이 아닌 현재 구현을 복제하지 않는다. 실패하는 단언을 지워서 빨간 스위트를 +녹색으로 만들지 않는다. 같은 계약을 남은 시나리오나 코퍼스가 여전히 잡으면 그 밖의 테스트는 +지울 수 있다. 위험한 동작인 상태 변경·동시 실행·경로 접근·검증 재사용을 실제 관찰 결과로 확인한다. 구조 검사는 테스트 혼입, 구현의 경로 조작과 등록 디렉터리 의존이 다시 생기면 실패해야 한다. Hermes의 미션 상태 변경은 `chef_mission` 도구 handler가 담당한다. 사전 훅은 검증만 하며 shell marker는 native bridge에서 거부한다. `contracts.py`는 명시된 외부 읽기 파일과 역할 지침·모델 정책의 해시를 확인한다. Claude·Codex·Grok의 기존 echo marker는 아래 실행 경계에 따라 전용 명령으로 전환한다. 기존 상태 CLI·훅 경로는 유지한다. diff --git a/docs/development.md b/docs/development.md index 7a809d4..254f728 100644 --- a/docs/development.md +++ b/docs/development.md @@ -93,6 +93,11 @@ python plugins/chef/chef_cli.py guard-check --runtime codex <어댑터 이름> 인자 없이 실행하면 생성 결과와 실제 파일의 일치를 검사합니다. CI는 Windows/macOS/Linux의 Python 3.11·3.13에서 전체 검사와 JUnit 결과 게시를 수행합니다. macOS/Linux의 별도 Hermes native job은 고정한 공개 Hermes 소스로 실제 플러그인 로더·도구 등록·훅·작업 경로 계약을 검사합니다. 모델·외부 메시징·인증정보를 사용하지 않습니다. +테스트 파일과 테스트 데이터(`py`·`json`·`tsv`·`txt`)는 파일당 400줄을 넘기지 않습니다. +수집 케이스는 300개를 넘기지 않으며, 999개는 절대 상한입니다. 줄 합은 약 3,400줄을 목표로 두되 +그 합을 CI에서 검사하지 않습니다. `python tools/check_test_budget.py`가 파일 길이와 수집 수, +가드 목록·검증 무효·슬롯 거부 계약이 테스트에 연결됐는지를 확인합니다. + 저장소의 `pytest.ini`가 패키지 경로와 테스트 검색 범위를 정합니다. 테스트 파일에서 스킬의 구현 디렉터리를 Python 검색 경로로 추가하지 않습니다. 기존 `python plugins/chef/codex/sync_shared.py`는 체크아웃에서만 쓰는 개발 명령 별칭으로 유지합니다. diff --git a/tests/contracts/test_distribution.py b/tests/contracts/test_distribution.py deleted file mode 100644 index 66a3a9a..0000000 --- a/tests/contracts/test_distribution.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Execute the installed layout without the checkout or ambient Python paths.""" -import json -import os -import shutil -import subprocess -import sys -from pathlib import Path - -import pytest - -from tests.paths import PLUGIN_ROOT -from tools.check_architecture import inspect - - -@pytest.fixture(scope="module") -def installed(tmp_path_factory): - root = tmp_path_factory.mktemp("distribution with spaces") - target = root / "installed plugin" - shutil.copytree(PLUGIN_ROOT, target, ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache")) - return target, root - - -@pytest.mark.parametrize("relative", [ - "skills/mission/scripts/mission_state.py", - "codex/skills/chef-mission/scripts/mission_state.py", - "skills/slots/scripts/slots.py", - "codex/skills/chef-slots/scripts/slots.py", - "skills/slots/scripts/dashboard.py", - "codex/skills/chef-slots/scripts/dashboard.py", - "skills/doctor/scripts/doctor.py", - "codex/skills/chef-doctor/scripts/doctor.py", - "skills/distill/scripts/distill.py", - "codex/skills/chef-distill/scripts/distill.py", - "skills/mission/scripts/p4c.py", - "codex/skills/chef-mission/scripts/p4c.py", - "grok/skills/chef-mission/scripts/p4c.py", - "skills/mission/scripts/check_human_doc.py", - "skills/mission/scripts/run_metrics.py", - "skills/mission/scripts/task_queue.py", - "skills/mission/scripts/model_recommendations.py", -]) -def test_installed_commands_resolve_without_checkout(installed, relative): - target, cwd = installed - result = subprocess.run([sys.executable, "-I", "-B", str(target / relative), "--help"], - cwd=cwd, capture_output=True, timeout=30) - assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace") - if relative.endswith("p4c.py"): - assert b"--client" in result.stdout and b"--dry-run" in result.stdout - else: - assert b"usage:" in result.stdout - - -@pytest.mark.parametrize("relative,runtime", [ - ("hooks/session_rules.py", "claude"), - ("codex/session_rules.py", "codex"), - ("hooks/session_rules.py", "grok"), -]) -def test_installed_session_hooks_keep_transcript_contract(installed, relative, runtime): - target, cwd = installed - transcript = str(cwd / "fictional-session.jsonl") - payload = {"hook_event_name": "SessionStart", "han_runtime": runtime, - "cwd": str(cwd), "session_id": "fictional-session", "transcript_path": transcript} - result = subprocess.run([sys.executable, "-I", "-B", str(target / relative)], cwd=cwd, - input=json.dumps(payload).encode(), capture_output=True, timeout=30) - assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace") - if runtime in ("codex", "grok"): - assert "--transcript" in result.stdout.decode("utf-8") - assert "fictional-session.jsonl" in result.stdout.decode("utf-8") - - -@pytest.mark.parametrize("relative", [ - "skills/mission/scripts/check_human_doc.py", - "skills/mission/scripts/run_metrics.py", - "skills/mission/scripts/task_queue.py", - "skills/mission/scripts/model_recommendations.py", -]) -def test_helpers_emit_utf8_under_a_western_windows_code_page(installed, relative): - target, cwd = installed - code = ( - "import runpy,sys;" - "sys.stdout.reconfigure(encoding='cp1252');sys.stderr.reconfigure(encoding='cp1252');" - "sys.argv=sys.argv[1:];runpy.run_path(sys.argv[0],run_name='__main__')" - ) - result = subprocess.run([sys.executable, "-I", "-B", "-c", code, str(target / relative), "--help"], - cwd=cwd, capture_output=True, timeout=30) - assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace") - text = result.stdout.decode("utf-8") - assert "usage:" in text and any(ord(character) > 127 for character in text) - - -def test_distribution_excludes_tests_and_enforces_dependencies(): - assert inspect() == [] - - -def test_structure_check_rejects_deployment_tests_and_inverted_imports(tmp_path): - package = tmp_path / "chef/infrastructure" - package.mkdir(parents=True) - (tmp_path / "test_accidental.py").write_text("", encoding="utf-8") - (package / "bad.py").write_text("import sys\nsys.path.insert(0, 'scripts')\nimport chef.slots.commands\n", encoding="utf-8") - errors = inspect(tmp_path) - assert any("test in deployment" in error for error in errors) - assert any("changes import paths" in error for error in errors) - assert any("infrastructure imports" in error for error in errors) diff --git a/tests/contracts/test_install.py b/tests/contracts/test_install.py new file mode 100644 index 0000000..42db44d --- /dev/null +++ b/tests/contracts/test_install.py @@ -0,0 +1,23 @@ +"""Installed entry points resolve without the checkout on the path.""" +import json +import shutil +import subprocess +import sys + +from tests.paths import PLUGIN_ROOT +from tests.support import INSTALL_PATHS + + +def test_installed_commands_resolve_without_checkout(tmp_path): + target = tmp_path / "installed plugin" + shutil.copytree(PLUGIN_ROOT, target, ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache")) + paths = json.loads(INSTALL_PATHS.read_text(encoding="utf-8")) + assert paths + for relative in paths: + result = subprocess.run( + [sys.executable, "-I", "-B", str(target / relative), "--help"], + cwd=tmp_path, capture_output=True, timeout=30, + ) + assert result.returncode == 0, (relative, result.stderr.decode("utf-8", errors="replace")) + expected = b"--client" if relative.endswith("p4c.py") else b"usage:" + assert expected in result.stdout, relative diff --git a/tests/contracts/test_python_runtime.py b/tests/contracts/test_python_runtime.py deleted file mode 100644 index c36081d..0000000 --- a/tests/contracts/test_python_runtime.py +++ /dev/null @@ -1,207 +0,0 @@ -"""Run installed hook commands with isolated interpreter paths.""" - -import json -import os -import shutil -import subprocess -import sys -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path - -import pytest - -from chef.infrastructure.python import python_environment -from tests.paths import PLUGIN_ROOT - - -def test_unsupported_python_is_rejected_before_loading_a_product_module(monkeypatch): - from chef.cli import entrypoints - monkeypatch.setattr(entrypoints.sys, "version_info", (3, 9)) - with pytest.raises(SystemExit, match="Python 3.11 or newer"): - entrypoints.expose({"__name__": "fictional_module"}, "must_not_import_missing_module") - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX interpreter aliases") -@pytest.mark.parametrize("interpreter", ["python3", "python"]) -def test_installed_codex_hook_uses_the_only_interpreter_on_path(tmp_path, interpreter): - original_bin = tmp_path / f"only {interpreter}" - original_bin.mkdir() - (original_bin / interpreter).symlink_to(sys.executable) - plugin = tmp_path / "plugin with spaces" - shutil.copytree(PLUGIN_ROOT, plugin, ignore=shutil.ignore_patterns("__pycache__")) - payload = {"hook_event_name": "SessionStart", "session_id": "fictional-session", - "cwd": str(tmp_path), "transcript_path": "fictional-session.jsonl"} - codex_hook = json.loads((plugin / "codex/hooks.json").read_text(encoding="utf-8"))["hooks"]["SessionStart"][0]["hooks"][0] - codex_command = codex_hook["command"].replace("${PLUGIN_ROOT}", str(plugin)) - result = subprocess.run(["/bin/sh", "-c", codex_command], env={**os.environ, "PATH": str(original_bin)}, - input=json.dumps(payload).encode(), capture_output=True, timeout=30) - assert result.returncode == 0, result.stderr - assert b"fictional-session.jsonl" in result.stdout - - -@pytest.fixture(params=[ - pytest.param("python3", marks=pytest.mark.skipif(os.name == "nt", reason="POSIX interpreter alias")), - pytest.param("python", marks=pytest.mark.skipif(os.name == "nt", reason="POSIX interpreter alias")), - *[pytest.param(shell, marks=pytest.mark.skipif(os.name != "nt", reason="Windows hook shell")) - for shell in ("powershell", "pwsh", "git-bash", "cmd")], -]) -def shared_hook_shell(request, tmp_path): - name = request.param - if name in ("python3", "python"): - bin_dir = tmp_path / "only interpreter" - bin_dir.mkdir() - (bin_dir / name).symlink_to(sys.executable) - return ["/bin/sh", "-c"], str(bin_dir) - - if name == "git-bash": - git = shutil.which("git.exe") - candidates = [Path(os.environ["ProgramFiles"]) / "Git/bin/bash.exe"] - if git: - candidates.insert(0, Path(git).parent.parent / "bin/bash.exe") - executable = next((str(path) for path in candidates if path.is_file()), None) - else: - executable = shutil.which(f"{name}.exe") - if not executable: - pytest.skip(f"{name} is unavailable") - prefix = { - "powershell": ["-NoProfile", "-NonInteractive", "-Command"], - "pwsh": ["-NoProfile", "-NonInteractive", "-Command"], - "git-bash": ["-c"], - "cmd": ["/C"], - }[name] - return [executable, *prefix], str(Path(sys.executable).parent) - - -@pytest.mark.parametrize("runtime", ["claude", "grok"]) -def test_installed_shared_hook_preserves_session_and_guard_protocol(tmp_path, shared_hook_shell, runtime): - shell, bin_dir = shared_hook_shell - plugin = tmp_path / "plugin with spaces $and 'quotes'" - shutil.copytree(PLUGIN_ROOT, plugin, ignore=shutil.ignore_patterns("__pycache__")) - hooks = json.loads((plugin / "hooks/hooks.json").read_text(encoding="utf-8"))["hooks"] - env = {**os.environ, "PATH": bin_dir, "CLAUDE_PLUGIN_ROOT": str(plugin), - "HAN_ADAPTERS_DIR": str(tmp_path / "empty registry")} - for key in ("GROK_HOOK_EVENT", "GROK_SESSION_ID", "CLAUDE_ENV_FILE", "CHEF_HERMES_WORKER", "HAN_REPO"): - env.pop(key, None) - - def run(event, payload): - handler = hooks[event][0]["hooks"][0] - assert handler["type"] == "command" and "args" not in handler - command = handler["command"] - return subprocess.run([*shell, command], env=env, input=json.dumps(payload).encode(), capture_output=True, - cwd=tmp_path, timeout=30) - - session = "fictional-session" - transcript = "fictional-session.jsonl" - if runtime == "claude": - env_file = tmp_path / "claude.env" - env["CLAUDE_ENV_FILE"] = str(env_file) - started = {"hook_event_name": "SessionStart", "session_id": session, "transcript_path": transcript} - tool = {"hook_event_name": "PreToolUse", "session_id": session, "tool_name": "Bash", - "tool_input": {"command": "release-tool publish", "shell": "bash"}} - else: - started = {"hookEventName": "session_start", "sessionId": session, "transcriptPath": transcript} - tool = {"hookEventName": "pre_tool_use", "sessionId": session, "toolName": "run_terminal_command", - "toolInput": {"command": "release-tool publish", "shell": "bash"}} - result = run("SessionStart", {**started, "cwd": str(tmp_path)}) - assert result.returncode == 0, result.stderr - assert result.stderr == b"" - if runtime == "claude": - assert f'export HAN_TRANSCRIPT="{transcript}"' in env_file.read_text(encoding="utf-8") - else: - assert transcript in json.loads(result.stdout)["hookSpecificOutput"]["additionalContext"] - - adapter = tmp_path / f".{runtime}/orchestrator/adapter.json" - adapter.parent.mkdir(parents=True) - adapter.write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}, - "guard": {"deny": [{"pattern": "^release-tool publish$", "reason": "release blocked"}]}}), - encoding="utf-8") - state = tmp_path / "state" - state.mkdir() - (state / "ACTIVE").write_text(json.dumps({"id": "garden", "session": session}), encoding="utf-8") - tool["cwd"] = str(tmp_path) - result = run("PreToolUse", tool) - assert result.returncode == 0, result.stderr - decision = json.loads(result.stdout)["hookSpecificOutput"] - assert decision["permissionDecision"] == "deny" - assert "release blocked" in decision["permissionDecisionReason"] - - # Chef's guard uses a JSON denial. Exercise the host's other denial protocol - # through the same configured command, including byte-for-byte stdio. - (plugin / "hooks/mission_guard.py").write_text( - "import sys\nsys.stdout.buffer.write(sys.stdin.buffer.read())\n" - "sys.stderr.buffer.write(b'fixture denial')\nsys.exit(2)\n", encoding="utf-8", - ) - denied = run("PreToolUse", tool) - assert denied.returncode == 2 - assert denied.stdout == json.dumps(tool).encode() - assert denied.stderr == b"fixture denial" - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX hook launcher") -def test_posix_hook_launcher_returns_the_denial_without_retrying(tmp_path): - bin_dir = tmp_path / "bin" - bin_dir.mkdir() - (bin_dir / "python3").symlink_to(sys.executable) - fallback = bin_dir / "python" - fallback.write_text("#!/bin/sh\necho unexpected fallback >&2\nexit 0\n", encoding="utf-8") - fallback.chmod(0o700) - script = tmp_path / "hook with spaces.py" - script.write_text("import sys\nassert sys.stdin.read() == 'payload'\nsys.exit(2)\n", encoding="utf-8") - result = subprocess.run( - ["/bin/sh", str(PLUGIN_ROOT / "hooks/run-python.sh"), str(script)], - env={**os.environ, "PATH": str(bin_dir)}, input="payload", capture_output=True, text=True, timeout=20, - ) - assert result.returncode == 2 - assert result.stderr == "" - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX alias") -def test_python_alias_is_stable_and_does_not_overwrite_an_existing_file(tmp_path): - first = python_environment({"PATH": "/fictional"}, cache_root=tmp_path) - assert first == python_environment({"PATH": "/fictional"}, cache_root=tmp_path) - alias = Path(first["PATH"].split(os.pathsep)[0]) / "python" - alias.unlink() - alias.write_text("user file", encoding="utf-8") - with pytest.raises(ValueError, match="another target"): - python_environment({"PATH": "/fictional"}, cache_root=tmp_path) - assert alias.read_text() == "user file" - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX launcher") -def test_python_launcher_preserves_virtual_environment_prefix(tmp_path): - env = python_environment(cache_root=tmp_path) - result = subprocess.check_output([shutil.which("python", path=env["PATH"]), "-c", "import sys; print(sys.prefix)"], - env=env, text=True, timeout=15) - assert result.strip() == sys.prefix - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX launcher") -def test_concurrent_python_launcher_publication_is_complete(tmp_path): - with ThreadPoolExecutor(max_workers=8) as pool: - environments = list(pool.map(lambda _: python_environment({"PATH": "/fixture"}, cache_root=tmp_path), range(16))) - assert all(env == environments[0] for env in environments) - assert not list(tmp_path.rglob(".python-*")) - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX cache node types and permissions") -def test_python_launcher_rejects_special_files_and_writable_cache(tmp_path): - env = python_environment(cache_root=tmp_path) - directory = Path(env["PATH"].split(os.pathsep)[0]) - alias = directory / "python" - alias.unlink() - os.mkfifo(alias) - with pytest.raises(ValueError, match="another target"): - python_environment(cache_root=tmp_path) - alias.unlink() - directory.chmod(0o777) - with pytest.raises(ValueError, match="owned directory"): - python_environment(cache_root=tmp_path) - - -def test_runtime_entrypoint_is_available_from_an_installed_tree(tmp_path): - plugin = tmp_path / "plugin" - shutil.copytree(PLUGIN_ROOT, plugin, ignore=shutil.ignore_patterns("__pycache__")) - result = subprocess.run([sys.executable, "-I", str(plugin / "runtime.py"), "--help"], - capture_output=True, text=True, timeout=30, cwd=tmp_path) - assert result.returncode == 0, result.stderr - assert "hermes" in result.stdout and "codex" in result.stdout diff --git a/tests/fixtures/guard_commands.json b/tests/fixtures/guard_commands.json new file mode 100644 index 0000000..1e5d290 --- /dev/null +++ b/tests/fixtures/guard_commands.json @@ -0,0 +1,157 @@ +{ + "deny": [ + "p4 submit -c 123", + "P4.EXE SUBMIT -c 1", + "CLI=Tool/VcsWrapper/vcs-wrapper.exe\n$CLI pending submit 123", + "p4 \\\n submit -c 123", + "p4 \\\r\n submit -c 123", + "p4 -c otherclient submit", + "& \"p4.exe\" submit -c 1", + "$P = 'p4'\n& $P submit", + "$CLI = \"Tool/VcsWrapper/vcs-wrapper.exe\"; $CLI pending submit 1", + "x=$(p4 submit -c 1)", + "$out = p4 submit -c 1", + "FOO=1 p4 edit a.cs", + "echo it's here; p4 submit -c 1", + "Tool/VcsWrapper/vcs-wrapper.exe pending submit 123", + "Tool/QualityGate/qualitygate.bat submit 123 --check-only", + "python Tool/cli.py submit 1", + "p4 -x list.txt edit", + "p4 -x list.txt add", + "p4 edit Foo.cs && p4 edit -c 123 Bar.cs", + "p4 revert -c 123 Foo.cs; p4 opened -a Foo.cs", + "p4 revert -a //...", + "Tool/VcsWrapper/vcs-wrapper.exe pending move-files 123 Foo.cs", + "Tool/VcsWrapper/vcs-wrapper.exe workspace delete x", + "vcs-wrapper git pull", + "p4 unshelve -s 9 -f", + "p4 unshelve -s 999 -f -c 123", + "p4 edit -c default Foo.cs", + "p4 obliterate -y //x/...", + "p4 shelve -d -c 1", + "p4 change -d 5", + "p4 changelist -f 5", + "p4 reopen -c 1 a.cs", + "p4 sync", + "p4 flush", + "p4 clean", + "p4 integrate a b", + "p4 protect", + "p4 lock a.cs", + "p4 client -d ws", + "p4 workspace -d ws", + "p4 reconcile Unity/Game/Assets/...", + "p4 rec", + "p4 open Foo.cs", + "p4 rename a b", + "p4 integ a b", + "p4 undo //x/...@1", + "p4 resolve -at", + "p4 resolve -ay", + "p4 populate //a/... //b/...", + "p4 client -i < spec.txt", + "p4 edit -c a.cs", + "p4 opened & p4 sync", + "echo $(p4 sync)", + "x=`p4 sync`", + "echo `p4 sync`", + "echo \"$(p4 sync)\"", + "cat <(p4 sync)", + "p4 opened -c 1 | xargs p4 revert", + "p4 opened -c 1 | xargs -I {} p4 revert {}", + "cmd /c p4 sync", + "cmd.exe /c \"p4 sync\"", + "env P4CLIENT=x p4 sync", + "nohup p4 sync", + "sudo p4 sync", + "start /b p4 sync", + "powershell -NoProfile -Command \"p4 sync\"", + "powershell.exe -NoProfile -ExecutionPolicy Bypass -c \"p4 sync; echo done\"", + "pwsh -c \"p4 sync\"", + "bash -c \"p4 sync\"", + "echo \"a\\\"b\"; p4 sync; echo \"x\\\"y\"", + "p4 -x \"C:/my list.txt\" edit", + "p4 -zprog=x sync", + "C:\\Perforce\\p4.exe sync", + "\"C:\\Program Files\\Perforce\\p4.exe\" sync", + "vcs-wrapper.exe pending submit 123", + "vcs-wrapper-tui pending submit 1", + "vcs-wrapper.exe p4 submit -c 1", + "vcs-wrapper.exe p4 -c 12 submit", + "vcs-wrapper.exe pending new \"fix submit gate\"" + ], + "allow": [ + "p4 edit -c 123 a.cs", + "p4 edit -c $CL a.cs", + "p4 edit -c \"$CL\" A.cs", + "CL=123\np4 edit -c $CL a.cs", + "CL=123; p4 edit -c \"$CL\" a.cs", + "CL=5; p4 edit -c ${CL} a.cs", + "p4 -x list.txt edit -c 12", + "p4 -x C:/tmp/list.txt edit -c 123", + "p4 -x \"C:/my list.txt\" edit -c 123", + "p4 add -c 99 b.cs b.cs.meta", + "p4 shelve -f -c 123", + "p4 opened -a x", + "p4 opened -c 123", + "p4 opened", + "p4 describe -s 1", + "p4 changes -s submitted -m5", + "p4 changes -s pending -c ws-yourname_Main", + "p4 revert -a -c 123", + "p4 diff -du Wiki/common/perforce-workflow.md", + "p4 -F \"%depotFile%\" opened -c 123 | p4 -x - diff -du", + "Build\\project-build.bat code test GameServer", + "Tool\\QualityGate\\qualitygate.bat change-description 1 --description-file x", + "p4 edit -c 123 Unity/Game/Packages/packages-lock.json", + "p4 opened -a Unity/Game/Packages/packages-lock.json", + "p4 fstat //Depot/Main/Code/Admin/x.cs", + "p4 edit -c 123 Code/GameServer/admin/Ops.cs", + "p4 add -c 123 Tool/foo-sync.md", + "p4 edit -c 1 Unity/Game/Assets/HeroArrangeSystem.Sync.cs", + "p4 add -c 123 Wiki/reports/20261015_sync_audit.md", + "Tool/VcsWrapper/vcs-wrapper.exe pending new \"Game mission m1 M1\"", + "Tool/VcsWrapper/vcs-wrapper.exe pending new \"Game mission 20261015-safe-submit-fix M1\"", + "Tool/VcsWrapper/vcs-wrapper.exe desc show 123", + "dotnet run --project Tool/DataTool -- D:/Work/Game_Main", + "p4 reconcile -c 123 Unity/Game/Assets/...", + "p4 rec -c 123 a.cs", + "p4 open -c 12 a.cs", + "p4 resolve -c 123 -am a.cs", + "p4 edit -c123 a.cs", + "p4 add -c99 b.cs", + "p4 revert -a -c123", + "p4 opened 2>&1", + "p4 opened &> out.txt", + "p4 opened >& out.txt", + "p4 changes -m5 &", + "p4 edit -c 1 a.{cs,meta}", + "echo ${CL}", + "cmd /c p4 opened", + "xargs echo", + "echo $(date)" + ], + "powershellDeny": [ + "p4 `\n submit -c 123", + "p4 `\r\n sync", + "dir *.cs | ForEach-Object { p4 edit $_ }", + "Get-ChildItem | % { p4 edit $_.FullName }", + "try { p4 sync } catch {}", + "try{p4 sync}catch{}", + "if ($true) { p4 submit -c 1 }", + "Write-Host (p4 sync)", + "Write-Host \"$(p4 sync)\"", + "echo $(p4 sync)", + "$x = $(p4 sync)", + "$p = 'p4'; & $P sync", + "$p = 'p4'\n& $P sync", + "cd D:\\Work\\x\\\np4 sync", + "& \"C:\\Program Files\\Perforce\\p4.exe\" sync", + "powershell -Command \"& { p4 sync }\"", + "echo \"a`\"b\"; p4 sync; echo \"x`\"y\"" + ], + "powershellAllow": [ + "Get-ChildItem | % { p4 edit -c 123 $_.FullName }", + "Write-Host \"a (p4 sync) b\"" + ] +} diff --git a/tests/fixtures/install_paths.json b/tests/fixtures/install_paths.json new file mode 100644 index 0000000..040388d --- /dev/null +++ b/tests/fixtures/install_paths.json @@ -0,0 +1,19 @@ +[ + "skills/mission/scripts/mission_state.py", + "codex/skills/chef-mission/scripts/mission_state.py", + "skills/slots/scripts/slots.py", + "codex/skills/chef-slots/scripts/slots.py", + "skills/slots/scripts/dashboard.py", + "codex/skills/chef-slots/scripts/dashboard.py", + "skills/doctor/scripts/doctor.py", + "codex/skills/chef-doctor/scripts/doctor.py", + "skills/distill/scripts/distill.py", + "codex/skills/chef-distill/scripts/distill.py", + "skills/mission/scripts/p4c.py", + "codex/skills/chef-mission/scripts/p4c.py", + "grok/skills/chef-mission/scripts/p4c.py", + "skills/mission/scripts/check_human_doc.py", + "skills/mission/scripts/run_metrics.py", + "skills/mission/scripts/task_queue.py", + "skills/mission/scripts/model_recommendations.py" +] diff --git a/tests/fixtures/required_contracts.json b/tests/fixtures/required_contracts.json new file mode 100644 index 0000000..02f993e --- /dev/null +++ b/tests/fixtures/required_contracts.json @@ -0,0 +1,17 @@ +{ + "guardGroups": [ + "deny", + "allow", + "powershellDeny", + "powershellAllow" + ], + "verificationInvalidations": [ + "input_change", + "command_change" + ], + "slotRefusals": [ + "malformed_name", + "outside_root", + "lock_held" + ] +} diff --git a/tests/integration/codex/test_codex.py b/tests/integration/codex/test_codex.py deleted file mode 100644 index 1b39a81..0000000 --- a/tests/integration/codex/test_codex.py +++ /dev/null @@ -1,623 +0,0 @@ -import json -import os -import shutil -import subprocess -import sys -from pathlib import Path - -import pytest -from chef.guards import adapters as guard_adapters - -from tests.paths import PLUGIN_ROOT -from tests.transition_support import run_lifecycle_hook - -PLUGIN = PLUGIN_ROOT - -from chef.guards import mission as mission_guard -from chef.runtimes import session as session_rules -from chef.slots import commands as slots - - -@pytest.fixture(autouse=True) -def isolated_codex_environment(monkeypatch, tmp_path): - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", raising=False) - monkeypatch.delenv("CODEX_HOME", raising=False) - monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) - - -@pytest.fixture -def project(tmp_path, monkeypatch): - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) - folder = tmp_path / "project" - adapter_dir = folder / ".codex/orchestrator" - adapter_dir.mkdir(parents=True) - adapter = { - "schema": 1, - "project": "test", - "paths": {"stateDir": "state"}, - "guard": {"deny": [{"pattern": r"^p4\s+(submit|sync)\b", "reason": "blocked"}]}, - "slots": { - "enabled": True, - "root": str(tmp_path / "slots"), - "client": "test_{name}", - "names": ["slot1"], - "prepare": [{"id": "claude", "run": "echo claude"}], - }, - "runtimes": {"codex": {"slots": {"prepare": [{"id": "codex", "run": "echo codex"}]}}}, - } - (adapter_dir / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - return folder - - -def hook(project, command, session="parent", **fields): - payload = { - "hook_event_name": "PreToolUse", - "tool_name": "Bash", - "cwd": str(project), - "session_id": session, - "tool_input": {"command": command}, - **fields, - } - done = run_lifecycle_hook(PLUGIN / "codex/mission_guard.py", payload) - assert done.returncode == 0, done.stderr - return json.loads(done.stdout or b"{}") - - -def denied(output): - return output.get("hookSpecificOutput", {}).get("permissionDecision") == "deny" - - -def test_codex_mission_lifecycle_and_session_scope(project, monkeypatch): - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project.parent / "other")) - opened = hook(project, "echo han-mission open test") - assert "켜짐" in opened["systemMessage"] - active = project / "state/ACTIVE" - assert json.loads(active.read_text())["session"] == "parent" - assert denied(hook(project, "p4 submit -c 123", agent_id="child", agent_type="default")) - assert not denied(hook(project, "p4 opened -c 123")) - assert not denied(hook(project, "p4 submit -c 123", session="other")) - allowance = project / "state/test/allow-once" - allowance.parent.mkdir(exist_ok=True) - allowance.write_text("p4 sync\n", encoding="utf-8") - assert not denied(hook(project, "p4 sync")) - assert denied(hook(project, "p4 sync")) - assert not denied(hook(project, "echo han-mission close test")) - assert not active.exists() - assert not allowance.exists() - - -def test_codex_shell_normalization_and_command_cwd(project): - hook(project, "echo han-mission open test") - payload = {"command": "$tool = 'p4'\n& $tool `\n sync", "shell": "pwsh"} - assert denied(hook(project, "", tool_input=payload)) - assert denied(hook(project.parent, "", tool_input={"command": "p4 sync", "cwd": str(project)})) - assert denied(hook(project, "echo han-mission close test; p4 sync")) - assert (project / "state/ACTIVE").exists() - - -def test_codex_adapter_precedence_and_shared_fallback(project, monkeypatch): - claude = project / ".claude/orchestrator" - claude.mkdir(parents=True) - adapter = claude / "adapter.json" - adapter.write_text('{"schema":1}', encoding="utf-8") - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project.parent)) - payload = {"cwd": str(project), "han_runtime": "codex"} - assert Path(mission_guard.find_adapter(payload).adapter_path).parent.name == "orchestrator" - assert ".codex" in mission_guard.find_adapter(payload).adapter_path - (project / ".codex/orchestrator/adapter.json").unlink() - assert Path(mission_guard.find_adapter(payload).adapter_path) == adapter - - -def test_runtime_overlay_and_local_precedence(project, monkeypatch): - path = project / ".codex/orchestrator/adapter.json" - local = {"project": "local", "runtimes": {"codex": {"project": "codex-local"}}} - (path.parent / "local.json").write_text(json.dumps(local), encoding="utf-8") - claude = mission_guard.load_adapter(str(path)) - codex = mission_guard.load_adapter(str(path), runtime="codex") - assert claude["project"] == "local" - assert claude["slots"]["prepare"][0]["id"] == "claude" - assert codex["project"] == "codex-local" - assert codex["slots"]["prepare"][0]["id"] == "codex" - config = slots.Config(mission_guard.Located(str(project), str(path)), codex, "codex") - monkeypatch.setattr(slots.shutil, "which", lambda name: name) - assert "memoryDir" not in config.values("slot1") - command = slots.wt_command(config, "slot1", "task; more") - assert command[-4:] == ["codex", "-c", "model_auto_compact_token_limit=200000", "$chef:chef-mission task\\; more"] - config = slots.Config(mission_guard.Located(str(project), str(path)), claude, "claude") - command = slots.wt_command(config, "slot1", "task") - assert command[command.index("claude"):][:5] == ["claude", "--autocompact", "500000", "-n", "slot1: task"] - assert command[-2:] == ["--", "/chef:mission task"] - assert "--mcp-config" not in command and "--dangerously-load-development-channels" not in command - - -def test_codex_registry_ignores_claude_configuration(tmp_path, monkeypatch): - registry = tmp_path / "registry" - registry.mkdir() - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - monkeypatch.setenv("CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "wrong") - assert mission_guard.resolve_registry("codex").path == str(registry) - monkeypatch.delenv("HAN_ADAPTERS_DIR") - assert mission_guard.resolve_registry("codex").source != "userConfig" - - -def test_codex_registry_uses_config_after_environment(tmp_path, monkeypatch): - env_registry = tmp_path / "env-registry" - config_registry = tmp_path / "config-registry" - config_home = tmp_path / "codex-home" - config_home.mkdir() - (config_home / "config.toml").write_text( - f'[shell_environment_policy.set]\nHAN_ADAPTERS_DIR = "{config_registry.as_posix()}"\n', encoding="utf-8" - ) - monkeypatch.setenv("CODEX_HOME", str(config_home)) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(env_registry)) - choice = mission_guard.resolve_registry("codex") - assert choice == mission_guard.Registry(str(env_registry), "env") - monkeypatch.delenv("HAN_ADAPTERS_DIR") - choice = mission_guard.resolve_registry("codex") - assert choice == mission_guard.Registry(str(config_registry), "codexConfig") - - -def test_codex_registry_reads_default_home_config(tmp_path, monkeypatch): - config_home = tmp_path / "home" - codex_home = config_home / ".codex" - codex_home.mkdir(parents=True) - registry = tmp_path / "registry" - (codex_home / "config.toml").write_text( - f'[shell_environment_policy.set]\nHAN_ADAPTERS_DIR = "{registry.as_posix()}"\n', encoding="utf-8" - ) - monkeypatch.delenv("CODEX_HOME", raising=False) - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - - def expand_home(path): - if path == "~": - return str(config_home) - return path - - monkeypatch.setattr(os.path, "expanduser", expand_home) - choice = mission_guard.resolve_registry("codex") - assert choice == mission_guard.Registry(str(registry), "codexConfig") - - -def test_codex_registry_empty_or_missing_config_falls_back(tmp_path, monkeypatch): - config_home = tmp_path / "codex-home" - config_home.mkdir() - monkeypatch.setenv("CODEX_HOME", str(config_home)) - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - monkeypatch.setattr(guard_adapters, "in_place_adapters_dir", lambda: str(tmp_path / "missing")) - assert mission_guard.resolve_registry("codex") == mission_guard.Registry("", "none") - config_path = config_home / "config.toml" - for content in ("", "[shell_environment_policy.set]\n", '[shell_environment_policy.set]\nHAN_ADAPTERS_DIR = ""\n'): - config_path.write_text(content, encoding="utf-8") - assert mission_guard.resolve_registry("codex") == mission_guard.Registry("", "none") - - -def test_codex_environment_registry_bypasses_invalid_config(tmp_path, monkeypatch): - config_home = tmp_path / "codex-home" - config_home.mkdir() - (config_home / "config.toml").write_text("invalid = [", encoding="utf-8") - registry = tmp_path / "registry" - monkeypatch.setenv("CODEX_HOME", str(config_home)) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - assert mission_guard.resolve_registry("codex") == mission_guard.Registry(str(registry), "env") - - -@pytest.mark.parametrize( - "config, message", - [ - ("[shell_environment_policy.set\nHAN_ADAPTERS_DIR = \"x\"", "읽기 실패"), - ('[shell_environment_policy.set]\nHAN_ADAPTERS_DIR = 7\n', "문자열이어야"), - ('shell_environment_policy = "invalid"\n', "shell_environment_policy 는 객체"), - ('[shell_environment_policy]\nset = "invalid"\n', "shell_environment_policy.set 는 객체"), - ], -) -def test_codex_registry_invalid_config_raises_guard_off(tmp_path, monkeypatch, config, message): - config_home = tmp_path / "codex-home" - config_home.mkdir() - (config_home / "config.toml").write_text(config, encoding="utf-8") - monkeypatch.setenv("CODEX_HOME", str(config_home)) - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - with pytest.raises(mission_guard.GuardOff, match=message): - mission_guard.resolve_registry("codex") - - -def test_codex_registry_unreadable_config_raises_guard_off(tmp_path, monkeypatch): - config_home = tmp_path / "codex-home" - config_home.mkdir() - config_path = config_home / "config.toml" - config_path.touch() - original_open = open - - def unreadable(path, *args, **kwargs): - if os.fspath(path) == str(config_path): - raise PermissionError("denied") - return original_open(path, *args, **kwargs) - - monkeypatch.setenv("CODEX_HOME", str(config_home)) - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - monkeypatch.setattr("builtins.open", unreadable) - with pytest.raises(mission_guard.GuardOff, match="읽기 실패"): - mission_guard.resolve_registry("codex") - - -def test_claude_registry_ignores_codex_config(tmp_path, monkeypatch): - config_home = tmp_path / "codex-home" - config_home.mkdir() - registry = tmp_path / "registry" - (config_home / "config.toml").write_text( - f'[shell_environment_policy.set]\nHAN_ADAPTERS_DIR = "{registry.as_posix()}"\n', encoding="utf-8" - ) - monkeypatch.setenv("CODEX_HOME", str(config_home)) - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - monkeypatch.setattr(guard_adapters, "in_place_adapters_dir", lambda: str(tmp_path / "missing")) - assert mission_guard.resolve_registry("claude") == mission_guard.Registry("", "none") - - -def test_installed_codex_hook_uses_config_registry_without_environment(project, tmp_path): - (project / ".codex/orchestrator/adapter.json").unlink() - installed = tmp_path / "installed" / "plugins" / "chef" - (installed / "codex").mkdir(parents=True) - (installed / "hooks").mkdir() - shutil.copytree(PLUGIN / "chef", installed / "chef", ignore=shutil.ignore_patterns("__pycache__")) - shutil.copy2(PLUGIN / "codex/mission_guard.py", installed / "codex/mission_guard.py") - shutil.copy2(PLUGIN / "mission_control.py", installed / "mission_control.py") - shutil.copy2(PLUGIN / "hooks/mission_guard.py", installed / "hooks/mission_guard.py") - shutil.copy2(PLUGIN / "hooks/mission_entry.py", installed / "hooks/mission_entry.py") - shutil.copy2(PLUGIN / "hooks/question_write_guard.py", installed / "hooks/question_write_guard.py") - shutil.copy2(PLUGIN / "hooks/hook_runtime.py", installed / "hooks/hook_runtime.py") - registry = tmp_path / "registry" - adapter_dir = registry / "test" - adapter_dir.mkdir(parents=True) - (registry / "projects.json").write_text( - json.dumps([{"adapter": "test", "roots": [str(project)]}]), encoding="utf-8" - ) - (adapter_dir / "adapter.json").write_text( - json.dumps( - { - "schema": 1, - "paths": {"stateDir": str(tmp_path / "state")}, - "guard": {"deny": [{"pattern": r"^p4\s+submit\b", "reason": "blocked"}]}, - } - ), - encoding="utf-8", - ) - config_home = tmp_path / "codex-home" - config_home.mkdir() - (config_home / "config.toml").write_text( - f'[shell_environment_policy.set]\nHAN_ADAPTERS_DIR = "{registry.as_posix()}"\n', encoding="utf-8" - ) - env = {key: value for key, value in os.environ.items() if key != "HAN_ADAPTERS_DIR"} - env["CODEX_HOME"] = str(config_home) - hook_path = installed / "codex/mission_guard.py" - payload = {"tool_name": "Bash", "cwd": str(project), "session_id": "installed-session"} - opened = run_lifecycle_hook(hook_path, - {**payload, "tool_input": {"command": "echo han-mission open test"}}, env=env) - assert "켜짐" in json.loads(opened.stdout)["systemMessage"] - denied_submit = subprocess.run( - [sys.executable, "-B", str(hook_path)], - input=json.dumps({**payload, "tool_input": {"command": "p4 submit -c 1"}}).encode(), - capture_output=True, - env=env, - check=True, - timeout=15, - ) - assert denied(json.loads(denied_submit.stdout)) - active = json.loads((tmp_path / "state/ACTIVE").read_text(encoding="utf-8")) - assert active["id"] == "test" and active["session"] == "installed-session" - - -def test_codex_session_context_does_not_export_claude_env(tmp_path, monkeypatch): - env_file = tmp_path / "env" - monkeypatch.setenv("CLAUDE_ENV_FILE", str(env_file)) - monkeypatch.setenv("CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "wrong") - assert session_rules.decide({"hook_event_name": "SessionStart"}, "codex") == {} - assert not env_file.exists() - - -@pytest.mark.parametrize("disable", ["0", "1"]) -def test_codex_transcript_context_ignores_legacy_rules_settings(tmp_path, monkeypatch, disable): - env_file = tmp_path / "claude-env" - monkeypatch.setenv("CLAUDE_ENV_FILE", str(env_file)) - monkeypatch.setenv("HAN_CODEX_INJECT_RULES", "shared") - monkeypatch.setenv("HAN_RULES_DISABLE", disable) - transcript = 'C:/대화 기록/quoted "session".jsonl' - payload = {"hook_event_name": "SessionStart", "transcript_path": transcript} - output = session_rules.decide(payload, "codex") - assert output["hookSpecificOutput"] == { - "hookEventName": "SessionStart", - "additionalContext": f"chef-distill 대화 기록 경로 (--transcript): {json.dumps(transcript, ensure_ascii=False)}", - } - assert session_rules.decide({**payload, "hook_event_name": "SubagentStart"}, "codex") == {} - assert not env_file.exists() - - -def test_codex_entrypoints_resolve_shared_code_from_another_cwd(project): - for relative, arguments in [ - ("chef-slots/scripts/slots.py", ["--project", str(project), "create", "slot1", "--dry-run"]), - ("chef-adapter-init/scripts/check_guard.py", ["--doctor"]), - ("chef-slots/scripts/dashboard.py", ["--help"]), - ]: - result = subprocess.run( - [sys.executable, str(PLUGIN / "codex/skills" / relative), *arguments], - cwd=project, - capture_output=True, - timeout=20, - ) - assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace") - if relative == "chef-slots/scripts/slots.py": - assert "echo codex" in result.stdout.decode("utf-8") - assert not (project.parent / "slots").exists() - - -@pytest.mark.parametrize("interpreter", ["python", "python3"]) -def test_check_guard_doctor_accepts_either_path_name(monkeypatch, capsys, interpreter): - from chef.cli import check_guard - - resolved = str(Path(sys.executable).with_name(interpreter)) - monkeypatch.setattr(check_guard.shutil, "which", lambda name: resolved if name == interpreter else None) - monkeypatch.setattr(check_guard.subprocess, "run", lambda argv, **_: subprocess.CompletedProcess( - argv, 0, b"Python 3.12.0\n", b"", - )) - assert check_guard.doctor() == 0 - assert f"python={resolved}" in capsys.readouterr().out - - -def test_codex_mission_state_entrypoint_resolves_shared_code_from_another_cwd(project): - hook(project, "echo han-mission open test", transcript_path="C:/t/parent.jsonl") - script = PLUGIN / "codex/skills/chef-mission/scripts/mission_state.py" - outputs = [] - for arguments in (["init", "--goal", "목표"], ["mission", "set", "--stage", "impl"], ["status"]): - result = subprocess.run( - [sys.executable, "-B", str(script), "--project", str(project), *arguments], - cwd=project.parent, - capture_output=True, - timeout=20, - ) - assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace") - outputs.append(result.stdout.decode("utf-8")) - folder = project / "state/test" - assert "상태: 진행" in (folder / "mission.md").read_text(encoding="utf-8") - assert "현재 단계 impl" in outputs[2] - assert "C:/t/parent.jsonl" in (folder / "sessions.tsv").read_text(encoding="utf-8") - - -def test_codex_status_reads_unshared_questions_without_a_valid_manifest(project): - hook(project, "echo han-mission open test") - script = PLUGIN / "codex/skills/chef-mission/scripts/mission_state.py" - command = [sys.executable, "-B", str(script), "--project", str(project)] - initialized = subprocess.run([*command, "init"], cwd=project.parent, capture_output=True, timeout=20) - assert initialized.returncode == 0, initialized.stderr.decode("utf-8", errors="replace") - folder = project / "state/test" - record = { - "schema": 1, "id": "ask-7", "revision": 1, "title": "질문", "intro": "", "body": "", - "items": [{"id": "1", "title": "진행할까요?", "body": "", "status": "pending", "answer": ""}], - "approval": {"status": "none", "reason": ""}, "answers": [], - } - draft = project / "question.json" - draft.write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8") - published = subprocess.run([*command, "question", "publish", "--input", str(draft)], - cwd=project.parent, capture_output=True, timeout=20) - assert published.returncode == 0, published.stderr.decode("utf-8", errors="replace") - (folder / "shared-documents.tsv").write_text("잘못된 헤더\n", encoding="utf-8") - pending = subprocess.run([*command, "status"], cwd=project.parent, capture_output=True, timeout=20) - assert pending.returncode == 0, pending.stderr.decode("utf-8", errors="replace") - assert "ask-7.md 답 없음" in pending.stdout.decode("utf-8") - reply = project / "reply.json" - reply.write_text(json.dumps({ - "schema": 1, "id": "reply-1", "revision": 1, "at": "2026-10-26", "text": "권장안 승인", - "updates": [{"id": "1", "status": "answered", "answer": "권장안 승인"}], - }, ensure_ascii=False), encoding="utf-8") - saved = subprocess.run([*command, "question", "answer", "ask-7.md", "--input", str(reply)], - cwd=project.parent, capture_output=True, timeout=20) - assert saved.returncode == 0, saved.stderr.decode("utf-8", errors="replace") - answered = subprocess.run([*command, "status"], cwd=project.parent, capture_output=True, timeout=20) - assert answered.returncode == 0, answered.stderr.decode("utf-8", errors="replace") - assert "걸린 것: 없음" in answered.stdout.decode("utf-8") - (folder / "ask-legacy.md").write_text("# 질문\n\n## 답\n\n2026-10-26 권장\n", encoding="utf-8") - legacy = subprocess.run([*command, "status"], cwd=project.parent, capture_output=True, timeout=20) - assert legacy.returncode == 0, legacy.stderr.decode("utf-8", errors="replace") - assert "ask-legacy.md 기록 확인 필요" in legacy.stdout.decode("utf-8") - assert "답 없음" not in legacy.stdout.decode("utf-8") - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_hook_registration_keeps_session_paths_guards_and_integrity(runtime): - path = PLUGIN / ("hooks/hooks.json" if runtime == "claude" else "codex/hooks.json") - hooks = json.loads(path.read_text(encoding="utf-8"))["hooks"] - for event in ("PreToolUse",): - matchers = {entry.get("matcher", "") for entry in hooks[event]} - for tool in ("Bash", "PowerShell", "Write", "Edit", "MultiEdit", "NotebookEdit", "apply_patch", "ApplyPatch"): - assert any(tool in matcher.split("|") for matcher in matchers) - for event in ("Stop",): - commands = [json.dumps(hook) for entry in hooks[event] for hook in entry["hooks"]] - assert any("question_integrity.py" in command for command in commands) - assert all(not hook.get("async", False) for entry in hooks[event] for hook in entry["hooks"]) - assert set(hooks) == {"SessionStart", "PreToolUse", "Stop"} - assert sum(len(entry["hooks"]) for entries in hooks.values() for entry in entries) == 4 - for removed in ("korean_reply.py", "memory_notice.py", "session_title.py"): - assert removed not in json.dumps(hooks) - assert not (PLUGIN / "hooks" / removed).exists() - assert not (PLUGIN / "codex" / removed).exists() - assert "mission_guard.py" in json.dumps(hooks["PreToolUse"]) - assert "subagent_allow.py" in json.dumps(hooks["PreToolUse"]) - assert "session_rules.py" in json.dumps(hooks["SessionStart"]) - - -@pytest.mark.parametrize("event,tool_name", [("Stop", ""), ("Stop", "Bash"), ("Stop", "apply_patch")]) -def test_installed_codex_integrity_uses_config_registry_read_only(project, tmp_path, event, tool_name): - (project / ".codex/orchestrator/adapter.json").unlink() - installed = tmp_path / "installed/plugins/chef" - shutil.copytree(PLUGIN, installed, ignore=shutil.ignore_patterns( - "__pycache__", ".pytest_cache", "pytest-cache-files-*", "*.pyc", - )) - registry = tmp_path / "registry" - adapter = registry / "fictional/adapter.json" - adapter.parent.mkdir(parents=True) - (registry / "projects.json").write_text(json.dumps([{"adapter": "fictional", "roots": [str(project)]}]), encoding="utf-8") - adapter.write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}}), encoding="utf-8") - config_home = tmp_path / "codex-config" - config_home.mkdir() - (config_home / "config.toml").write_text(f'[shell_environment_policy.set]\nHAN_ADAPTERS_DIR = "{registry.as_posix()}"\n', encoding="utf-8") - folder = project / "state/fictional-mission" - folder.mkdir(parents=True) - (folder.parent / "ACTIVE").write_text(json.dumps({"id": folder.name, "session": "owner"}), encoding="utf-8") - (folder / "ask-colors.md").write_text("# Fictional garden palette\n\nUse blue.\n", encoding="utf-8") - log = tmp_path / "guard-log.jsonl" - env = {key: value for key, value in os.environ.items() if key not in ("HAN_ADAPTERS_DIR", "HAN_REPO", "CLAUDE_PROJECT_DIR")} - env.update(CODEX_HOME=str(config_home), HAN_GUARD_LOG=str(log)) - payload = {"hook_event_name": event, "tool_name": tool_name, "session_id": "owner", "agent_id": "child", "cwd": str(project), - "tool_input": {"command": "*** Begin Patch\n*** End Patch"}, "stop_hook_active": False} - - def run(fields): - done = subprocess.run([sys.executable, str(installed / "codex/question_integrity.py")], input=json.dumps(fields).encode(), - capture_output=True, check=True, env=env, timeout=15) - return json.loads(done.stdout or b"{}") - - before = {str(path): (path.read_bytes(), path.stat().st_mtime_ns) for path in folder.parent.rglob("*") if path.is_file()} - output = run(payload) - assert "decision" not in output and "ask-colors.md" in output["systemMessage"] - assert run({**payload, "stop_hook_active": True}) == {} - if event == "PostToolUse": - assert output["hookSpecificOutput"]["hookEventName"] == event - assert run({**payload, "session_id": "unrelated"}) == {} - after = {str(path): (path.read_bytes(), path.stat().st_mtime_ns) for path in folder.parent.rglob("*") if path.is_file()} - assert after == before - assert not log.exists() - assert not list(installed.rglob("__pycache__")) - - -@pytest.fixture -def shared_docs(): - import importlib.util - - spec = importlib.util.spec_from_file_location("sync_shared", PLUGIN_ROOT.parent.parent / "tools/check_shared.py") - sync = importlib.util.module_from_spec(spec) - spec.loader.exec_module(sync) - return sync - - -def test_shared_references_are_pointers_to_single_source(shared_docs): - files = list(shared_docs.shared_files()) - assert len(files) >= 10 - assert any(t.endswith("human-writing.md") for _, t in files) - assert shared_docs.differing() == [], "python codex/sync_shared.py --write" - assert shared_docs.contract_errors() == [] - for source, target in files: - assert Path(source).read_text(encoding="utf-8") != Path(target).read_text(encoding="utf-8") - - -def test_shared_reference_check_detects_missing_or_copied_pointer(shared_docs, tmp_path, monkeypatch): - source = tmp_path / "skills/mission/references/human-writing.md" - source.parent.mkdir(parents=True) - source.write_text("# Source\n", encoding="utf-8") - target = tmp_path / "codex/skills/chef-mission/references/human-writing.md" - monkeypatch.setattr(shared_docs, "ROOT", str(tmp_path)) - assert shared_docs.differing() == [(str(source), str(target))] - target.parent.mkdir(parents=True) - target.write_text(source.read_text(encoding="utf-8"), encoding="utf-8") - assert shared_docs.differing() == [(str(source), str(target))] - target.write_text(shared_docs.pointer_text(str(source), str(target)), encoding="utf-8") - assert shared_docs.differing() == [] - - -@pytest.fixture -def shared_doc_tree(shared_docs, tmp_path, monkeypatch): - plugin = tmp_path / "plugin" - shutil.copytree(PLUGIN, plugin, ignore=shutil.ignore_patterns("__pycache__")) - monkeypatch.setattr(shared_docs, "ROOT", str(plugin)) - return plugin - - -def test_shared_skill_check_rejects_missing_canonical_or_wrong_entrypoint(shared_docs, shared_doc_tree): - plugin = shared_doc_tree - assert shared_docs.contract_errors() == [] - canonical = plugin / "shared/skills/mission.md" - canonical.unlink() - assert any("shared/skills/mission.md" in error for error in shared_docs.contract_errors()) - canonical.write_text("# Common mission\n", encoding="utf-8") - entrypoint = plugin / "grok/skills/chef-mission/SKILL.md" - entrypoint.write_text("# Detached runtime copy\n", encoding="utf-8") - assert any("공통 절차 링크 없음" in error and "grok/skills/chef-mission/SKILL.md" in error - for error in shared_docs.contract_errors()) - entrypoint.write_text("[공통 절차](../../../shared/skills/mission.md)\n\n" + canonical.read_text(encoding="utf-8"), encoding="utf-8") - assert any("공통 본문 중복" in error for error in shared_docs.contract_errors()) - - -@pytest.mark.parametrize("name", ["question.json", "units.tsv", "ledger.tsv", "decisions.tsv", "obsolete.md"]) -def test_shared_reference_check_rejects_unmanaged_runtime_copy(shared_docs, shared_doc_tree, name): - reference = shared_doc_tree / "codex/skills/chef-mission/references/templates" / name - reference.write_text("unmanaged runtime copy\n", encoding="utf-8") - assert shared_docs.obsolete_reference_files() == [str(reference)] - assert any("불필요한 참조 사본" in error and name in error for error in shared_docs.contract_errors()) - - -@pytest.mark.parametrize("scope", ["section", "paragraph", "whitespace"]) -def test_shared_skill_check_rejects_partial_prose_copy(shared_docs, shared_doc_tree, scope): - source = (shared_doc_tree / "shared/skills/mission.md").read_text(encoding="utf-8") - section = source.split("## 5. 구현 진행", 1)[1].split("## 6.", 1)[0] - paragraph = section.split("\n\n", 2)[1] - copied = section - if scope == "paragraph": - copied = paragraph - elif scope == "whitespace": - copied = " \n ".join(paragraph.split()) - target = shared_doc_tree / "grok/skills/chef-mission/SKILL.md" - target.write_text(target.read_text(encoding="utf-8") + "\n" + copied, encoding="utf-8") - assert any("공통 문단 중복" in error and "grok/skills/chef-mission/SKILL.md" in error - for error in shared_docs.contract_errors()) - - -def test_shared_skill_check_does_not_treat_code_examples_as_shared_prose(shared_docs, shared_doc_tree): - source = (shared_doc_tree / "shared/skills/mission.md").read_text(encoding="utf-8") - code = "```" + source.split("```", 2)[1] + "```" - target = shared_doc_tree / "grok/skills/chef-mission/SKILL.md" - target.write_text(target.read_text(encoding="utf-8") + "\n" + code, encoding="utf-8") - assert shared_docs.contract_errors() == [] - - -def test_shared_reference_check_includes_claude_usage_links(shared_docs, shared_doc_tree): - source = shared_doc_tree / "skills/mission/references/claude-usage.md" - source.write_text(source.read_text(encoding="utf-8") + "\n[missing](unregistered-target.md)\n", encoding="utf-8") - assert any("claude-usage.md -> unregistered-target.md" in error for error in shared_docs.contract_errors()) - - -def test_codex_role_definitions_are_listed_and_review_inherits_the_model(): - import tomllib - - roles = (PLUGIN / "codex/skills/chef-mission/references/codex-roles.md").read_text(encoding="utf-8") - for path in sorted((PLUGIN / "codex/agents").glob("*.toml")): - definition = tomllib.loads(path.read_text(encoding="utf-8")) - assert definition["name"].startswith("chef:") - assert path.name == "chef-" + definition["name"].split(":", 1)[1] + ".toml" - assert definition["description"] and definition["developer_instructions"].strip() - assert f"codex/agents/{path.name}" in roles - reviewer = tomllib.loads((PLUGIN / "codex/agents/chef-code-reviewer.toml").read_text(encoding="utf-8")) - assert reviewer["name"] == "chef:code-reviewer" - assert "model" not in reviewer and "model_reasoning_effort" not in reviewer - assert "읽기 전용" in reviewer["description"] - - -def test_codex_reviewer_small_is_pinned_and_listed_with_routing(): - import tomllib - - small = tomllib.loads((PLUGIN / "codex/agents/chef-reviewer-small.toml").read_text(encoding="utf-8")) - assert small["name"] == "chef:reviewer-small" - assert small["model"] == "gpt-6.1-terra" and small["model_reasoning_effort"] == "high" - assert "읽기 전용" in small["description"] - assert "변경 전 본과의 diff" in small["developer_instructions"] - roles = (PLUGIN / "codex/skills/chef-mission/references/codex-roles.md").read_text(encoding="utf-8") - assert "codex/agents/chef-reviewer-small.toml" in roles - assert "config/defaults.json" in roles and "chef config show --runtime codex" in roles - assert "변경 전 본 대비 diff" in roles - mission = (PLUGIN / "codex/skills/chef-mission/SKILL.md").read_text(encoding="utf-8") - assert "chef:reviewer-small" in mission and "roles.reviewSmall" in mission and "변경 전 본 대비 diff" in mission - - -def test_claude_code_reviewer_is_read_only_deep_reviewer(): - text = (PLUGIN / "agents/code-reviewer.md").read_text(encoding="utf-8").replace("\r\n", "\n") - fields = dict(line.split(": ", 1) for line in text.split("---", 2)[1].strip().splitlines()) - assert fields["name"] == "code-reviewer" - assert fields["model"] == "claude-opus-5-5" and fields["effort"] == "high" - assert {tool.strip() for tool in fields["tools"].split(",")} == {"Read", "Grep", "Glob", "Bash", "PowerShell"} - assert "reviewer-small" in fields["description"] diff --git a/tests/integration/codex/test_codex_entry.py b/tests/integration/codex/test_codex_entry.py new file mode 100644 index 0000000..f74a15f --- /dev/null +++ b/tests/integration/codex/test_codex_entry.py @@ -0,0 +1,19 @@ +"""Codex locates its own adapter directory.""" +import json + +from chef.slots import commands as slots + +from tests.support import isolate + + +def test_codex_locate_reads_the_codex_adapter(tmp_path, monkeypatch): + isolate(monkeypatch, tmp_path) + root = tmp_path / "project" + adapter = root / ".codex/orchestrator" + adapter.mkdir(parents=True) + (adapter / "adapter.json").write_text(json.dumps({ + "schema": 1, "project": "FAKE", "paths": {"stateDir": "_My/missions"}, + }), encoding="utf-8") + located = slots.locate(str(root), "codex") + assert located.adapter_path.endswith("adapter.json") + assert ".codex" in located.adapter_path.replace("\\", "/") diff --git a/tests/integration/distill/test_distill.py b/tests/integration/distill/test_distill.py deleted file mode 100644 index 8bac981..0000000 --- a/tests/integration/distill/test_distill.py +++ /dev/null @@ -1,450 +0,0 @@ -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest -from chef.cli import distill as distill - -from tests.paths import PLUGIN_ROOT - - -def user(text, ts, **flags): - return {"type": "user", "timestamp": ts, "message": {"role": "user", "content": text}, **flags} - - -def assistant(content, ts="2026-10-19T00:00:00.000Z"): - if isinstance(content, str): - content = [{"type": "text", "text": content}] - return {"type": "assistant", "timestamp": ts, "message": {"role": "assistant", "content": content}} - - -def write_transcript(path, entries, raw=()): - lines = [json.dumps(e, ensure_ascii=False) for e in entries] - lines.extend(raw) - path.write_text("\n".join(lines) + "\n", encoding="utf-8") - return path - - -@pytest.fixture -def env(tmp_path, capsys, monkeypatch): - monkeypatch.setenv("HAN_DISTILL_LOG", str(tmp_path / "log.tsv")) - monkeypatch.delenv("HAN_TRANSCRIPT", raising=False) - - class Env: - root = tmp_path - log = tmp_path / "log.tsv" - out = tmp_path / "out.md" - - def run(self, *args): - capsys.readouterr() - code = distill.main(list(args)) - captured = capsys.readouterr() - return code, captured.out.rstrip("\n"), captured.err.rstrip("\n") - - def ok(self, *args): - code, out, err = self.run(*args) - assert code == 0, err - return out - - def fail(self, *args): - code, out, err = self.run(*args) - assert code == 1 and out == "" and "\n" not in err, (code, out, err) - return err - - def extract(self, transcript, *extra): - self.ok("extract", "--transcript", str(transcript), "--out", str(self.out), *extra) - return self.out.read_text(encoding="utf-8") - - return Env() - - -def test_string_and_list_content_become_messages(env): - path = write_transcript( - env.root / "s1.jsonl", - [ - user("문자열 메시지", "2026-10-19T01:00:00.000Z"), - user( - [ - {"type": "image", "source": {}}, - {"type": "text", "text": "이미지 설명"}, - {"type": "tool_result", "content": "무시"}, - {"type": "text", "text": "이어서"}, - ], - "2026-10-19T02:00:00.000Z", - ), - user([{"type": "tool_result", "content": "결과만"}], "2026-10-19T03:00:00.000Z"), - ], - ) - text = env.extract(path) - assert "## s1" in text - assert "### 1 · 2026-10-19T01:00:00.000Z\n사용자: 문자열 메시지" in text - assert "### 2 · 2026-10-19T02:00:00.000Z\n사용자: 이미지 설명\n이어서" in text - assert "결과만" not in text and "무시" not in text and "### 3" not in text - - -@pytest.mark.parametrize("flag", ["isMeta", "isCompactSummary", "isSidechain", "isVisibleInTranscriptOnly"]) -def test_flagged_user_entries_are_dropped(env, flag): - path = write_transcript( - env.root / "s1.jsonl", - [user("버릴 것", "2026-10-19T01:00:00.000Z", **{flag: True}), user("남길 것", "2026-10-19T02:00:00.000Z")], - ) - text = env.extract(path) - assert "버릴 것" not in text and "사용자: 남길 것" in text - - -def test_non_user_types_and_broken_lines_are_skipped(env): - path = write_transcript( - env.root / "s1.jsonl", - [{"type": "system", "message": {"content": "시스템"}}, user("진짜", "2026-10-19T01:00:00.000Z")], - raw=["{깨진 줄", "[1, 2]"], - ) - text = env.extract(path) - assert "시스템" not in text and "사용자: 진짜" in text - - -def test_system_reminder_blocks_are_stripped(env): - path = write_transcript( - env.root / "s1.jsonl", - [ - user("앞\n숨김\n뒤", "2026-10-19T01:00:00.000Z"), - user("전부 숨김", "2026-10-19T02:00:00.000Z"), - ], - ) - text = env.extract(path) - assert "사용자: 앞뒤" in text and "숨김" not in text and "### 2" not in text - - -@pytest.mark.parametrize( - "body", - [ - "끝남", - "out", - "err", - "c", - "[Request interrupted by user for tool use]", - " ", - ], -) -def test_discard_prefixes(env, body): - path = write_transcript(env.root / "s1.jsonl", [user(body, "2026-10-19T01:00:00.000Z")]) - assert "###" not in env.extract(path) - - -def test_slash_command_kept_only_with_args(env): - path = write_transcript( - env.root / "s1.jsonl", - [ - user("x\n/x\nY 인자", "2026-10-19T01:00:00.000Z"), - user("x\n/x\n", "2026-10-19T02:00:00.000Z"), - user("/clear", "2026-10-19T03:00:00.000Z"), - ], - ) - text = env.extract(path) - assert "사용자: /x Y 인자" in text and "### 2" not in text - - -def test_previous_assistant_text_tail_folds_and_resets(env): - long = "가" * 400 - path = write_transcript( - env.root / "s1.jsonl", - [ - assistant(f"처음\n\n말 {long}"), - assistant([{"type": "tool_use", "id": "t", "name": "Bash", "input": {}}]), - user("첫", "2026-10-19T01:00:00.000Z"), - user("둘", "2026-10-19T02:00:00.000Z"), - assistant([{"type": "text", "text": "a\nb"}, {"type": "text", "text": "c"}]), - user("셋", "2026-10-19T03:00:00.000Z"), - ], - ) - lines = env.extract(path).splitlines() - first = lines.index("### 1 · 2026-10-19T01:00:00.000Z") - assert lines[first + 1] == "앞 답: > " + "가" * 300 - assert lines[first + 2] == "사용자: 첫" - second = lines.index("### 2 · 2026-10-19T02:00:00.000Z") - assert lines[second + 1] == "사용자: 둘" - third = lines.index("### 3 · 2026-10-19T03:00:00.000Z") - assert lines[third + 1] == "앞 답: > a b c" - - -def test_tool_only_assistant_keeps_previous_text(env): - path = write_transcript( - env.root / "s1.jsonl", - [ - assistant("텍스트 답"), - assistant([{"type": "tool_use", "id": "t", "name": "Bash", "input": {}}]), - user("질문", "2026-10-19T01:00:00.000Z"), - ], - ) - assert "앞 답: > 텍스트 답" in env.extract(path) - - -def test_numbering_spans_transcripts_and_stdout_summary(env): - a = write_transcript(env.root / "a.jsonl", [user("a1", "2026-10-19T01:00:00.000Z"), user("a2", "2026-10-19T02:00:00.000Z")]) - b = write_transcript(env.root / "b.jsonl", [user("b1", "2026-10-19T03:00:00.000Z")]) - out = env.ok("extract", "--transcript", str(a), "--transcript", str(b), "--out", str(env.out)) - assert out.splitlines() == [ - "a: 메시지 2개, until=2026-10-19T02:00:00.000Z", - "b: 메시지 1개, until=2026-10-19T03:00:00.000Z", - str(env.out), - ] - text = env.out.read_text(encoding="utf-8") - assert "## a" in text and "## b" in text and "### 3 · 2026-10-19T03:00:00.000Z" in text - - -def test_transcript_comes_from_environment(env, monkeypatch): - path = write_transcript(env.root / "envs.jsonl", [user("환경", "2026-10-19T01:00:00.000Z")]) - monkeypatch.setenv("HAN_TRANSCRIPT", str(path)) - env.ok("extract", "--out", str(env.out)) - assert "## envs" in env.out.read_text(encoding="utf-8") - monkeypatch.delenv("HAN_TRANSCRIPT") - assert "--transcript 나 HAN_TRANSCRIPT 필요" in env.fail("extract", "--out", str(env.out)) - - -def test_missing_transcript_fails(env): - assert "대화 기록 없음" in env.fail("extract", "--transcript", str(env.root / "none.jsonl"), "--out", str(env.out)) - - -def test_watermark_skips_processed_and_all_overrides(env): - path = write_transcript( - env.root / "s1.jsonl", - [ - user("옛 것", "2026-10-19T01:00:00.000Z"), - user("경계", "2026-10-19T02:00:00.000Z"), - user("새 것", "2026-10-19T03:00:00.000Z"), - ], - ) - env.ok("record", "--session", "s1", "--until", "2026-10-19T02:00:00.000Z", "--verdict", "확인") - env.ok("record", "--session", "other", "--until", "2026-10-19T09:00:00.000Z", "--verdict", "확인") - text = env.extract(path) - assert "옛 것" not in text and "경계" not in text and "사용자: 새 것" in text and "### 1 · 2026-10-19T03" in text - everything = env.extract(path, "--all") - assert "옛 것" in everything and "경계" in everything and "새 것" in everything - - -def test_watermark_uses_largest_until(env): - path = write_transcript(env.root / "s1.jsonl", [user("m", "2026-10-19T02:00:00.000Z"), user("n", "2026-10-19T05:00:00.000Z")]) - env.ok("record", "--session", "s1", "--until", "2026-10-19T05:00:00.000Z", "--verdict", "확인") - env.ok("record", "--session", "s1", "--until", "2026-10-19T01:00:00.000Z", "--verdict", "확인") - assert "###" not in env.extract(path) - - -def test_empty_extract_reports_dash(env): - path = write_transcript(env.root / "s1.jsonl", [assistant("답만")]) - out = env.ok("extract", "--transcript", str(path), "--out", str(env.out)) - assert out.splitlines()[0] == "s1: 메시지 0개, until=-" - - -def test_record_writes_header_and_row(env): - env.ok( - "record", "--session", "s1", "--until", "2026-10-19T02:00:00.000Z", - "--verdict", "반영", "--dest", "guide", "--summary", "탭\t줄\n바꿈", - ) - env.ok("record", "--session", "s1", "--until", "2026-10-19T03:00:00.000Z", "--verdict", "확인") - rows = [line.split("\t") for line in env.log.read_text(encoding="utf-8").splitlines()] - assert rows[0] == list(distill.LOG_HEADER) - assert rows[1][1:] == ["s1", "2026-10-19T02:00:00.000Z", "반영", "guide", "탭 줄 바꿈"] - assert rows[2][1:] == ["s1", "2026-10-19T03:00:00.000Z", "확인", "-", "-"] - assert all(len(row) == 6 for row in rows) - - -def test_record_creates_missing_folder(env, monkeypatch): - nested = env.root / "a" / "b" / "log.tsv" - monkeypatch.setenv("HAN_DISTILL_LOG", str(nested)) - env.ok("record", "--session", "s1", "--until", "t", "--verdict", "확인") - assert nested.is_file() - - -@pytest.mark.parametrize( - "extra", - [ - ["--verdict", "반영", "--dest", "guide"], - ["--verdict", "반영", "--summary", "요약"], - ["--verdict", "기각"], - ["--verdict", "기각", "--summary", " "], - ["--verdict", "없는판정"], - ["--verdict", "반영", "--dest", "elsewhere", "--summary", "요약"], - [], - ], -) -def test_record_rejects_bad_arguments(env, extra): - env.fail("record", "--session", "s1", "--until", "t", *extra) - assert not env.log.exists() - - -def test_record_rejects_bad_log_header(env): - env.log.write_text("엉뚱\t헤더\n", encoding="utf-8") - path = write_transcript(env.root / "s1.jsonl", [user("m", "2026-10-19T01:00:00.000Z")]) - assert "헤더가 다름" in env.fail("extract", "--transcript", str(path), "--out", str(env.out)) - - -def codex_message(role, text, ts="2026-10-20T01:00:00.000Z", content_type="text"): - return { - "type": "response_item", - "timestamp": ts, - "payload": {"type": "message", "role": role, "content": [{"type": content_type, "text": text}]}, - } - - -@pytest.mark.parametrize("content_type", ["text", "input_text", "output_text"]) -def test_codex_reads_canonical_messages_without_duplicate_events(env, content_type): - path = write_transcript(env.root / "codex.jsonl", [ - {"type": "session_meta", "payload": {"id": "codex-session"}}, - codex_message("developer", "시스템 지시"), - codex_message("assistant", "앞\n답", content_type=content_type), - {"type": "response_item", "payload": {"type": "reasoning", "summary": "숨김"}}, - {"type": "response_item", "payload": {"type": "function_call_output", "output": "도구"}}, - {"type": "event_msg", "payload": {"type": "user_message", "message": "교정"}}, - codex_message("user", "교정", content_type=content_type), - {"type": "compacted", "replacement_history": [codex_message("user", "요약")]}, - ]) - text = env.extract(path) - assert "## codex-session" in text - assert "앞 답: > 앞 답" in text - assert text.count("사용자: 교정") == 1 - assert all(value not in text for value in ("시스템 지시", "숨김", "도구", "요약")) - - -@pytest.mark.parametrize("prefix", distill.CODEX_CONTEXT_PREFIXES) -@pytest.mark.parametrize("as_list", [True, False]) -def test_codex_injected_context_is_not_feedback(env, prefix, as_list): - entry = codex_message("user", prefix + "\n주입된 내용") - if not as_list: - entry["payload"]["content"] = prefix + "\n주입된 내용" - path = write_transcript(env.root / "codex.jsonl", [entry, codex_message("user", "사용자 교정")]) - text = env.extract(path) - assert "주입된 내용" not in text - assert "사용자: 사용자 교정" in text - assert "### 2" not in text - - -def test_codex_context_part_does_not_drop_feedback_in_other_parts(env): - entry = codex_message("user", "# AGENTS.md instructions\n규칙") - entry["payload"]["content"].append({"type": "input_text", "text": "실제 피드백"}) - path = write_transcript(env.root / "codex.jsonl", [entry]) - text = env.extract(path) - assert "사용자: 실제 피드백" in text and "규칙" not in text - - -def test_codex_watermark_uses_session_metadata_across_rollout_names(env): - entries = [ - {"type": "session_meta", "payload": {"id": "same-session"}}, - codex_message("user", "처리한 교정", "2026-10-20T01:00:00.000Z"), - codex_message("user", "새 교정", "2026-10-20T02:00:00.000Z"), - ] - first = write_transcript(env.root / "rollout-first.jsonl", entries) - second = write_transcript(env.root / "rollout-second.jsonl", entries) - env.ok("record", "--session", "same-session", "--until", "2026-10-20T01:00:00.000Z", "--verdict", "확인") - for path in (first, second): - text = env.extract(path) - assert "처리한 교정" not in text and "사용자: 새 교정" in text - assert "처리한 교정" in env.extract(path, "--all") - - -def test_claude_and_codex_transcripts_can_be_extracted_together(env): - claude = write_transcript(env.root / "claude.jsonl", [user("Claude 교정", "2026-10-19T01:00:00.000Z")]) - codex = write_transcript(env.root / "codex.jsonl", [codex_message("user", "Codex 교정")]) - env.ok("extract", "--transcript", str(claude), "--transcript", str(codex), "--out", str(env.out)) - text = env.out.read_text(encoding="utf-8") - assert "사용자: Claude 교정" in text and "사용자: Codex 교정" in text and "### 2" in text - - -def test_runtime_log_defaults_and_override(env, monkeypatch): - monkeypatch.delenv("HAN_DISTILL_LOG") - monkeypatch.setenv("CODEX_HOME", str(env.root / "codex-home")) - assert Path(distill.log_path("codex")) == env.root / "codex-home/han/distill/log.tsv" - assert Path(distill.log_path()) == Path.home() / ".claude/han/distill/log.tsv" - monkeypatch.delenv("CODEX_HOME") - assert Path(distill.log_path("codex")) == Path.home() / ".codex/han/distill/log.tsv" - monkeypatch.setenv("HAN_DISTILL_LOG", str(env.log)) - assert distill.log_path("codex") == distill.log_path() == str(env.log) - - -def test_codex_requires_explicit_transcript_instead_of_inherited_claude_path(env, monkeypatch, capsys): - path = write_transcript(env.root / "claude.jsonl", [user("다른 세션", "2026-10-19T01:00:00.000Z")]) - monkeypatch.setenv("HAN_TRANSCRIPT", str(path)) - capsys.readouterr() - assert distill.main(["extract", "--out", str(env.out)], runtime="codex") == 1 - assert "--transcript 필요" in capsys.readouterr().err - assert not env.out.exists() - - -def test_codex_entrypoint_records_and_extracts_from_another_cwd(env, monkeypatch): - monkeypatch.delenv("HAN_DISTILL_LOG") - monkeypatch.setenv("CODEX_HOME", str(env.root / "codex-home")) - script = PLUGIN_ROOT / "codex/skills/chef-distill/scripts/distill.py" - path = write_transcript(env.root / "rollout.jsonl", [ - {"type": "session_meta", "payload": {"id": "codex-session"}}, - codex_message("user", "교정"), - ]) - commands = [ - ["extract", "--transcript", str(path), "--out", str(env.out)], - ["record", "--session", "codex-session", "--until", "2026-10-20T01:00:00.000Z", "--verdict", "확인"], - ["extract", "--transcript", str(path), "--out", str(env.out)], - ] - outputs = [] - for arguments in commands: - result = subprocess.run([sys.executable, str(script), *arguments], cwd=env.root, capture_output=True, timeout=15) - assert result.returncode == 0, result.stderr.decode("utf-8") - outputs.append(result.stdout.decode("utf-8")) - assert "메시지 1개" in outputs[0] and "메시지 0개" in outputs[-1] - assert (env.root / "codex-home/han/distill/log.tsv").is_file() - - -def grok_update(kind, text="", timestamp=1800000000, session="sample-session"): - return {"timestamp": timestamp, "params": {"sessionId": session, - "update": {"sessionUpdate": kind, "content": {"type": "text", "text": text}}}} - - -def test_grok_streaming_prompts_previous_response_and_context_filter(env): - path = write_transcript(env.root / "updates.jsonl", [ - grok_update("user_message_chunk", "# AGENTS.md instructions\nInjected context"), - grok_update("turn_completed"), - grok_update("agent_message_chunk", "The "), grok_update("agent_thought_chunk", "Hidden thought"), - grok_update("tool_call_update", "Hidden tool"), grok_update("agent_message_chunk", "color is blue."), - grok_update("turn_completed"), - grok_update("user_message_chunk", "Use ", 1800000001), grok_update("user_message_chunk", "green", 1800000002), - ]) - env.ok("extract", "--runtime", "grok", "--transcript", str(path), "--out", str(env.out)) - text = env.out.read_text(encoding="utf-8") - assert "## sample-session" in text - assert "앞 답: > The color is blue." in text - assert "사용자: Use green" in text - assert "2027-01-15T08:00:02.000Z" in text - assert all(value not in text for value in ("Injected context", "Hidden thought", "Hidden tool")) - - -def test_grok_distinct_sessions_have_separate_watermarks(env): - paths = [] - for session in ("first-session", "second-session"): - folder = env.root / session - folder.mkdir() - paths.append(write_transcript(folder / "updates.jsonl", [ - grok_update("user_message_chunk", "Earlier", session=session), grok_update("turn_completed", session=session), - grok_update("user_message_chunk", "Later", 1800000001, session), - ])) - env.ok("--runtime", "grok", "record", "--session", "first-session", "--until", "2027-01-15T08:00:00.000Z", "--verdict", "확인") - env.ok("--runtime", "grok", "extract", "--transcript", str(paths[0]), "--transcript", str(paths[1]), "--out", str(env.out)) - text = env.out.read_text(encoding="utf-8") - first, second = text.split("## second-session") - assert "## first-session" in first and "Earlier" not in first and "Later" in first - assert "Earlier" in second and "Later" in second - - -def test_grok_log_honors_home_and_explicit_override(env, monkeypatch): - monkeypatch.delenv("HAN_DISTILL_LOG") - monkeypatch.delenv("GROK_HOME", raising=False) - assert Path(distill.log_path("grok")) == Path.home() / ".grok/han/distill/log.tsv" - monkeypatch.setenv("GROK_HOME", str(env.root / "grok-home")) - env.ok("record", "--runtime", "grok", "--session", "sample-session", "--until", "2027-01-15T08:00:00.000Z", "--verdict", "확인") - assert (env.root / "grok-home/han/distill/log.tsv").is_file() - monkeypatch.setenv("HAN_DISTILL_LOG", str(env.log)) - assert distill.log_path("grok") == str(env.log) - - -def test_grok_requires_explicit_transcript_and_never_uses_claude_environment(env, monkeypatch): - path = write_transcript(env.root / "claude.jsonl", [user("Different session", "2027-01-15T08:00:00.000Z")]) - monkeypatch.setenv("HAN_TRANSCRIPT", str(path)) - assert "--transcript 필요" in env.fail("extract", "--runtime", "grok", "--out", str(env.out)) - assert not env.out.exists() diff --git a/tests/integration/distill/test_distill_entry.py b/tests/integration/distill/test_distill_entry.py new file mode 100644 index 0000000..b2d3eeb --- /dev/null +++ b/tests/integration/distill/test_distill_entry.py @@ -0,0 +1,20 @@ +"""A user message in a transcript becomes distill text. Tool results do not.""" +import json + +from chef.cli import distill + + +def test_user_text_is_extracted_and_tool_results_are_not(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HAN_DISTILL_LOG", str(tmp_path / "log.tsv")) + transcript = tmp_path / "session.jsonl" + transcript.write_text("\n".join([ + json.dumps({"type": "user", "timestamp": "2026-10-19T01:00:00.000Z", + "message": {"role": "user", "content": "문자열 메시지"}}), + json.dumps({"type": "user", "timestamp": "2026-10-19T02:00:00.000Z", + "message": {"role": "user", "content": [{"type": "tool_result", "content": "결과만"}]}}), + ]) + "\n", encoding="utf-8") + out = tmp_path / "out.md" + assert distill.main(["extract", "--transcript", str(transcript), "--out", str(out)]) == 0 + text = out.read_text(encoding="utf-8") + assert "문자열 메시지" in text and "결과만" not in text + capsys.readouterr() diff --git a/tests/integration/doctor/test_doctor.py b/tests/integration/doctor/test_doctor.py deleted file mode 100644 index 3aacfeb..0000000 --- a/tests/integration/doctor/test_doctor.py +++ /dev/null @@ -1,501 +0,0 @@ -import json -import os -import sys -from pathlib import Path -from types import SimpleNamespace - -import pytest -from chef.cli import doctor as doctor - -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture(autouse=True) -def isolated_codex_home(tmp_path, monkeypatch): - monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) - - -def make_registry(tmp_path, cases=True, unity=None): - adapters = tmp_path / "adapters" - project_adapter = adapters / "t" - project_adapter.mkdir(parents=True) - main = tmp_path / "main" - (main / "state").mkdir(parents=True) - adapter = {"schema": 1, "project": "T", "paths": {"vcsRoot": ".", "stateDir": "state"}, - "guard": {"deny": [{"pattern": "^p4 submit", "reason": "no"}]}} - if unity: - adapter["vars"] = {"unityExe": unity} - (project_adapter / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - if cases: - (project_adapter / "guard-cases.json").write_text(json.dumps([{"expect": "deny", "command": "p4 submit"}]), encoding="utf-8") - (adapters / "projects.json").write_text(json.dumps([{"adapter": "t", "roots": [str(main)]}]), encoding="utf-8") - return adapters, main - - -def levels(report, area): - return [row["level"] for row in report.rows if row["area"] == area] - - -def test_doctor_reports_registry_adapter_cases_and_stale_active(tmp_path, monkeypatch): - adapters, main = make_registry(tmp_path, unity=str(tmp_path / "missing.exe")) - active = main / "state" / "ACTIVE" - active.write_text(json.dumps({"id": "m1", "session": "s"}), encoding="utf-8") - old = 1_000_000_000 - os.utime(active, (old, old)) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - report = doctor.run("claude") - assert levels(report, "registry") == ["OK"] - assert levels(report, "guard-cases") == ["OK"] - assert levels(report, "unity") == ["FAIL"] - stale = [row["text"] for row in report.rows if row["area"] == "active"] - assert stale and "close-stale" in stale[0] and "--force-close-stale" in stale[0] - assert active.exists() # 읽기 전용 - - -def write_role_policy(adapters, adapter_extra=None, local=None): - path = adapters / "t" / "adapter.json" - adapter = json.loads(path.read_text(encoding="utf-8")) - adapter.update(adapter_extra or {}) - path.write_text(json.dumps(adapter), encoding="utf-8") - if local is not None: - (adapters / "t" / "local.json").write_text(json.dumps(local), encoding="utf-8") - - -def role_policy_rows(report): - return [(row["level"], row["text"]) for row in report.rows if row["area"] == "role-policy"] - - -def test_doctor_role_policy_absent_adds_no_rows(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - assert role_policy_rows(doctor.run("claude")) == [] - - -def test_doctor_role_policy_valid_values_are_ok(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"rolePolicy": {"model": "inherit", "subagents": False}, - "runtimes": {"codex": {"rolePolicy": {"model": "definition"}}, "grok": {"rolePolicy": {"subagents": True}}}}, - local={"rolePolicy": {"model": "definition"}}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - report = doctor.run("claude") - rows = role_policy_rows(report) - assert [level for level, _ in rows] == ["OK"] * 4 - assert not report.failed - - -@pytest.mark.parametrize("policy,needle", [ - ({"model": "same"}, "model"), - ({"model": True}, "model"), - ({"subagents": "no"}, "subagents"), - ({"subagents": 0}, "subagents"), - ("inherit", "객체"), -]) -def test_doctor_role_policy_bad_values_fail(tmp_path, monkeypatch, policy, needle): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"rolePolicy": policy}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - report = doctor.run("claude") - rows = role_policy_rows(report) - assert [level for level, _ in rows] == ["FAIL"] and needle in rows[0][1] - assert report.failed - - -def test_doctor_role_policy_unknown_key_warns(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"rolePolicy": {"model": "inherit", "effort": "high"}}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - rows = role_policy_rows(doctor.run("claude")) - assert [level for level, _ in rows] == ["WARN"] and "effort" in rows[0][1] - - -@pytest.mark.parametrize("source", ["adapter", "local"]) -@pytest.mark.parametrize("runtime", ["codex", "grok"]) -def test_doctor_role_policy_runtime_overlay_values_are_checked(tmp_path, monkeypatch, source, runtime): - adapters, _ = make_registry(tmp_path) - overlay = {"runtimes": {runtime: {"rolePolicy": {"model": "other", "subagents": "x"}}}} - if source == "adapter": - write_role_policy(adapters, overlay) - else: - write_role_policy(adapters, local=overlay) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - rows = role_policy_rows(doctor.run("claude")) - assert [level for level, _ in rows] == ["FAIL", "FAIL"] - assert all(f"runtimes.{runtime}.rolePolicy" in text and f"{source}.json" in text for _, text in rows) - - -@pytest.mark.parametrize("source", ["adapter", "local"]) -def test_doctor_role_policy_claude_overlay_is_supported(tmp_path, monkeypatch, source): - adapters, _ = make_registry(tmp_path) - overlay = {"runtimes": {"claude": {"rolePolicy": {"model": "inherit"}}}} - if source == "adapter": - write_role_policy(adapters, overlay) - else: - write_role_policy(adapters, local=overlay) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - report = doctor.run("claude") - rows = role_policy_rows(report) - assert [level for level, _ in rows] == ["OK"] - assert not report.failed - - -ALL_TEAM_ROLES = {"research": "team-research", "implement": "team-dev", "verify": "team-verify", "review": "team-review", - "reviewSmall": "team-review-small"} - - -def agent_allow_rows(report): - return [(row["level"], row["text"]) for row in report.rows if row["area"] == "agent-allow"] - - -def test_doctor_agent_allow_absent_adds_no_rows(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - assert agent_allow_rows(doctor.run("claude")) == [] - - -def test_doctor_agent_allow_ok_when_all_roles_allowed(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"roles": {"dev": "team-dev", "reviewer": "chef:code-reviewer", "reviewLoopSkill": "x"}, - "agents": {"allow": ["team-*", "chef:*"]}}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - rows = agent_allow_rows(doctor.run("claude")) - assert [level for level, _ in rows] == ["OK"] - - -def test_doctor_agent_allow_warns_for_blocked_roles(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"roles": {"dev": "team-dev", "verifier": "chef:verifier"}, - "agents": {"allow": ["team-*"]}}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - rows = agent_allow_rows(doctor.run("claude")) - assert [level for level, _ in rows] == ["WARN"] - assert "chef:verifier" in rows[0][1] and "team-dev" not in rows[0][1].split("(")[0] - - -def test_doctor_agent_allow_checks_default_names_of_missing_roles(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"roles": {"research": "team-research", "implement": "team-dev"}, "agents": {"allow": ["team-*"]}}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - rows = agent_allow_rows(doctor.run("claude")) - assert [level for level, _ in rows] == ["WARN"] - for default in ("chef:verifier", "chef:code-reviewer", "chef:reviewer-small"): - assert default in rows[0][1] - assert "team-research" not in rows[0][1].split("(")[0] - - -def test_doctor_agent_allow_reads_legacy_names_as_current(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"roles": {**ALL_TEAM_ROLES, "verify": "chef_verifier"}, "agents": {"allow": ["team-*"]}}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - rows = agent_allow_rows(doctor.run("claude")) - assert [level for level, _ in rows] == ["WARN"] and "chef:verifier" in rows[0][1] - - -def test_doctor_agent_allow_uses_runtime_overlay(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"roles": ALL_TEAM_ROLES, "agents": {"allow": ["team-*"]}, - "runtimes": {"codex": {"agents": {"allow": ["other-*"]}}}}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - assert [level for level, _ in agent_allow_rows(doctor.run("claude"))] == ["OK"] - assert [level for level, _ in agent_allow_rows(doctor.run("codex"))] == ["WARN"] - - -@pytest.mark.parametrize("agents", ["team-*", {"allow": "team-*"}, {"allow": ["team-*", 3]}, {"allow": [""]}]) -def test_doctor_agent_allow_bad_shape_warns(tmp_path, monkeypatch, agents): - adapters, _ = make_registry(tmp_path) - write_role_policy(adapters, {"agents": agents}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - rows = agent_allow_rows(doctor.run("claude")) - assert [level for level, _ in rows] == ["WARN"] and "형식 오류" in rows[0][1] - - -def test_doctor_without_registry_fails(tmp_path, monkeypatch): - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "none")) - report = doctor.run("codex") - assert levels(report, "registry") == ["FAIL"] - - -def test_doctor_grok_runtime_uses_shared_mission_script(tmp_path, monkeypatch, capsys): - monkeypatch.setattr(doctor, "check_grok", lambda report: report.add("OK", "grok-cli", "synthetic")) - adapters, main = make_registry(tmp_path) - active = main / "state" / "ACTIVE" - active.write_text(json.dumps({"id": "m1", "session": "s"}), encoding="utf-8") - old = 1_000_000_000 - os.utime(active, (old, old)) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - report = doctor.run("grok") - assert levels(report, "registry") == ["OK"] - assert doctor.MISSION_STATE["grok"] == doctor.MISSION_STATE["claude"] - doctor.main(["--runtime", "grok"]) - out = capsys.readouterr().out.replace("\\", "/") - preview = next(line for line in out.splitlines() if "close-stale" in line) - assert "skills/mission/scripts/mission_state.py" in preview - assert "--runtime" in preview and "grok" in preview and "--project" in preview - assert sys.executable.replace("\\", "/") in preview - assert "codex/skills" not in out - assert active.exists() - - -def test_doctor_cli_json(tmp_path, monkeypatch, capsys): - adapters, _ = make_registry(tmp_path, cases=False) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - doctor.main(["--json"]) - out = json.loads(capsys.readouterr().out) - assert any(row["area"] == "guard-cases" and row["level"] == "WARN" for row in out["rows"]) - - -def grok_inspection(trusted=False): - skill_root = os.path.join(doctor.PLUGIN, "grok", "skills") - skills = [{"name": name} for name in os.listdir(skill_root) - if name not in ("chef-watch", "chef-handoff") and os.path.isfile(os.path.join(skill_root, name, "SKILL.md"))] - agents = [{"name": f"chef:{role}", "source": {"type": "plugin", "path": os.path.join(doctor.PLUGIN, "grok", "agents", f"{role}.md")}} - for role in doctor.GROK_NATIVE_ROLES] - return {"projectTrusted": trusted, "skills": skills, "agents": agents, - "plugins": [{"name": "chef", "path": doctor.PLUGIN, "enabled": True, "provides": {"agents": 1}}], - "hooks": [{"event": "(plugin)", "hookType": "file", "target": "/example/plugins/chef/hooks/hooks.json"}]} - - -def test_grok_doctor_reports_discovery_separately_from_trust(monkeypatch): - calls = [] - monkeypatch.setattr(doctor.shutil, "which", lambda name: "/example/grok") - - def run(argv, **kwargs): - calls.append(argv) - assert kwargs["timeout"] == 10 - if argv[-1] == "--version": - return SimpleNamespace(returncode=0, stdout="grok 1.0.70") - return SimpleNamespace(returncode=0, stdout=json.dumps(grok_inspection())) - - monkeypatch.setattr(doctor.subprocess, "run", run) - report = doctor.Report() - doctor.check_grok(report) - assert calls == [["/example/grok", "--version"], ["/example/grok", "inspect", "--json"]] - assert levels(report, "grok-cli") == ["OK"] - assert levels(report, "grok-skills") == ["OK"] - assert levels(report, "grok-agents") == ["OK"] - assert levels(report, "grok-native") == ["OK"] - assert levels(report, "grok-hooks") == ["OK"] - assert levels(report, "grok-trust") == ["WARN"] - assert any("로드·실행 검증이 아님" in row["text"] for row in report.rows) - assert any("하위 에이전트 상태는 저장된 metadata·lifecycle 기준" in row["text"] for row in report.rows) - - -def test_grok_doctor_missing_binary_fails_without_running_it(monkeypatch): - monkeypatch.setattr(doctor.shutil, "which", lambda name: "") - monkeypatch.setattr(doctor.subprocess, "run", lambda *args, **kwargs: pytest.fail("must not launch missing CLI")) - report = doctor.Report() - doctor.check_grok(report) - assert levels(report, "grok-cli") == ["FAIL"] - - -@pytest.mark.parametrize("target", ["/example/plugins/chef/hooks/hooks.json", r"C:\\example\\plugins\\chef\\hooks/hooks.json"]) -def test_grok_hook_registration_accepts_native_and_compat_paths(target): - assert doctor.grok_han_hook({"target": target}) - assert not doctor.grok_han_hook({"target": "/example/plugins/other/hooks/hooks.json"}) - - -def test_grok_hook_registration_accepts_marketplace_source(): - path = "/example/.grok/installed-plugins/chef-a4b5c6" - hook = { - "event": "(plugin)", - "target": f"{path}/hooks/hooks.json", - "source": {"type": "plugin", "plugin_name": "chef", "path": path}, - } - assert doctor.grok_han_hook(hook) - hook["source"]["plugin_name"] = "other" - assert not doctor.grok_han_hook(hook) - - -@pytest.mark.parametrize("output,code", [("not JSON", 0), ("[]", 0), ("{}", 1)]) -def test_grok_doctor_inspection_failures_are_explicit(monkeypatch, output, code): - monkeypatch.setattr(doctor.shutil, "which", lambda name: "/example/grok") - - def run(argv, **kwargs): - if argv[-1] == "--version": - return SimpleNamespace(returncode=0, stdout="grok 1.0.70") - return SimpleNamespace(returncode=code, stdout=output) - - monkeypatch.setattr(doctor.subprocess, "run", run) - report = doctor.Report() - doctor.check_grok(report) - assert levels(report, "grok-registration") == ["WARN"] - assert not levels(report, "grok-trust") - - -def test_grok_doctor_missing_registration_is_a_warning(monkeypatch): - monkeypatch.setattr(doctor.shutil, "which", lambda name: "/example/grok") - - def run(argv, **kwargs): - if argv[-1] == "--version": - return SimpleNamespace(returncode=0, stdout="grok 1.0.70") - return SimpleNamespace(returncode=0, stdout=json.dumps({"projectTrusted": True, "skills": [], "hooks": []})) - - monkeypatch.setattr(doctor.subprocess, "run", run) - report = doctor.Report() - doctor.check_grok(report) - assert levels(report, "grok-skills") == ["WARN"] - assert levels(report, "grok-agents") == ["WARN"] - assert levels(report, "grok-native") == ["WARN"] - assert levels(report, "grok-hooks") == ["WARN"] - assert levels(report, "grok-trust") == ["OK"] - - -@pytest.mark.parametrize("change,detail", [ - ("missing", "없음: chef:reviewer-small"), - ("wrong-name", "예상 밖 역할: chef:other"), - ("compat-source", "원본 경로 불일치·중복: chef:reviewer-small"), - ("missing-source", "원본 경로 불일치·중복: chef:reviewer-small"), - ("duplicate", "원본 경로 불일치·중복: chef:reviewer-small"), -]) -def test_grok_doctor_reports_missing_or_wrong_native_roles(change, detail): - inspection = grok_inspection() - reviewer = inspection["agents"][-1] - if change == "missing": - inspection["agents"].pop() - elif change == "wrong-name": - reviewer["name"] = "chef:other" - elif change == "compat-source": - reviewer["source"]["path"] = os.path.join(doctor.PLUGIN, "agents", "reviewer-small.md") - elif change == "missing-source": - reviewer.pop("source") - else: - inspection["agents"].append(dict(reviewer)) - report = doctor.Report() - doctor.check_grok_agents(report, inspection) - assert levels(report, "grok-agents") == ["WARN"] - row = next(row for row in report.rows if row["area"] == "grok-agents") - assert detail in row["text"] - assert "5/6개" in row["text"] - - -@pytest.mark.parametrize("change", ["wrong-path", "disabled", "missing", "duplicate"]) -def test_grok_doctor_rejects_inactive_or_wrong_selected_plugin(change): - inspection = grok_inspection() - plugin = inspection["plugins"][0] - if change == "wrong-path": - plugin["path"] = os.path.join(doctor.PLUGIN, "other") - elif change == "disabled": - plugin["enabled"] = False - elif change == "missing": - inspection.pop("plugins") - else: - inspection["plugins"].append(dict(plugin)) - report = doctor.Report() - doctor.check_grok_agents(report, inspection) - assert levels(report, "grok-native") == ["WARN"] - - -def test_grok_doctor_does_not_use_registration_directory_count_as_role_count(): - inspection = grok_inspection() - inspection["agents"].append({"name": "other:researcher", "source": {"type": "plugin", "path": "/other/researcher.md"}}) - report = doctor.Report() - doctor.check_grok_agents(report, inspection) - assert levels(report, "grok-agents") == ["OK"] - assert levels(report, "grok-native") == ["OK"] - assert any("파견·모델·effort 실행 검증이 아님" in row["text"] for row in report.rows) - - -def shipped_role(name): - return os.path.join(doctor.PLUGIN, "codex", "agents", name) - - -def shipped_text(name): - with open(shipped_role(name), encoding="utf-8") as f: - return f.read() - - -def codex_agent_rows(report): - return [(row["level"], row["text"]) for row in report.rows if row["area"] == "codex-agents"] - - -def shipped_files(): - folder = os.path.join(doctor.PLUGIN, "codex", "agents") - return sorted(name for name in os.listdir(folder) if name.endswith(".toml")) - - -def register_codex_role(tmp_path, name, text): - folder = tmp_path / "codex-home" / "agents" - folder.mkdir(parents=True, exist_ok=True) - (folder / name).write_bytes(text.encode("utf-8")) - return folder / name - - -def test_doctor_codex_agents_none_registered_is_info_only(tmp_path, monkeypatch): - adapters, _ = make_registry(tmp_path) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(adapters)) - report = doctor.run("codex") - rows = codex_agent_rows(report) - assert [level for level, _ in rows] == ["OK"] and "등록 없음" in rows[0][1] - assert not report.failed - - -def test_doctor_codex_agents_full_matching_copy_is_ok_even_with_crlf(tmp_path): - for name in shipped_files(): - register_codex_role(tmp_path, name, shipped_text(name).replace("\n", "\r\n")) - report = doctor.Report() - doctor.check_codex_agents(report) - ((level, detail),) = codex_agent_rows(report) - assert level == "OK" and "낡은" not in detail and "빠진" not in detail - assert os.path.join(doctor.PLUGIN, "codex", "agents") in detail - - -def test_doctor_codex_agents_partial_registration_names_missing_roles(tmp_path): - register_codex_role(tmp_path, "chef-researcher.toml", shipped_text("chef-researcher.toml")) - report = doctor.Report() - doctor.check_codex_agents(report) - ((level, detail),) = codex_agent_rows(report) - assert level == "WARN" - assert "빠진 역할" in detail and "chef:verifier" in detail and "chef:researcher" not in detail.split("빠진 역할")[1] - - -def test_doctor_codex_agents_compares_by_role_name_not_file_name(tmp_path): - for name in shipped_files(): - if name != "chef-verifier.toml": - register_codex_role(tmp_path, name, shipped_text(name)) - register_codex_role(tmp_path, "my-verifier.toml", shipped_text("chef-verifier.toml").replace("\"chef:verifier\"", "'chef:verifier'") + "\n# 오래된 사본\n") - report = doctor.Report() - doctor.check_codex_agents(report) - ((level, detail),) = codex_agent_rows(report) - assert level == "WARN" and "my-verifier.toml" in detail and "낡은 등록" in detail - assert "빠진 역할" not in detail - - -def test_doctor_codex_agents_role_name_ignores_nested_tables_and_reads_literal_strings(): - assert doctor.role_name_by_pattern("name = 'chef_a'\n") == "chef_a" - assert doctor.role_name_by_pattern("[x]\nname = \"chef_b\"\n") == "" - assert doctor.role_name("name = 'chef_c'\n") == "chef_c" - assert doctor.role_name("broken = [\nname = \"chef_d\"\n") == "chef_d" - - -def test_doctor_codex_agents_os_error_is_reported_and_doctor_finishes(tmp_path, monkeypatch): - registered = os.path.join(str(tmp_path / "codex-home"), "agents") - (tmp_path / "codex-home" / "agents").mkdir(parents=True) - real_listdir = os.listdir - - def listdir(path="."): - if os.fspath(path) == registered: - raise PermissionError("denied") - return real_listdir(path) - - monkeypatch.setattr(doctor.os, "listdir", listdir) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "none")) - report = doctor.run("codex") - ((level, detail),) = codex_agent_rows(report) - assert level == "WARN" and "PermissionError" in detail - assert levels(report, "registry") == ["FAIL"] - - -def test_doctor_codex_agents_reports_stale_and_unknown_chef_roles(tmp_path): - stale = register_codex_role(tmp_path, "chef-verifier.toml", shipped_text("chef-verifier.toml") + "\n# 오래된 사본\n") - register_codex_role(tmp_path, "chef-retired.toml", 'name = "chef_retired"\n') - register_codex_role(tmp_path, "renamed.toml", 'name = "chef:renamed"\n') - register_codex_role(tmp_path, "chef-developer-small.toml", 'name = "chef_developer_small"\n') - other = register_codex_role(tmp_path, "my-reviewer.toml", 'name = "my_reviewer"\n') - report = doctor.Report() - doctor.check_codex_agents(report) - ((level, detail),) = codex_agent_rows(report) - assert level == "WARN" - assert "낡은 등록" in detail and "chef-verifier.toml" in detail - assert "chef-retired.toml" in detail and "renamed.toml" in detail and "chef-developer-small.toml" in detail - assert "my-reviewer" not in detail - assert stale.exists() and other.exists() - assert not report.failed diff --git a/tests/integration/doctor/test_doctor_entry.py b/tests/integration/doctor/test_doctor_entry.py new file mode 100644 index 0000000..1dd5d24 --- /dev/null +++ b/tests/integration/doctor/test_doctor_entry.py @@ -0,0 +1,11 @@ +"""Doctor fails closed when the adapter registry is missing.""" +from chef.cli import doctor + +from tests.support import isolate + + +def test_missing_registry_fails(tmp_path, monkeypatch): + isolate(monkeypatch, tmp_path) + monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) + report = doctor.run("codex") + assert any(row["level"] == "FAIL" and row["area"] == "registry" for row in report.rows) diff --git a/tests/integration/grok/test_grok_entry.py b/tests/integration/grok/test_grok_entry.py new file mode 100644 index 0000000..93dbe6f --- /dev/null +++ b/tests/integration/grok/test_grok_entry.py @@ -0,0 +1,11 @@ +"""Grok doctor uses the same missing-registry failure as the other runtimes.""" +from chef.cli import doctor + +from tests.support import isolate + + +def test_grok_missing_registry_fails(tmp_path, monkeypatch): + isolate(monkeypatch, tmp_path) + monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) + report = doctor.run("grok") + assert any(row["level"] == "FAIL" and row["area"] == "registry" for row in report.rows) diff --git a/tests/integration/grok/test_grok_transcript.py b/tests/integration/grok/test_grok_transcript.py deleted file mode 100644 index 8447c24..0000000 --- a/tests/integration/grok/test_grok_transcript.py +++ /dev/null @@ -1,416 +0,0 @@ -import json -import sys -from pathlib import Path - -import pytest -from chef.runtimes.grok import transcript as grok_transcript - -from tests.paths import PLUGIN_ROOT - - -def update(kind, text="", timestamp=1800000000, session="sample-session", **params): - return { - "timestamp": timestamp, - "params": {"sessionId": session, "update": {"sessionUpdate": kind, "content": {"type": "text", "text": text}}, **params}, - } - - -def write(path, *events): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text("\n".join(json.dumps(event) for event in events) + "\n", encoding="utf-8") - return path - - -def test_find_transcript_uses_exact_session_and_home_override(tmp_path, monkeypatch): - home = tmp_path / "home" - expected = write(home / ".grok/sessions/encoded/sample-session/updates.jsonl", update("turn_completed")) - write(home / ".grok/sessions/encoded/sample-session-extra/updates.jsonl", update("turn_completed")) - monkeypatch.delenv("GROK_HOME", raising=False) - assert grok_transcript.find_transcript("sample-session", str(home)) == str(expected) - override = tmp_path / "override" - other = write(override / "sessions/encoded/sample-session/updates.jsonl", update("turn_completed")) - monkeypatch.setenv("GROK_HOME", str(override)) - assert grok_transcript.find_transcript("sample-session", str(home)) == str(other) - - -@pytest.mark.parametrize("session", ["*", "../sample-session", "a/b", "", None]) -def test_find_transcript_rejects_unsafe_ids(session): - assert grok_transcript.find_transcript(session) == "" - - -def test_detection_requires_acp_update_in_updates_file(tmp_path): - unrelated = write(tmp_path / "unrelated/updates.jsonl", {"timestamp": 1800000000}) - assert not grok_transcript.is_transcript(unrelated) - path = write(tmp_path / "grok/updates.jsonl", {"params": {"update": {}}}, update("turn_completed")) - assert grok_transcript.is_transcript(path) - assert grok_transcript.session_id(path) == "sample-session" - - -def test_detection_skips_content_for_other_file_names(tmp_path, monkeypatch): - claude = write(tmp_path / "11111111-2222-3333-4444-555555555555.jsonl", update("turn_completed")) - codex = write(tmp_path / "rollout-2026-01-01T00-00-00-11111111-2222-3333-4444-555555555555.jsonl", update("turn_completed")) - monkeypatch.setattr(grok_transcript, "entries", lambda *_: pytest.fail("content was read")) - assert not grok_transcript.is_transcript(claude) - assert not grok_transcript.is_transcript(codex) - - -def test_detection_remembers_only_confirmed_transcripts(tmp_path, monkeypatch): - monkeypatch.setattr(grok_transcript, "CONFIRMED", set()) - path = tmp_path / "grok/updates.jsonl" - path.parent.mkdir() - path.write_text("", encoding="utf-8") - assert not grok_transcript.is_transcript(path) - write(path, update("agent_message_chunk", "hello")) - assert grok_transcript.is_transcript(path) - monkeypatch.setattr(grok_transcript, "entries", lambda *_: pytest.fail("content was read again")) - assert grok_transcript.is_transcript(path) - assert grok_transcript.is_transcript(str(path)) - - -def test_detection_memory_stays_bounded(tmp_path, monkeypatch): - monkeypatch.setattr(grok_transcript, "CONFIRMED", set()) - monkeypatch.setattr(grok_transcript, "CONFIRMED_LIMIT", 3) - paths = [write(tmp_path / f"grok-{number}/updates.jsonl", update("turn_completed")) for number in range(5)] - for path in paths: - assert grok_transcript.is_transcript(path) - assert len(grok_transcript.CONFIRMED) <= 3 - - -def test_session_fallback_uses_directory_not_common_filename(tmp_path): - event = update("turn_completed") - event["params"].pop("sessionId") - path = write(tmp_path / "distinct-session/updates.jsonl", event) - assert grok_transcript.session_id(path) == "distinct-session" - - -def test_streaming_messages_preserve_prompts_and_assistant_across_tools(tmp_path): - path = write(tmp_path / "updates.jsonl", - update("user_message_chunk", "Make "), update("user_message_chunk", "it blue", timestamp=1800000001), - update("agent_thought_chunk", "hidden thought"), - update("agent_message_chunk", "Changed "), update("tool_call", "hidden tool"), - update("agent_message_chunk", "the color."), update("turn_completed"), - update("user_message_chunk", "Use green instead", timestamp=1800000002), update("turn_completed"), - update("user_message_chunk", "Keep the size", timestamp=1800000003), - ) - messages = grok_transcript.read_messages(path) - assert [(row["role"], row["text"]) for row in messages] == [ - ("user", "Make it blue"), ("assistant", "Changed the color."), - ("user", "Use green instead"), ("user", "Keep the size"), - ] - assert messages[0]["timestamp"] == "2027-01-15T08:00:01.000Z" - - -def test_numeric_timestamps_and_malformed_lines_are_safe(tmp_path): - path = write(tmp_path / "updates.jsonl", [], {"params": []}, - update("user_message_chunk", "Prompt", _meta={"agentTimestampMs": 1800000000123}), - update("turn_completed", timestamp="bad"), - ) - with path.open("a", encoding="utf-8") as handle: - handle.write("{broken\n") - events = grok_transcript.read_events(path) - assert events[0]["timestamp"] == "2027-01-15T08:00:00.123Z" - assert events[1]["timestamp"] == "" - - -def test_non_text_content_and_system_updates_never_become_messages(tmp_path): - image = update("user_message_chunk", "hidden image") - image["params"]["update"]["content"]["type"] = "image" - path = write(tmp_path / "updates.jsonl", image, update("system_message", "hidden instruction"), - update("agent_thought_chunk", "hidden thought"), update("tool_call_update", "hidden result"), - ) - assert grok_transcript.read_messages(path) == [] - assert all(not row["text"] for row in grok_transcript.read_events(path)) - - -def test_overflowing_agent_timestamp_is_ignored_without_losing_message(tmp_path): - path = write(tmp_path / "updates.jsonl", update("user_message_chunk", "Prompt", _meta={"agentTimestampMs": 10**400})) - messages = grok_transcript.read_messages(path) - assert len(messages) == 1 - assert messages[0]["text"] == "Prompt" and messages[0]["timestamp"] == "" - - -@pytest.mark.parametrize("final_kind,completed", [("turn_completed", True), ("user_message_chunk", False)]) -def test_activity_reads_tail_after_split_utf8_line_and_ignores_partial_final_event(tmp_path, final_kind, completed): - large = update("user_message_chunk", "가" * grok_transcript.ACTIVITY_TAIL_BYTES) - final = update(final_kind, "Continue", timestamp=1800000002) - path = tmp_path / "updates.jsonl" - while True: - raw = (json.dumps(large, ensure_ascii=False) + "\n" + json.dumps(final) + "\n").encode("utf-8") + b'{"params":{"update":' - if raw[len(raw) - grok_transcript.ACTIVITY_TAIL_BYTES] & 0xC0 == 0x80: - break - final["params"]["update"]["content"]["text"] += "x" - path.write_bytes(raw) - events = list(grok_transcript.iter_events(path, grok_transcript.ACTIVITY_TAIL_BYTES)) - assert len(events) == 1 and events[0]["update"] == final_kind - state = grok_transcript.activity(path) - assert state["completed"] == completed - assert state["last_timestamp"] == "2027-01-15T08:00:02.000Z" - messages = grok_transcript.read_messages(path) - assert messages[0]["text"].startswith("가" * 100) - assert len(grok_transcript.read_events(path)) == 2 - - -def test_tail_reader_keeps_event_starting_exactly_at_boundary(tmp_path): - first = update("user_message_chunk", "Earlier") - final = update("turn_completed", timestamp=1800000002) - path = tmp_path / "updates.jsonl" - final_line = (json.dumps(final) + "\n").encode("utf-8") - path.write_bytes((json.dumps(first) + "\n").encode("utf-8") + final_line) - tail_bytes = len(final_line) - events = list(grok_transcript.iter_events(path, tail_bytes)) - assert len(events) == 1 and events[0]["update"] == "turn_completed" - - -def test_activity_recovers_completed_before_oversized_metadata(tmp_path): - path = write(tmp_path / "updates.jsonl", update("turn_completed", timestamp=1800000001), - update("session_info_update", "x" * grok_transcript.ACTIVITY_TAIL_BYTES, timestamp=1800000002)) - state = grok_transcript.activity(path) - assert state["completed"] and state["last_timestamp"] == "2027-01-15T08:00:01.000Z" - - -def test_activity_recovers_oversized_final_tool_activity(tmp_path): - path = write(tmp_path / "updates.jsonl", update("turn_completed", timestamp=1800000001), - update("tool_call_update", "x" * grok_transcript.ACTIVITY_TAIL_BYTES, timestamp=1800000002)) - state = grok_transcript.activity(path) - assert not state["completed"] and state["last_timestamp"] == "2027-01-15T08:00:02.000Z" - - -def test_activity_with_valid_tail_event_never_falls_back_to_full_read(tmp_path, monkeypatch): - path = write(tmp_path / "updates.jsonl", update("user_message_chunk", "x" * grok_transcript.ACTIVITY_TAIL_BYTES), - update("turn_completed", timestamp=1800000002)) - original = grok_transcript.iter_events - reads = [] - - def tracked(path, tail_bytes=0): - reads.append(tail_bytes) - return original(path, tail_bytes) - - monkeypatch.setattr(grok_transcript, "iter_events", tracked) - assert grok_transcript.activity(path)["completed"] - assert reads == [grok_transcript.ACTIVITY_TAIL_BYTES] - - -def test_completion_survives_metadata_until_next_activity(tmp_path): - path = write(tmp_path / "updates.jsonl", update("user_message_chunk", "Prompt"), - update("turn_completed"), update("session_info_update", timestamp=1800000002), - ) - assert grok_transcript.activity(path) == { - "session_id": "sample-session", "last_timestamp": "2027-01-15T08:00:00.000Z", "last_role": "completed", "completed": True, - } - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(update("user_message_chunk", "Continue", timestamp=1800000003)) + "\n") - assert not grok_transcript.activity(path)["completed"] - - -def child_meta(**changes): - return {"subagent_id": "worker-a", "parent_session_id": "sample-session", "child_session_id": "child-session", - "attempt_id": "attempt-a", "status": "running", "started_at": "2027-01-15T08:00:01Z", **changes} - - -def write_meta(path, **changes): - meta = child_meta(**changes) - folder = path.parent / "subagents" / meta["subagent_id"] - folder.mkdir(parents=True, exist_ok=True) - (folder / "meta.json").write_text(json.dumps(meta), encoding="utf-8") - return folder / "meta.json" - - -def child_event(kind, timestamp=1800000001, session="sample-session", **changes): - event = update(kind, timestamp=timestamp, session=session) - event["params"]["update"].update({"subagent_id": "worker-a", "child_session_id": "child-session", "attempt_id": "attempt-a", **changes}) - return event - - -def test_subagents_metadata_finds_child_in_different_cwd_and_preserves_running(tmp_path, monkeypatch): - monkeypatch.setenv("GROK_HOME", str(tmp_path)) - parent = write(tmp_path / "sessions/parent-cwd/sample-session/updates.jsonl", update("turn_completed")) - child = write(tmp_path / "sessions/child-cwd/child-session/updates.jsonl", update("turn_completed", session="child-session")) - write_meta(parent, child_cwd="/different/worktree") - records = grok_transcript.subagent_records(parent) - assert len(records) == 1 - assert records[0]["transcript"] == str(child) - assert records[0]["status"] == "running" - assert records[0]["started_at"] == "2027-01-15T08:00:01.000Z" - assert grok_transcript.subagent_transcripts(parent) == [str(child)] - - -@pytest.mark.parametrize("status", ["completed", "failed", "cancelled"]) -def test_terminal_metadata_wins_over_running_lifecycle(tmp_path, status): - parent = write(tmp_path / "sample-session/updates.jsonl", child_event("subagent_spawned")) - write_meta(parent, status=status, completed_at="2027-01-15T08:00:02Z") - record = grok_transcript.subagent_records(parent)[0] - assert record["status"] == status - assert record["completed_at"] == "2027-01-15T08:00:02.000Z" - assert record["transcript"] == "" - - -def test_lifecycle_fallback_completes_matching_attempt_without_metadata(tmp_path): - parent = write(tmp_path / "sample-session/updates.jsonl", child_event("subagent_spawned"), - child_event("subagent_finished", 1800000003, status="completed")) - record = grok_transcript.subagent_records(parent)[0] - assert record["status"] == "completed" - assert record["started_at"] == "2027-01-15T08:00:01.000Z" - assert record["completed_at"] == "2027-01-15T08:00:03.000Z" - - -def test_old_attempt_finish_does_not_stop_new_attempt(tmp_path): - parent = write(tmp_path / "sample-session/updates.jsonl", child_event("subagent_spawned"), - child_event("subagent_spawned", 1800000002, attempt_id="attempt-b", child_session_id="child-b"), - child_event("subagent_finished", 1800000003, status="completed")) - records = grok_transcript.subagent_records(parent) - assert len(records) == 1 - assert records[0]["attempt_id"] == "attempt-b" and records[0]["status"] == "running" - - -def test_stale_running_metadata_cannot_reverse_terminal_lifecycle(tmp_path): - parent = write(tmp_path / "sample-session/updates.jsonl", child_event("subagent_spawned"), - child_event("subagent_finished", 1800000003, status="completed")) - write_meta(parent, status="running") - record = grok_transcript.subagent_records(parent)[0] - assert record["status"] == "completed" and record["completed_at"] == "2027-01-15T08:00:03.000Z" - - -@pytest.mark.parametrize("meta_started", ["2027-01-15T08:00:01Z", "", "invalid"]) -def test_stale_or_undated_metadata_cannot_replace_newer_lifecycle_attempt(tmp_path, meta_started): - parent = write(tmp_path / "sample-session/updates.jsonl", - child_event("subagent_spawned", 1800000002, attempt_id="attempt-b", child_session_id="child-b")) - write_meta(parent, status="completed", started_at=meta_started, completed_at="2027-01-15T08:00:03Z") - record = grok_transcript.subagent_records(parent)[0] - assert record["attempt_id"] == "attempt-b" and record["status"] == "running" - - -def test_newer_dated_metadata_can_replace_earlier_lifecycle_attempt(tmp_path): - parent = write(tmp_path / "sample-session/updates.jsonl", child_event("subagent_spawned")) - write_meta(parent, attempt_id="attempt-b", child_session_id="child-b", started_at="2027-01-15T08:00:02Z") - assert grok_transcript.subagent_records(parent)[0]["attempt_id"] == "attempt-b" - - -def test_missing_lifecycle_start_time_keeps_known_attempt(tmp_path): - parent = write(tmp_path / "sample-session/updates.jsonl", child_event("subagent_spawned", timestamp="invalid")) - write_meta(parent, attempt_id="attempt-b", child_session_id="child-b", started_at="2027-01-15T08:00:02Z") - assert grok_transcript.subagent_records(parent)[0]["attempt_id"] == "attempt-a" - - -def test_subagent_lifecycle_is_not_lost_outside_activity_tail(tmp_path): - parent = write(tmp_path / "sample-session/updates.jsonl", child_event("subagent_spawned"), - update("session_info_update", "x" * grok_transcript.ACTIVITY_TAIL_BYTES), update("turn_completed")) - records = grok_transcript.subagent_records(parent) - assert len(records) == 1 and records[0]["status"] == "running" - - -@pytest.mark.parametrize("changes", [ - {"parent_session_id": "different-parent"}, {"child_session_id": "../escape"}, - {"status": "unknown"}, {"status": []}, {"attempt_id": []}, {"child_session_id": "sample-session"}, -]) -def test_invalid_metadata_is_rejected(tmp_path, changes): - parent = write(tmp_path / "sample-session/updates.jsonl", update("turn_completed")) - write_meta(parent, **changes) - assert grok_transcript.subagent_records(parent) == [] - - -def test_malformed_metadata_falls_back_to_parent_lifecycle_and_ignores_foreign_events(tmp_path): - parent = write(tmp_path / "sample-session/updates.jsonl", child_event("subagent_spawned"), - child_event("subagent_finished", session="other-parent", status="completed"), - child_event("subagent_finished", parent_session_id="other-parent", status="completed")) - meta = write_meta(parent) - meta.write_text("{broken", encoding="utf-8") - assert grok_transcript.subagent_records(parent)[0]["status"] == "running" - - -def test_optional_attempt_id_and_missing_child_transcript_remain_visible(tmp_path): - parent = write(tmp_path / "sample-session/updates.jsonl", update("turn_completed")) - write_meta(parent, attempt_id=None) - record = grok_transcript.subagent_records(parent)[0] - assert record["attempt_id"] == "" and record["transcript"] == "" and record["status"] == "running" - - -def test_subagent_metadata_and_session_symlinks_cannot_escape_storage(tmp_path, monkeypatch): - monkeypatch.setenv("GROK_HOME", str(tmp_path / "store")) - parent = write(tmp_path / "store/sessions/parent/sample-session/updates.jsonl", update("turn_completed")) - outside = tmp_path / "outside" - write(outside / "child-session/updates.jsonl", update("turn_completed", session="child-session")) - (outside / "worker-a").mkdir() - (outside / "worker-a/meta.json").write_text(json.dumps(child_meta()), encoding="utf-8") - try: - (parent.parent / "subagents").symlink_to(outside, target_is_directory=True) - (tmp_path / "store/sessions/escape").symlink_to(outside, target_is_directory=True) - except OSError as error: - pytest.skip(f"Directory symlinks unavailable: {error}") - assert grok_transcript.subagent_records(parent) == [] - assert grok_transcript.find_transcript("child-session") == "" - - -def test_summary_parent_references_do_not_invent_subagent_relationships(tmp_path, monkeypatch): - monkeypatch.setenv("GROK_HOME", str(tmp_path)) - parent = write(tmp_path / "sessions/parent/sample-session/updates.jsonl", update("turn_completed")) - child = write(tmp_path / "sessions/child/forked-session/updates.jsonl", update("turn_completed", session="forked-session")) - child.with_name("summary.json").write_text(json.dumps({"parent_session_id": "sample-session"}), encoding="utf-8") - assert grok_transcript.subagent_records(parent) == [] - - -def busy_update(kind, timestamp=1800000000, **fields): - return {"timestamp": timestamp, "params": {"sessionId": "sample-session", "update": {"sessionUpdate": kind, **fields}}} - - -def busy_path(tmp_path, *events): - return write(tmp_path / "sample-session" / "updates.jsonl", *events) - - -def test_busy_reasons_idle_after_completed_turn(tmp_path): - path = busy_path(tmp_path, busy_update("user_message_chunk"), busy_update("tool_call", toolCallId="t1"), - busy_update("tool_call_update", toolCallId="t1", status="completed"), busy_update("turn_completed")) - assert grok_transcript.busy_reasons(str(path), now=1800000000) == [] - - -def test_busy_reasons_running_turn_and_open_tool(tmp_path): - path = busy_path(tmp_path, busy_update("turn_completed"), busy_update("user_message_chunk"), - busy_update("tool_call", toolCallId="t2", title="run_terminal_command")) - reasons = grok_transcript.busy_reasons(str(path), now=1800000000) - assert any("turn_completed" in reason for reason in reasons) - assert any("t2" in reason for reason in reasons) - - -def test_busy_reasons_interrupted_turn_tools_do_not_linger(tmp_path): - path = busy_path(tmp_path, busy_update("user_message_chunk"), busy_update("tool_call", toolCallId="t3"), - busy_update("turn_completed", stop_reason="interrupted")) - assert grok_transcript.busy_reasons(str(path), now=1800000000) == [] - - -def test_busy_reasons_background_task_until_completed(tmp_path): - events = [busy_update("user_message_chunk"), - busy_update("task_backgrounded", task_id="bg1", tool_call_id="c1", command="Start-Sleep 75"), - busy_update("background_tasks", tasks=[{"task_id": "bg1", "status": "running", "description": "sleep"}]), - busy_update("turn_completed")] - path = busy_path(tmp_path, *events) - assert any("bg1" in reason for reason in grok_transcript.busy_reasons(str(path), now=1800000000)) - path = busy_path(tmp_path, *events, busy_update("task_completed", task_snapshot={"task_id": "bg1", "status": "completed"}), - busy_update("background_tasks", tasks=[])) - assert grok_transcript.busy_reasons(str(path), now=1800000000) == [] - - -def test_busy_reasons_background_subagent_and_wake(tmp_path): - spawned = busy_update("subagent_spawned", subagent_id="sub1", attempt_id="at1.abc", parent_session_id="sample-session", - child_session_id="sub1", description="sleep then reply") - path = busy_path(tmp_path, busy_update("user_message_chunk"), spawned, busy_update("turn_completed")) - assert any("sub1" in reason for reason in grok_transcript.busy_reasons(str(path), now=1800000000)) - finished = busy_update("subagent_finished", timestamp=1800000100, subagent_id="sub1", attempt_id="at1.abc", - child_session_id="sub1", status="completed", will_wake=True) - path = busy_path(tmp_path, busy_update("user_message_chunk"), spawned, busy_update("turn_completed"), finished) - assert any("will_wake" in reason for reason in grok_transcript.busy_reasons(str(path), now=1800000110)) - assert grok_transcript.busy_reasons(str(path), now=1800000100 + grok_transcript.WAKE_GRACE_SECONDS + 1) == [] - - -def test_busy_reasons_reads_subagent_meta_status(tmp_path): - path = busy_path(tmp_path, busy_update("user_message_chunk"), busy_update("turn_completed")) - meta = path.parent / "subagents" / "sub9" / "meta.json" - meta.parent.mkdir(parents=True) - meta.write_text(json.dumps({"subagent_id": "sub9", "parent_session_id": "sample-session", "status": "running"}), encoding="utf-8") - assert any("sub9" in reason for reason in grok_transcript.busy_reasons(str(path), now=1800000000)) - meta.write_text(json.dumps({"subagent_id": "sub9", "parent_session_id": "sample-session", "status": "completed"}), encoding="utf-8") - assert grok_transcript.busy_reasons(str(path), now=1800000000) == [] - - -def test_busy_reasons_events_jsonl_open_turn(tmp_path): - path = busy_path(tmp_path, busy_update("user_message_chunk"), busy_update("turn_completed")) - (path.parent / "events.jsonl").write_text(json.dumps({"type": "turn_ended"}) + "\n" + json.dumps({"type": "turn_started"}) + "\n", encoding="utf-8") - assert any("events.jsonl" in reason for reason in grok_transcript.busy_reasons(str(path), now=1800000000)) diff --git a/tests/integration/grok/test_han_state.py b/tests/integration/grok/test_han_state.py deleted file mode 100644 index e66b42d..0000000 --- a/tests/integration/grok/test_han_state.py +++ /dev/null @@ -1,533 +0,0 @@ -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest -from chef.guards import adapters as guard_adapters - -from tests.paths import PLUGIN_ROOT - -SCRIPT = (PLUGIN_ROOT / 'grok') / "scripts" / "han_state.py" - -from chef.guards import mission as mission_guard -from chef.runtimes.grok import state as han_state - - -def write_json(path, payload): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") - - -def adapter_body(project="base"): - return { - "schema": 1, - "project": project, - "paths": {"stateDir": "_My/missions"}, - "runtimes": {"codex": {"project": "codex-only"}}, - } - - -def plant(folder, kind, project="base"): - path = folder / kind / "orchestrator" / "adapter.json" - write_json(path, adapter_body(project)) - return path - - -def isolate_registry(monkeypatch, tmp_path): - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - monkeypatch.delenv("HAN_REPO", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", raising=False) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - home = tmp_path / "codex-home" - home.mkdir() - monkeypatch.setenv("CODEX_HOME", str(home)) - monkeypatch.setattr(guard_adapters, "in_place_adapters_dir", lambda: str(tmp_path / "missing-adapters")) - - -def test_grok_walk_prefers_nearest_then_grok_claude_codex(tmp_path, monkeypatch): - isolate_registry(monkeypatch, tmp_path) - parent = tmp_path / "parent" - child = parent / "child" - child.mkdir(parents=True) - plant(parent, ".grok", "parent-grok") - plant(parent, ".codex", "parent-codex") - claude = plant(child, ".claude", "child-claude") - plant(child, ".codex", "child-codex") - found = mission_guard.find_adapter({"cwd": str(child), "han_runtime": "grok"}) - assert Path(found.adapter_path) == claude - grok = plant(child, ".grok", "child-grok") - found = mission_guard.find_adapter({"cwd": str(child), "han_runtime": "grok"}) - assert Path(found.adapter_path) == grok - - -def test_claude_and_codex_ignore_grok_adapter(tmp_path, monkeypatch): - isolate_registry(monkeypatch, tmp_path) - project = tmp_path / "game" - project.mkdir() - plant(project, ".grok") - empty = tmp_path / "empty-registry" - empty.mkdir() - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(empty)) - for runtime in ("claude", "codex"): - with pytest.raises(mission_guard.AdapterNotFound): - mission_guard.find_adapter({"cwd": str(project), "han_runtime": runtime}) - codex = plant(project, ".codex", "codex") - found = mission_guard.find_adapter({"cwd": str(project), "han_runtime": "codex"}) - assert Path(found.adapter_path) == codex - assert ".grok" not in found.adapter_path - - -def test_grok_falls_back_to_codex_adapter_and_ignores_claude_project_dir(tmp_path, monkeypatch): - isolate_registry(monkeypatch, tmp_path) - project = tmp_path / "game" - other = tmp_path / "other" - project.mkdir() - other.mkdir() - codex = plant(project, ".codex", "from-codex") - plant(other, ".grok", "from-env") - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(other)) - found = mission_guard.find_adapter({"cwd": str(project), "han_runtime": "grok"}) - assert Path(found.adapter_path) == codex - - -def test_grok_registry_order_skips_claude_and_codex_config(tmp_path, monkeypatch): - isolate_registry(monkeypatch, tmp_path) - repo = tmp_path / "han-repo" - repo_adapters = repo / "adapters" - (repo_adapters / "game").mkdir(parents=True) - env_adapters = tmp_path / "env-adapters" - env_adapters.mkdir() - plugin_adapters = tmp_path / "plugin-adapters" - plugin_adapters.mkdir() - config_adapters = tmp_path / "config-adapters" - config_adapters.mkdir() - codex_home = Path(os.environ["CODEX_HOME"]) - (codex_home / "config.toml").write_text( - f'[shell_environment_policy.set]\nHAN_ADAPTERS_DIR = "{config_adapters.as_posix()}"\n', - encoding="utf-8", - ) - monkeypatch.setenv("HAN_REPO", str(repo)) - assert mission_guard.resolve_registry("grok") == mission_guard.Registry(str(repo_adapters), "hanRepo") - assert mission_guard.resolve_registry("claude") == mission_guard.Registry("", "none") - assert mission_guard.resolve_registry("codex") == mission_guard.Registry(str(config_adapters), "codexConfig") - monkeypatch.setenv("CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", str(plugin_adapters)) - assert mission_guard.resolve_registry("grok") == mission_guard.Registry(str(repo_adapters), "hanRepo") - assert mission_guard.resolve_registry("claude") == mission_guard.Registry(str(plugin_adapters), "userConfig") - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(env_adapters)) - assert mission_guard.resolve_registry("grok") == mission_guard.Registry(str(env_adapters), "env") - monkeypatch.delenv("HAN_ADAPTERS_DIR") - monkeypatch.setenv("HAN_REPO", str(tmp_path / "missing-repo")) - with pytest.raises(mission_guard.GuardOff, match="HAN_REPO/adapters 없음"): - mission_guard.resolve_registry("grok") - - -def test_grok_registry_matches_projects_json(tmp_path, monkeypatch): - isolate_registry(monkeypatch, tmp_path) - project = tmp_path / "work" - project.mkdir() - registry = tmp_path / "adapters" - write_json(registry / "game" / "adapter.json", adapter_body("registered")) - write_json(registry / "projects.json", [{"adapter": "game", "roots": [str(project)]}]) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - found = mission_guard.find_adapter({"cwd": str(project / "nested"), "han_runtime": "grok"}) - assert found.project == str(project) - assert found.adapter_path == str(registry / "game" / "adapter.json") - - -def test_snapshot_reads_state_without_writes(tmp_path): - project = tmp_path / "game" - plant(project, ".grok") - write_json( - project / ".grok" / "orchestrator" / "local.json", - {"project": "from-local"}, - ) - state = project / "_My" / "missions" - mission = state / "20261026-demo" - mission.mkdir(parents=True) - (state / "ACTIVE").write_text( - json.dumps({"id": "20261026-demo", "session": "sess", "openedAt": "2026-10-26T00:00:00+09:00"}), - encoding="utf-8", - ) - (mission / "mission.md").write_text( - "# 미션\n\n상태: 진행\n현재 단계: impl\n확인 A: 승인\n확인 B: 대기\n확인 C: 대기\n\n## 목표\n\n버튼 입력을 서버로 보낸다\n", - encoding="utf-8", - ) - closed = state / "20261001-old" - closed.mkdir() - (closed / "mission.md").write_text("상태: 닫힘\n현재 단계: review\n\n## 목표\n\n지난 일\n", encoding="utf-8") - stale = state / "20261026-stale" - stale.mkdir() - (stale / "mission.md").write_text("상태: 진행\n현재 단계: content\n\n## 목표\n\n끊긴 조사\n", encoding="utf-8") - slot = tmp_path / "slots" / "slot1" - slot_mission = slot / "_My" / "missions" / "20261026-slot" - slot_mission.mkdir(parents=True) - (slot / "_My" / "missions" / "ACTIVE").write_text( - json.dumps({"id": "20261026-slot", "session": "slot-sess", "openedAt": "2026-10-26T01:00:00+09:00"}), - encoding="utf-8", - ) - (slot_mission / "mission.md").write_text("상태: 진행\n현재 단계: poc\n\n## 목표\n\n슬롯 일\n", encoding="utf-8") - idle = tmp_path / "slots" / "slot2" - idle.mkdir(parents=True) - (state / "slots.tsv").write_text( - "name\tpath\tclient\tcreated\tsynced\tstate\n" - f"slot1\t{slot}\tclient_slot1\t2026-10-26T00:00:00+09:00\t2026-10-26T00:00:00+09:00\tready\n" - f"slot2\t{idle}\tclient_slot2\t2026-10-26T00:00:00+09:00\t-\tready\n", - encoding="utf-8", - ) - before = sorted(path.relative_to(tmp_path).as_posix() for path in tmp_path.rglob("*")) - lines = han_state.build_snapshot(str(project / "Unity")).lines - text = "\n".join(lines) - after = sorted(path.relative_to(tmp_path).as_posix() for path in tmp_path.rglob("*")) - assert before == after - assert "프로젝트: from-local" in text - assert "codex-only" not in text - assert "20261026-demo [ACTIVE] 상태=진행 단계=impl 확인 A=승인 확인 B=대기 확인 C=대기 목표=버튼 입력을 서버로 보낸다" in text - assert "20261026-stale [진행, ACTIVE 아님]" in text - assert "20261001-old" not in text - assert f"slot1 state=ready" in text and "active=20261026-slot 상태=진행 단계=poc" in text - assert "비어 있는 ready 슬롯: slot2" in text - assert "지난 일" not in text - - -def test_snapshot_uses_grok_runtime_state_paths_and_local_precedence(tmp_path): - project = tmp_path / "game" - path = plant(project, ".claude") - adapter = adapter_body() - adapter["runtimes"]["grok"] = {"project": "grok-base", "paths": {"stateDir": "grok-state"}} - write_json(path, adapter) - state = project / "local-grok-state" - state.mkdir() - (state / "ACTIVE").write_text(json.dumps({"id": "demo", "session": "grok-session"}), encoding="utf-8") - write_json(path.parent / "local.json", { - "project": "local-base", - "paths": {"stateDir": "local-base-state"}, - "runtimes": {"grok": {"project": "grok-local", "paths": {"stateDir": "local-grok-state"}}}, - }) - before = sorted(item.relative_to(tmp_path).as_posix() for item in tmp_path.rglob("*")) - snapshot = han_state.build_snapshot(str(project)) - assert "프로젝트: grok-local" in snapshot.lines - assert f"상태 폴더: {state}" in snapshot.lines - assert snapshot.active.id == "demo" - assert before == sorted(item.relative_to(tmp_path).as_posix() for item in tmp_path.rglob("*")) - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -@pytest.mark.parametrize("local_override", [False, True]) -def test_brief_reads_target_runtime_state(tmp_path, runtime, local_override): - project = tmp_path / "game" - path = plant(project, ".grok") - adapter = adapter_body() - adapter["runtimes"]["grok"] = {"project": "grok-only", "paths": {"stateDir": "grok-state"}} - adapter["runtimes"]["codex"]["paths"] = {"stateDir": "codex-state"} - write_json(path, adapter) - expected = {"claude": ("base", "_My/missions"), "codex": ("codex-only", "codex-state"), "grok": ("grok-only", "grok-state")} - if local_override: - write_json(path.parent / "local.json", { - "project": "local-base", "paths": {"stateDir": "local-state"}, - "runtimes": { - "codex": {"project": "local-codex", "paths": {"stateDir": "local-codex-state"}}, - "grok": {"project": "local-grok", "paths": {"stateDir": "local-grok-state"}}, - }, - }) - expected = {"claude": ("local-base", "local-state"), "codex": ("local-codex", "local-codex-state"), "grok": ("local-grok", "local-grok-state")} - name, state_dir = expected[runtime] - state = project / state_dir - state.mkdir(parents=True) - (state / "ACTIVE").write_text(json.dumps({"id": runtime, "session": "session"}), encoding="utf-8") - lines = han_state.build_brief(str(project), "inspect", runtime) - assert f"프로젝트: {name}" in lines - assert f"상태 폴더: {state}" in lines - assert any(f"메인 ACTIVE가 이미 있다 ({runtime})" in line for line in lines) - - -def test_brief_mentions_existing_work_and_does_not_write(tmp_path): - project = tmp_path / "game" - plant(project, ".claude", "shared") - state = project / "_My" / "missions" - state.mkdir(parents=True) - (state / "ACTIVE").write_text(json.dumps({"id": "20261026-demo", "session": "sess", "openedAt": ""}), encoding="utf-8") - before = sorted(path.relative_to(project).as_posix() for path in project.rglob("*")) - text = "\n".join(han_state.build_brief(str(project), " 버튼\n입력 ", "codex")) - after = sorted(path.relative_to(project).as_posix() for path in project.rglob("*")) - assert before == after - assert "사람이 그 세션에 붙일 문장: $chef:chef-mission 버튼 입력" in text - assert "메인 ACTIVE가 이미 있다 (20261026-demo)" in text - assert "Grok은 이 문장을 실행하지 않는다." in text - claude = "\n".join(han_state.build_brief(str(project), "조사", "claude")) - assert "사람이 그 세션에 붙일 문장: /chef:mission 조사" in claude - - -def test_grok_brief_targets_main_or_registered_slot_and_does_not_write(tmp_path): - project = tmp_path / "game" - plant(project, ".grok", "shared") - state = project / "_My" / "missions" - state.mkdir(parents=True) - slot = tmp_path / "slots" / "slot2" - slot.mkdir(parents=True) - busy = tmp_path / "slots" / "slot1" - busy_mission = busy / "_My" / "missions" / "20261026-slot" - busy_mission.mkdir(parents=True) - (busy / "_My" / "missions" / "ACTIVE").write_text( - json.dumps({"id": "20261026-slot", "session": "slot-sess", "openedAt": ""}), - encoding="utf-8", - ) - (busy_mission / "mission.md").write_text("상태: 진행\n현재 단계: poc\n\n## 목표\n\n슬롯 일\n", encoding="utf-8") - (state / "slots.tsv").write_text( - "name\tpath\tclient\tcreated\tsynced\tstate\n" - f"slot1\t{busy}\tclient_slot1\t2026-10-26T00:00:00+09:00\t2026-10-26T00:00:00+09:00\tready\n" - f"slot2\t{slot}\tclient_slot2\t2026-10-26T00:00:00+09:00\t-\tready\n", - encoding="utf-8", - ) - before = sorted(path.relative_to(project).as_posix() for path in project.rglob("*")) - main_text = "\n".join(han_state.build_brief(str(project), " 버튼\n입력 ", "grok")) - slot_text = "\n".join(han_state.build_brief(str(project), "슬롯 작업", "grok", "slot2")) - busy_text = "\n".join(han_state.build_brief(str(project), "겹침", "grok", "slot1")) - after = sorted(path.relative_to(project).as_posix() for path in project.rglob("*")) - assert before == after - assert "실행 대상: main (메인)" in main_text - assert "SendToAgent:" in main_text and "대상: main" in main_text - assert f"프로젝트 경로: {project}" in main_text - assert "목표: 버튼 입력" in main_text - assert "쓰기 확인:" in main_text and "실행 규칙:" in main_text - assert "/chef:mission" not in main_text and "$chef:chef-mission" not in main_text - assert "실행 대상: slot2 (slot2)" in slot_text - assert f"프로젝트 경로: {slot}" in slot_text - assert "slot1 은 이미 미션이 붙어 있다" in busy_text - with pytest.raises(han_state.Usage, match="등록되지 않은 슬롯: slot9"): - han_state.build_brief(str(project), "x", "grok", "slot9") - - -def test_grok_brief_uses_local_main_and_configured_slot_names(tmp_path): - main = tmp_path / "main" - slot_root = tmp_path / "workspaces" - slot = slot_root / "worker-Delta" - slot.mkdir(parents=True) - adapter_path = plant(slot, ".grok", "shared") - write_json( - adapter_path.parent / "local.json", - {"vars": {"main": str(main)}, "slots": {"root": str(slot_root), "names": ["worker-Delta"]}}, - ) - state = main / "_My" / "missions" - state.mkdir(parents=True) - (state / "ACTIVE").write_text( - json.dumps({"id": "20261026-main", "session": "main-session", "openedAt": ""}), - encoding="utf-8", - ) - main_text = "\n".join(han_state.build_brief(str(slot / "Editor"), "메인 작업", "grok", "main")) - slot_text = "\n".join(han_state.build_brief(str(slot / "Editor"), "슬롯 작업", "grok")) - explicit = "\n".join(han_state.build_brief(str(slot), "슬롯 작업", "grok", "worker-Delta")) - assert "메인 ACTIVE: 20261026-main session=main-session" in main_text - assert "메인 ACTIVE가 이미 있다 (20261026-main)" in main_text - assert "대상: main" in main_text and f"프로젝트 경로: {main}" in main_text - assert "대상: worker-Delta" in slot_text and f"프로젝트 경로: {slot}" in slot_text - assert "대상: worker-Delta" in explicit and f"프로젝트 경로: {slot}" in explicit - with pytest.raises(han_state.Usage, match="등록되지 않은 슬롯"): - han_state.build_brief(str(slot), "슬롯 작업", "grok", "worker-delta") - - -def test_grok_brief_prefers_recorded_path_and_longest_containing_slot(tmp_path): - project = tmp_path / "main" - adapter_path = plant(project, ".grok", "shared") - write_json( - adapter_path.parent / "local.json", - {"slots": {"root": str(tmp_path / "default-slots"), "names": ["review", "worker"]}}, - ) - state = project / "_My" / "missions" - state.mkdir(parents=True) - parent_slot = project / "workspaces" / "review" - nested_slot = parent_slot / "worker" - nested_slot.mkdir(parents=True) - (state / "slots.tsv").write_text( - "name\tpath\tstate\n" - f"review\t{parent_slot}\tready\n" - f"worker\t{nested_slot}\tready\n", - encoding="utf-8", - ) - inferred = "\n".join(han_state.build_brief(str(nested_slot / "Editor"), "작업", "grok")) - explicit = "\n".join(han_state.build_brief(str(project), "작업", "grok", "worker")) - outside = "\n".join(han_state.build_brief(str(parent_slot) + "-other", "작업", "grok")) - assert "대상: worker" in inferred and f"프로젝트 경로: {nested_slot}" in inferred - assert "대상: worker" in explicit and f"프로젝트 경로: {nested_slot}" in explicit - assert "대상: main" in outside and f"프로젝트 경로: {project}" in outside - - -def test_grok_brief_rejects_slot_without_a_registered_path(tmp_path): - project = tmp_path / "game" - adapter_path = plant(project, ".grok") - write_json(adapter_path.parent / "local.json", {"slots": {"names": ["worker"]}}) - with pytest.raises(han_state.Usage, match="등록되지 않은 슬롯: worker"): - han_state.build_brief(str(project), "작업", "grok", "worker") - main_text = "\n".join(han_state.build_brief(str(project), "작업", "grok")) - assert "대상: main" in main_text and f"프로젝트 경로: {project}" in main_text - - -@pytest.mark.parametrize("table_exists", [False, True]) -@pytest.mark.parametrize("corrupt", [False, True]) -def test_snapshot_checks_configured_slot_active_without_table_or_row(tmp_path, table_exists, corrupt): - main = tmp_path / "main" - slot_root = tmp_path / "workspaces" - slot = slot_root / "worker" - slot_state = slot / "_My" / "missions" - slot_state.mkdir(parents=True) - (slot_root / "waiting").mkdir() - adapter_path = plant(slot, ".grok", "shared") - write_json( - adapter_path.parent / "local.json", - {"vars": {"main": str(main)}, "slots": {"root": str(slot_root), "names": ["worker", "waiting"]}}, - ) - if table_exists: - state = main / "_My" / "missions" - state.mkdir(parents=True) - (state / "slots.tsv").write_text( - f"name\tpath\tstate\nlisted\t{tmp_path / 'missing'}\tpending\n", - encoding="utf-8", - ) - active_text = "{invalid" if corrupt else json.dumps({"id": "20261026-busy", "session": "slot-session", "openedAt": ""}) - (slot_state / "ACTIVE").write_text(active_text, encoding="utf-8") - snapshot = han_state.build_snapshot(str(slot / "Editor")) - brief = "\n".join(han_state.build_brief(str(slot / "Editor"), "새 작업", "grok")) - assert f"worker state=미확인 synced=- path={slot}" in brief - assert "waiting state=미확인" in brief - assert snapshot.idle_slots == () - assert "비어 있는 ready 슬롯: 없음" in brief - assert "대상: worker" in brief - if corrupt: - assert "active=손상" in brief - assert "경고: worker ACTIVE가 손상되어 있다" in brief - assert snapshot.busy_slots == () - else: - assert "active=20261026-busy" in brief - assert "슬롯 ACTIVE가 있다 (worker:20261026-busy)" in brief - assert "worker 은 이미 미션이 붙어 있다" in brief - assert snapshot.busy_slots == ("worker:20261026-busy",) - - -def test_grok_skill_registration_names(): - skills = SCRIPT.parents[1] / "skills" - registered = ( - "chef-status", "chef-doctor", "chef-mission-brief", "chef-run", - "chef-mission", "chef-slots", "chef-adapter-init", "chef-distill", - ) - plugin = SCRIPT.parents[2] - manifest = json.loads((plugin / ".grok-plugin/plugin.json").read_text(encoding="utf-8")) - paths = manifest["skills"] - assert len(paths) == 8 - assert set(paths) == {f"./grok/skills/{name}" for name in registered} - names = {Path(path).name for path in paths} - assert "chef-watch" not in names and "chef-handoff" not in names - for path in paths: - name = Path(path).name - text = (plugin / path / "SKILL.md").read_text(encoding="utf-8") - assert f"name: {name}\n" in text - run = (skills / "chef-run" / "SKILL.md").read_text(encoding="utf-8") - assert "CLAUDE.md" in run and ".claude/rules/" in run - assert "chef grok-state snapshot" in run and "chef mission active --runtime grok" in run - assert "~/.grok/rules/" in run and "submit" in run - mission = (skills / "chef-mission" / "SKILL.md").read_text(encoding="utf-8") - slot_skill = (skills / "chef-slots" / "SKILL.md").read_text(encoding="utf-8") - adapter = (skills / "chef-adapter-init" / "SKILL.md").read_text(encoding="utf-8") - distill = (skills / "chef-distill" / "SKILL.md").read_text(encoding="utf-8") - assert "--runtime grok" in mission and 'python "/chef_cli.py"' in mission - assert "../../../shared/skills/mission.md" in mission and "--force-tier" in mission - assert "사람에게 묻는 법" not in mission and "ACTIVE" in mission - assert "chef slots --runtime grok" in slot_skill and "chef-run" in slot_skill - assert "ready" in slot_skill and "chef-watch" not in slot_skill - assert "../../../shared/skills/adapter-init.md" in adapter - assert "adapter-schema.md" in adapter and "pluginConfigs" in adapter - adapter_shared = (plugin / "shared/skills/adapter-init.md").read_text(encoding="utf-8") - assert "chef guard-check --runtime" in adapter_shared - assert "../../../shared/skills/distill.md" in distill - assert "--transcript" in distill and "HAN_TRANSCRIPT" in distill - distill_shared = (plugin / "shared/skills/distill.md").read_text(encoding="utf-8") - assert "chef distill --runtime <런타임> extract --transcript" in distill_shared - watch = (skills / "chef-watch" / "SKILL.md").read_text(encoding="utf-8") - handoff = (skills / "chef-handoff" / "SKILL.md").read_text(encoding="utf-8") - assert "등록하는 스킬이 아니다" in watch and "chef-status" in watch and "chef-doctor" in watch - assert "등록하는 스킬이 아니다" in handoff and "chef-mission-brief" in handoff - assert "실행 봇" in handoff and "SendToAgent" in handoff - brief = (skills / "chef-mission-brief" / "SKILL.md").read_text(encoding="utf-8") - assert "SendToAgent" in brief and "실행 대상" in brief and "" in brief - assert "--runtime claude" in brief and "--runtime codex" in brief - status = (skills / "chef-status" / "SKILL.md").read_text(encoding="utf-8") - doctor = (skills / "chef-doctor" / "SKILL.md").read_text(encoding="utf-8") - assert "실행 봇" in status and "읽기" in status - assert "Claude·Codex의 chef가 맡는다" not in status - assert "읽기 전용" in doctor and "chef-mission-brief" in doctor - readme = (SCRIPT.parents[1] / "README.md").read_text(encoding="utf-8") - for name in registered: - assert name in readme - assert "chef-watch" in readme and "등록하지 않는다" in readme - assert "" in readme and "" in readme and "실행 규칙" in readme - - -def test_grok_native_role_registration_and_runtime_settings(): - plugin = SCRIPT.parents[2] - manifest = json.loads((plugin / ".grok-plugin/plugin.json").read_text(encoding="utf-8")) - assert manifest["agents"] == ["./grok/agents"] - expected = {"researcher": "medium", "dev-small": "medium", "dev-medium": "high", "verifier": "low", "code-reviewer": "high", "reviewer-small": "medium"} - agent_dir = plugin / manifest["agents"][0] - assert {path.stem for path in agent_dir.glob("*.md")} == set(expected) - for name, effort in expected.items(): - text = (agent_dir / f"{name}.md").read_text(encoding="utf-8") - assert text.startswith("---\n") - fields = dict(line.split(": ", 1) for line in text.split("---", 2)[1].strip().splitlines()) - assert fields["name"] == name - assert fields["model"] == "inherit" - assert fields["effort"] == effort - role_reference = (plugin / "grok/skills/chef-mission/references/grok-roles.md").read_text(encoding="utf-8") - for name in expected: - assert f"chef:{name}" in role_reference - assert "runtimes.grok.roles" in role_reference - assert "`chef:reviewer-small`, `chef_reviewer_small` → `chef:reviewer-small`" in role_reference - assert "→ `chef:code-reviewer`" in role_reference and "chef:reviewer-small` → `chef:code-reviewer`" not in role_reference - assert "chef:reviewer-small` → `chef:reviewer`" not in role_reference and "grok/agents/reviewer.md" not in role_reference - assert "summary.json" in role_reference and "reasoning_effort" in role_reference - - -def test_cli_snapshot_and_missing_adapter(tmp_path): - project = tmp_path / "game" - plant(project, ".grok", "cli-game") - env = os.environ.copy() - env.pop("HAN_REPO", None) - env.pop("CLAUDE_PROJECT_DIR", None) - seen = subprocess.run( - [sys.executable, str(SCRIPT), "snapshot", "--project", str(project)], - capture_output=True, - text=True, - encoding="utf-8", - env=env, - check=False, - ) - assert seen.returncode == 0, seen.stderr - assert "프로젝트: cli-game" in seen.stdout - assert "메인 ACTIVE: 없음" in seen.stdout - empty = tmp_path / "empty" - empty.mkdir() - missing_project = tmp_path / "nowhere" - missing_project.mkdir() - env["HAN_ADAPTERS_DIR"] = str(empty) - missing = subprocess.run( - [sys.executable, str(SCRIPT), "snapshot", "--project", str(missing_project)], - capture_output=True, - text=True, - encoding="utf-8", - env=env, - check=False, - ) - assert missing.returncode == 2 - assert "projects.json 없음" in missing.stderr - assert missing.stdout == "" - brief = subprocess.run( - [sys.executable, str(SCRIPT), "brief", "--project", str(project), "--goal", "버튼"], - capture_output=True, - text=True, - encoding="utf-8", - env=env, - check=False, - ) - assert brief.returncode == 0, brief.stderr - assert "SendToAgent:" in brief.stdout - assert "대상: main" in brief.stdout - assert "/chef:mission" not in brief.stdout diff --git a/tests/integration/grok/test_p4c.py b/tests/integration/grok/test_p4c.py deleted file mode 100644 index 989839f..0000000 --- a/tests/integration/grok/test_p4c.py +++ /dev/null @@ -1,53 +0,0 @@ -import json -import subprocess -import sys -from pathlib import Path - -from tests.paths import PLUGIN_ROOT - -SCRIPT = (PLUGIN_ROOT / 'grok/skills/chef-mission/scripts/p4c.py') - - -def test_grok_p4_wrapper_uses_grok_adapter_and_runtime_client(tmp_path): - project = tmp_path / "project" - adapter_dir = project / ".grok" / "orchestrator" - adapter_dir.mkdir(parents=True) - adapter = { - "schema": 1, - "vars": {"main": str(project)}, - "slots": {"mainClient": "base-client"}, - "runtimes": {"grok": {"slots": {"mainClient": "grok-client"}}}, - } - (adapter_dir / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - result = subprocess.run( - [sys.executable, str(SCRIPT), "--project", str(project), "--dry-run", "edit", "example.txt"], - capture_output=True, - text=True, - encoding="utf-8", - timeout=30, - ) - assert result.returncode == 0, result.stderr - assert result.stdout.strip() == "p4 -c grok-client edit example.txt" - - -def test_grok_p4_wrapper_rejects_client_from_another_runtime(tmp_path): - project = tmp_path / "project" - adapter_dir = project / ".grok" / "orchestrator" - adapter_dir.mkdir(parents=True) - adapter = { - "schema": 1, - "vars": {"main": str(project)}, - "slots": {"mainClient": "base-client"}, - "runtimes": {"grok": {"slots": {"mainClient": "grok-client"}}}, - } - (adapter_dir / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - result = subprocess.run( - [sys.executable, str(SCRIPT), "--project", str(project), "--client", "base-client", "--dry-run", "edit", "example.txt"], - capture_output=True, - text=True, - encoding="utf-8", - timeout=30, - ) - assert result.returncode == 2 - assert "grok-client" in result.stderr - assert result.stdout == "" diff --git a/tests/integration/grok/test_process_discovery.py b/tests/integration/grok/test_process_discovery.py deleted file mode 100644 index ff64446..0000000 --- a/tests/integration/grok/test_process_discovery.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Grok process ownership checks without real runtime or process mutation.""" - -import os -import shutil -import subprocess -import sys -from types import SimpleNamespace - -import pytest - -from chef.runtimes.grok import injection - - -def test_headless_injection_carries_hook_python_without_system_alias(tmp_path, monkeypatch): - transcript = tmp_path / "updates.jsonl" - transcript.write_text("") - monkeypatch.setenv("GROK_BIN", "/fictional/grok") - monkeypatch.setattr(injection, "session_files", lambda *_: str(transcript)) - monkeypatch.setattr(injection, "session_cwd", lambda *_: str(tmp_path)) - monkeypatch.setattr(injection, "wait_idle", lambda *_: []) - monkeypatch.setattr(injection, "grok_processes", lambda: {}) - monkeypatch.setattr(injection, "open_tuis", lambda *_: []) - monkeypatch.setattr(injection.grok_transcript, "busy_reasons", lambda *_: []) - monkeypatch.setattr(injection, "user_turn_since", lambda *_: True) - def spawn(argv, log, environment): - python = shutil.which("python", path=environment["PATH"]) - actual = subprocess.check_output([python, "-c", "import sys; print(sys.prefix)"], env=environment, text=True, timeout=10) - assert actual.strip() == sys.prefix - return SimpleNamespace(pid=123) - monkeypatch.setattr(injection, "spawn_detached", spawn) - environment = {**os.environ, "PATH": os.defpath, "XDG_CACHE_HOME": str(tmp_path / "cache")} - assert injection.inject(str(tmp_path), "11111111-1111-4111-8111-111111111111", "fictional reply", - env=environment, out=lambda *_: None) == injection.OK - - -@pytest.fixture -def posix(monkeypatch): - monkeypatch.setattr(injection, "os", SimpleNamespace(name="posix", path=os.path, environ=os.environ)) - - -def test_process_discovery_handles_spaces_native_and_node_entrypoints(posix, monkeypatch): - names = "11 /fictional/Tools With Spaces/grok\n12 /usr/bin/node\n13 node\n14 node\n15 unrelated\n" - arguments = ( - "11 /fictional/Tools With Spaces/grok --resume session\n" - "12 /usr/bin/node /fictional/grok.js --resume session\n" - "13 node /fictional/other.js grok.js\n" - "14 node -e 'console.log(\"grok\")'\n" - "15 /fictional/other --argument grok\n" - ) - monkeypatch.setattr(injection.subprocess, "run", lambda command, **kwargs: - SimpleNamespace(returncode=0, stdout=names if command[-1] == "pid=,comm=" else arguments)) - found = injection.grok_processes() - assert set(found) == {11, 12} - assert "Tools With Spaces" in found[11] - - -def test_node_process_matches_configured_entry_script_with_unquoted_spaces(posix, tmp_path, monkeypatch): - script = tmp_path / "Tools With Spaces" / "index.js" - script.parent.mkdir() - script.write_text("// fictional entrypoint") - monkeypatch.setenv("GROK_BIN", str(script)) - # Exercise the POSIX process-list format even on a Windows test host. - rendered = script.as_posix() - assert injection.node_grok_command(f"/usr/bin/node {rendered} --resume session") - assert injection.node_grok_command(f'/usr/bin/node --require helper "{rendered}" --resume session') - assert not injection.node_grok_command(f"/usr/bin/node /fictional/other.js {rendered}") - - -@pytest.mark.parametrize("failed", ["pid=,comm=", "pid=,args="]) -def test_failed_process_listing_is_not_an_empty_success(posix, monkeypatch, failed): - monkeypatch.setattr(injection.subprocess, "run", lambda command, **kwargs: - SimpleNamespace(returncode=1 if command[-1] == failed else 0, stdout="")) - with pytest.raises(injection.InjectError, match="실패"): - injection.grok_processes() - - -def test_process_listing_exception_fails_closed(posix, monkeypatch): - def failed(*args, **kwargs): - raise subprocess.TimeoutExpired("ps", 30) - monkeypatch.setattr(injection.subprocess, "run", failed) - with pytest.raises(injection.InjectError, match="실패"): - injection.grok_processes() - - -def test_powershell_listing_nonzero_exit_fails_closed(monkeypatch): - monkeypatch.setattr(injection, "os", SimpleNamespace(name="nt", path=os.path, environ=os.environ)) - monkeypatch.setattr(injection.subprocess, "run", lambda *args, **kwargs: - SimpleNamespace(returncode=1, stdout="")) - with pytest.raises(injection.InjectError, match="실패"): - injection.grok_processes() - - -def test_session_directory_aliases_have_same_physical_identity(tmp_path): - target = tmp_path / "garden" - target.mkdir() - alias = tmp_path / "shortcut" - try: - alias.symlink_to(target, target_is_directory=True) - except OSError: - pytest.skip("directory links unavailable") - assert injection.same_dir(target, alias) - assert not injection.same_dir(target, tmp_path / "other") diff --git a/tests/integration/hermes/test_attachments.py b/tests/integration/hermes/test_attachments.py deleted file mode 100644 index aa3fa17..0000000 --- a/tests/integration/hermes/test_attachments.py +++ /dev/null @@ -1,324 +0,0 @@ -"""Named bridge transport and shared worker admission with invented data.""" - -import contextlib -import json -import os -from pathlib import Path -import sys -import time -from types import SimpleNamespace - -import pytest - -from chef.guards import adapters, mission -from chef.infrastructure.locking import LockBusy -from chef.runtimes.hermes import attachment, workers - - -@pytest.fixture -def project(tmp_path, monkeypatch): - root = tmp_path / "orchard" - root.mkdir() - selected = root / ".hermes/orchestrator/adapter.json" - selected.parent.mkdir(parents=True) - selected.write_text(json.dumps({"schema": 1, "project": "imaginary-orchard", "paths": {"stateDir": "state"}, - "agents": {"allow": ["chef:*"]}, - "guard": {"deny": [{"pattern": "forbidden-action", "reason": "fictional policy"}]}}), encoding="utf-8") - state = root / "state" - (state / "orchard-mission").mkdir(parents=True) - (state / "orchard-mission/mission.md").write_text("# Imaginary mission\n", encoding="utf-8") - (state / "ACTIVE").write_text(json.dumps({"id": "orchard-mission", "session": "orchard-owner", - "runtime": "hermes", "openedAt": "2026-01-01"}), encoding="utf-8") - monkeypatch.setenv("HERMES_HOME", str(tmp_path / "gateway")) - for name in ("HAN_ADAPTERS_DIR", "HAN_REPO", "CLAUDE_PROJECT_DIR", workers.WORKER_ENV): - monkeypatch.delenv(name, raising=False) - monkeypatch.setattr(adapters, "in_place_adapters_dir", lambda: str(tmp_path / "absent")) - return SimpleNamespace(root=root, state=state, adapter=selected, active=mission.read_active(str(state))) - - -@pytest.fixture -def bridge(tmp_path): - script = tmp_path / "model bridge.py" - script.write_text('''import json, os, subprocess, sys, time -from pathlib import Path -mode = sys.argv[1] -def send(value): - print(json.dumps({"schema": 1, **value}), flush=True) -def receive(): - return json.loads(sys.stdin.readline()) -assert receive() == {"schema": 1, "action": "status"} -if mode == "bad-status": - print("not-json", flush=True) - sys.exit(0) -send({"type":"status", "transport":"chef-tools-v1", "roles":["chef:researcher", "chef:dev-small"]}) -if mode == "no-read": - time.sleep(10) -line = sys.stdin.readline() -if not line: - sys.exit(0) -request = json.loads(line) -assert request["action"] == "delegate" -assert os.getcwd() != request["workspace"] -if mode in ("sleep", "sleep-child"): - Path(sys.argv[2]).write_text(str(os.getpid())) - if mode == "sleep-child": - subprocess.Popen([sys.executable, "-c", "import os,signal,sys,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);open(sys.argv[1],'w').write(str(os.getpid()));time.sleep(30)", sys.argv[3]]) - while True: - time.sleep(1) -if mode == "stderr": - sys.stderr.write("x" * (2 * 1024 * 1024)) - sys.stderr.flush() -if mode == "large-line": - print("x" * (2 * 1024 * 1024), flush=True) -if mode == "invalid": - send({"type":"tool", "id":"one", "tool":"chef_worker_read", "arguments":{}, "session_id":"claimed-owner"}) -elif mode in ("tools", "readonly", "command", "denied", "duplicate"): - tool = "chef_worker_shell" if mode in ("command", "denied") else "chef_worker_write" if mode == "readonly" else "chef_worker_read" - args = {"command": "forbidden-action" if mode == "denied" else "printf attached > note.txt", "timeout":2} if tool == "chef_worker_shell" else {"operation":"read", "path":"notice.txt"} - send({"type":"tool", "id":"one", "tool":tool, "arguments":args}) - response = receive() - if mode == "duplicate": - send({"type":"tool", "id":"one", "tool":tool, "arguments":args}) - else: - send({"type":"result", "ok":response["ok"], "result":json.dumps(response), "error":response.get("error", "")}) -else: - send({"type":"result", "ok":True, "result":"observed orchard", "error":""}) -time.sleep(10) -''', encoding="utf-8") - - def configured(mode="tools", *args): - return {"backend": "garden-bridge", "attachments": {"garden-bridge": { - "command": [sys.executable, str(script), mode, *map(str, args)]}}} - - return configured - - -class FakeNative: - def __init__(self, project): - self.project = project - self.calls = [] - self.revoked = False - - def check_available(self): - pass - - def check_tool_execution(self): - pass - - @contextlib.contextmanager - def assignment(self, role, cwd, state, active, checker, slot, config=None): - self.role = role - try: - yield self - finally: - self.revoke() - - def check(self): - if self.revoked or mission.read_active(str(self.project.state)) != self.project.active: - raise ValueError("assignment ownership changed") - - def revoke(self): - self.revoked = True - - def call(self, tool, args, task): - self.check() - self.calls.append((tool, args, task)) - if self.role == "researcher" and tool != "chef_worker_read": - raise ValueError("this tool is unavailable to the assigned role") - return {"text": "observed orchard"} - - -def configure(project, settings): - adapter = json.loads(project.adapter.read_text(encoding="utf-8")) - adapter["workers"] = settings - project.adapter.write_text(json.dumps(adapter), encoding="utf-8") - - -def run(project, native, role="dev-small"): - return workers.delegate({"role": role, "prompt": "Inspect the imaginary orchard.", "timeout": 10}, - session_id="orchard-owner", cwd=str(project.root), native=native) - - -def test_default_hermes_never_probes_codex_and_passes_role_config(project, monkeypatch): - native = FakeNative(project) - configure(project, {"hermesRoles": {"dev-small": {"model": "imaginary-model"}}}) - seen = [] - native.run = lambda *args, **kwargs: (seen.append((args, kwargs)) or {"ok": True}) - monkeypatch.setattr(workers, "codex_executable", lambda: pytest.fail("unexpected Codex auth")) - assert run(project, native) == {"ok": True} - assert seen[0][0][0] == "dev-small" - assert seen[0][1] == {"config": {"model": "imaginary-model"}} - assert workers.status({}, native=native) == { - "backend": "hermes", "roles": ["chef:" + role for role in workers.ROLES], "available": True} - - -def test_named_attachment_executes_literal_argv_and_mediates_host_identity(project, bridge): - configure(project, bridge()) - native = FakeNative(project) - result = run(project, native) - assert result["ok"] and result["runtime"] == "garden-bridge" - tool, args, task = native.calls[0] - assert tool == "chef_worker_read" and args == {"operation": "read", "path": "notice.txt"} - assert task.startswith("chef-attachment-") and task != "one" - assert native.revoked - - -def test_attachment_status_intersects_advertised_roles_and_project_allow(project, bridge): - native = FakeNative(project) - adapter = {"workers": bridge(), "agents": {"allow": ["chef:dev-*"]}} - assert workers.status(adapter, native=native) == { - "backend": "garden-bridge", "roles": ["chef:dev-small"], "available": True} - adapter["agents"]["allow"] = ["chef:verifier"] - assert "no roles" in workers.status(adapter, native=native)["error"] - - -def test_attachment_status_needs_no_hermes_lifecycle_or_model_profile(bridge, monkeypatch): - from chef.runtimes.hermes import native, research - - host = native.NativeWorkers(None) - checks = [] - platform_check = host.check_tool_execution - - def check_tools(): - checks.append(True) - if os.name == "posix": - platform_check() - - monkeypatch.setattr(host, "check_tool_execution", check_tools) - monkeypatch.setattr(research, "profile_config", lambda: pytest.fail("attachment read Hermes model profile")) - result = workers.status({"workers": bridge()}, native=host) - assert result == {"backend": "garden-bridge", "roles": ["chef:researcher", "chef:dev-small"], "available": True} - assert checks == [True] - - -def test_claude_status_and_dispatch_forward_same_private_settings_path(project, tmp_path, monkeypatch): - from chef.runtimes.hermes import claude - - settings_path = str(tmp_path / "private-routing.json") - settings = {"backend": "claude", "claudeSettings": settings_path, - "claudeRoles": {"dev-small": {"model": "imaginary-model"}}} - configure(project, settings) - probed, delegated = [], [] - monkeypatch.setattr(claude, "executable", lambda **kwargs: (probed.append(kwargs) or "/imaginary/claude")) - monkeypatch.setattr(claude, "run", lambda *args, **kwargs: (delegated.append((args, kwargs)) or {"ok": True})) - adapter = json.loads(project.adapter.read_text(encoding="utf-8")) - assert workers.status(adapter, cwd=str(project.root))["available"] - assert run(project, FakeNative(project)) == {"ok": True} - assert probed == [{"cwd": str(project.root), "settings_path": settings_path}] - args, kwargs = delegated[0] - assert args[3] == str(project.root) - assert kwargs["settings_path"] == settings_path - assert kwargs["settings"] == settings["claudeRoles"] - - -@pytest.mark.parametrize("mode,error", [("bad-status", "not JSON"), ("invalid", "invalid worker attachment tool"), - ("duplicate", "invalid worker attachment tool"), - ("stderr", "stderr output limit"), ("large-line", "JSONL size limit")]) -def test_attachment_rejects_invalid_protocol_without_fallback(project, bridge, mode, error): - configure(project, bridge(mode)) - native = FakeNative(project) - with pytest.raises(ValueError, match=error): - run(project, native) - assert len(native.calls) <= (1 if mode == "duplicate" else 0) - assert native.revoked - - -def test_readonly_attachment_cannot_gain_write_capability(project, bridge): - configure(project, bridge("readonly")) - result = run(project, FakeNative(project), role="researcher") - assert result["ok"] is False and "unavailable to the assigned role" in result["error"] - - -def test_attachment_missing_advertised_role_does_not_start_tools(project, bridge): - configure(project, bridge()) - native = FakeNative(project) - with pytest.raises(ValueError, match="does not support"): - run(project, native, role="verifier") - assert not native.calls - - -@pytest.mark.parametrize("value", [None, "missing", [], {}, {"command": ["relative-agent"]}, - {"command": ["/imaginary/bridge"], "fallback": "codex"}]) -def test_attachment_configuration_is_explicit_and_cannot_enable_fallback(value): - with pytest.raises(ValueError): - workers.backend_for({"workers": {"backend": "garden-bridge", "attachments": {"garden-bridge": value}}}) - - -def test_shared_workspace_gate_rejects_overlapping_native_and_attachment_dispatch(project, bridge): - native = FakeNative(project) - observed = [] - - def first(*args, **kwargs): - configure(project, bridge()) - with pytest.raises(LockBusy): - run(project, native) - observed.append(True) - return {"ok": True} - - native.run = first - assert run(project, native)["ok"] and observed == [True] - - -def test_native_dispatch_does_not_accept_protected_state_mutation(project): - native = FakeNative(project) - - def mutate(*args, **kwargs): - (project.state / "orchard-mission/mission.md").write_text("changed", encoding="utf-8") - return {"ok": True} - - native.run = mutate - with pytest.raises(ValueError, match="protected mission state changed"): - run(project, native) - assert (project.state / "orchard-mission/mission.md").read_text(encoding="utf-8") == "changed" - - -def test_attachment_timeout_revokes_assignment_and_reaps_bridge(project, bridge, tmp_path): - marker = tmp_path / "bridge.pid" - native = FakeNative(project) - selected = attachment.Attachment(bridge("sleep", marker), "garden-bridge") - started = time.monotonic() - with pytest.raises(TimeoutError, match="timed out"): - selected.run(native, "dev-small", "Wait", 1, str(project.root), str(project.state), project.active, None, None) - assert time.monotonic() - started < 4 and native.revoked - assert marker.is_file() - assert not workers.process_alive(int(marker.read_text())) - - -def test_attachment_blocked_stdin_respects_deadline_and_revokes_assignment(project, bridge): - native = FakeNative(project) - selected = attachment.Attachment(bridge("no-read"), "garden-bridge") - started = time.monotonic() - with pytest.raises(TimeoutError, match="timed out writing"): - selected.run(native, "dev-small", "x" * 100000, 1, str(project.root), str(project.state), project.active, None, None) - assert time.monotonic() - started < 4 and native.revoked - - -@pytest.mark.skipif(os.name != "posix", reason="process-group cleanup requires macOS/Linux") -def test_attachment_timeout_kills_term_ignoring_descendant(project, bridge, tmp_path): - leader, child = tmp_path / "bridge.pid", tmp_path / "child.pid" - native = FakeNative(project) - selected = attachment.Attachment(bridge("sleep-child", leader, child), "garden-bridge") - with pytest.raises(TimeoutError): - selected.run(native, "dev-small", "Wait", 1, str(project.root), str(project.state), project.active, None, None) - assert native.revoked and leader.is_file() and child.is_file() - assert not workers.process_alive(int(leader.read_text())) - # POSIX may retain a killed grandchild as a zombie until its init reaps it. - import subprocess - - status = subprocess.run(["ps", "-o", "stat=", "-p", child.read_text()], capture_output=True, - text=True, timeout=5).stdout.strip() - assert not status or status.startswith("Z") - - -@pytest.mark.skipif(os.name != "posix", reason="native shell execution requires macOS/Linux") -def test_attachment_real_command_execution_and_guard_denial(project, bridge): - from chef.runtimes.hermes.native import NativeWorkers - - native = NativeWorkers(None) - configure(project, bridge("command")) - result = run(project, native) - assert result["ok"] - assert (project.root / "note.txt").read_text() == "attached" - configure(project, bridge("denied")) - result = run(project, native) - assert not result["ok"] and "fictional policy" in result["error"] diff --git a/tests/integration/hermes/test_claude_workers.py b/tests/integration/hermes/test_claude_workers.py deleted file mode 100644 index d7ddbd4..0000000 --- a/tests/integration/hermes/test_claude_workers.py +++ /dev/null @@ -1,413 +0,0 @@ -"""Claude workers using fictional projects and fake CLI I/O.""" - -import json -import os -import subprocess -import sys -import time -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from chef.guards import adapters, mission -from chef.runtimes import hooks -from chef.runtimes.hermes import claude, workers - - -def write_json(path, value): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(value), encoding="utf-8") - - -@pytest.fixture -def project(tmp_path, monkeypatch): - root = tmp_path / "fictional orchard" - root.mkdir() - write_json(root / ".hermes/orchestrator/adapter.json", { - "schema": 1, "project": "fictional-orchard", "paths": {"stateDir": "state"}, - "agents": {"allow": ["chef:*"]}, "workers": {"backend": "claude"}}) - write_json(root / "state/ACTIVE", {"id": "orchard-mission", "session": "orchard-owner", - "runtime": "hermes", "openedAt": "2026-01-01"}) - folder = root / "state/orchard-mission" - folder.mkdir() - (folder / "mission.md").write_text("# Fictional mission\n") - for name in ("HAN_ADAPTERS_DIR", "HAN_REPO", "CHEF_HERMES_WORKER", "GROK_SESSION_ID", "GROK_HOOK_EVENT"): - monkeypatch.delenv(name, raising=False) - monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home")) - monkeypatch.setattr(adapters, "in_place_adapters_dir", lambda: str(tmp_path / "missing")) - return SimpleNamespace(root=root, state=str(root / "state"), active=mission.read_active(str(root / "state"))) - - -@pytest.fixture -def cli(monkeypatch): - calls = [] - monkeypatch.setattr(claude, "checked_executable", lambda *a, **kw: "/fictional/claude") - - def hook(command, payload, env, cwd): - settings = json.loads(Path(command[command.index("--settings") + 1]).read_text(encoding="utf-8")) - spec = settings["hooks"][payload["hook_event_name"]][0]["hooks"][0] - result = subprocess.run([spec["command"], *spec["args"]], cwd=cwd, env=env, - input=json.dumps(payload), capture_output=True, text=True, encoding="utf-8", timeout=15) - assert result.returncode == 0, result.stderr - return json.loads(result.stdout or "{}") - - def execute(command, prompt, env, timeout, cwd): - data = json.loads(Path(env[claude.WORKER_ENV]).read_text(encoding="utf-8")) - snapshot = json.loads(Path(command[command.index("--settings") + 1]).read_text(encoding="utf-8")) - calls.append((command, prompt, env, timeout, cwd, data, snapshot)) - payload = {"session_id": "separate-cli-session", "cwd": cwd, "hook_event_name": "SessionStart"} - hook(command, payload, env, cwd) - if data["phase"] == "probe": - output = hook(command, {**payload, "hook_event_name": "PreToolUse", "tool_name": "Bash", - "tool_input": {"command": claude.PROBE}}, env, cwd) - assert output["hookSpecificOutput"]["permissionDecision"] == "deny" - return subprocess.CompletedProcess(command, 0, json.dumps({"type": "result", "subtype": "success", - "is_error": False, "result": "observed result"}), "") - - monkeypatch.setattr(claude, "run_process", execute) - return SimpleNamespace(calls=calls, execute=execute, hook=hook) - - -def run(project, role="dev-small", **kwargs): - return claude.run(role, 'Inspect "quoted" fictional files.\nNext line.', 240, str(project.root), - project.state, project.active, None, **kwargs) - - -def test_per_call_fixed_hooks_probe_and_context_cleanup(project, cli, monkeypatch): - for name in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_CODE_USE_BEDROCK", - "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CONFIG_DIR"): - monkeypatch.setenv(name, "fictional-selector") - assert run(project) == {"ok": True, "runtime": "claude", "role": "chef:dev-small", "exit_code": 0, - "result": "observed result", "error": ""} - assert len(cli.calls) == 2 - probe, work = cli.calls - assert probe[3] == 120 and work[3] == 240 - assert probe[5]["phase"] == "probe" and work[5]["phase"] == "work" - assert work[5]["session"] == "orchard-owner" - assert work[5]["backend"] == "claude" - assert work[1] not in work[0] and work[4] == str(project.root) - for command, _, env, _, _, _, settings in cli.calls: - assert env["PWD"] == str(project.root) - assert env["ANTHROPIC_API_KEY"] == "fictional-selector" - assert env["CLAUDE_CONFIG_DIR"] == "fictional-selector" - assert command[command.index("--setting-sources") + 1] == "" - assert command[command.index("--mcp-config") + 1] == '{"mcpServers":{}}' - assert command[command.index("--disallowedTools") + 1] == "Agent,Task" - assert "--no-session-persistence" in command and "--strict-mcp-config" in command - assert settings["disableAllHooks"] is False - assert settings["hooks"]["PreToolUse"][0]["hooks"][0]["onFailure"] == "block" - assert not Path(work[2][claude.WORKER_ENV]).exists() - - -@pytest.mark.parametrize("role", claude.READ_ONLY) -def test_readonly_roles_have_no_shell_and_use_own_role_defaults(project, cli, role): - assert run(project, role)["ok"] - command = cli.calls[-1][0] - assert "Bash" not in command[command.index("--tools") + 1] - source = (claude.PLUGIN_ROOT / "agents" / (role + ".md")).read_text(encoding="utf-8") - config = claude.role_config(role) - assert config["model"] in source and config["effort"] in source - assert source.split("---", 2)[2].strip() in config["instructions"] - - -@pytest.mark.parametrize("value", [{"loggedIn": False}, {}, [], None]) -def test_auth_rejects_logged_out_or_malformed_status(monkeypatch, value): - monkeypatch.setattr(claude, "selected_settings", lambda *args: []) - monkeypatch.setattr(claude.shutil, "which", lambda _: "/fictional/claude") - monkeypatch.setattr(claude.subprocess, "run", lambda command, **kw: subprocess.CompletedProcess( - command, 0, "2.1.331 (Claude Code)" if "--version" in command else json.dumps(value), "")) - with pytest.raises(ValueError, match="authentication"): - claude.executable() - - -@pytest.mark.parametrize("method,provider", [("claude.ai", "firstParty"), ("api_key", "firstParty"), ("provider", "bedrock")]) -def test_auth_uses_json_status_and_preserves_operator_provider(monkeypatch, method, provider): - monkeypatch.setattr(claude, "selected_settings", lambda *args: []) - monkeypatch.setattr(claude.shutil, "which", lambda _: "/fictional/claude") - monkeypatch.setenv("ANTHROPIC_API_KEY", "fictional-unusable-key") - def auth(command, **kwargs): - if "--version" in command: - return subprocess.CompletedProcess(command, 0, "2.1.331 (Claude Code)", "") - assert command[-3:] == ["auth", "status", "--json"] - assert kwargs["env"]["ANTHROPIC_API_KEY"] == "fictional-unusable-key" - return subprocess.CompletedProcess(command, 0, json.dumps({"loggedIn": True, "authMethod": method, "apiProvider": provider}), "") - monkeypatch.setattr(claude.subprocess, "run", auth) - assert claude.executable() == "/fictional/claude" - - -@pytest.mark.parametrize("version", ["2.1.294 (Claude Code)", "2.0.500", "unknown", ""]) -def test_older_or_unknown_cli_version_is_rejected_before_auth(monkeypatch, version): - monkeypatch.setattr(claude.shutil, "which", lambda _: "/fictional/claude") - def check(command, **kwargs): - assert command == ["/fictional/claude", "--version"] - return subprocess.CompletedProcess(command, 0, version, "") - monkeypatch.setattr(claude.subprocess, "run", check) - with pytest.raises(ValueError, match="2.1.295"): - claude.executable() - - -def test_settings_endpoint_selection_requires_explicit_snapshot_before_auth(tmp_path, monkeypatch): - profile = tmp_path / "profile" - write_json(profile / "settings.json", {"env": {"ANTHROPIC_BASE_URL": "https://gateway.example.invalid"}}) - monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(profile)) - monkeypatch.setattr(claude.shutil, "which", lambda _: "/fictional/claude") - def version_only(command, **kwargs): - assert command[-1] == "--version", "ambiguous settings routing reached authentication" - return subprocess.CompletedProcess(command, 0, "2.1.331 (Claude Code)", "") - monkeypatch.setattr(claude.subprocess, "run", version_only) - with pytest.raises(ValueError, match="provide workers.claudeSettings") as failure: - claude.executable(cwd=str(tmp_path)) - assert str(profile / "settings.json") in str(failure.value) - assert "gateway.example.invalid" not in str(failure.value) - - -def test_relative_profile_is_resolved_from_assigned_cwd(tmp_path): - paths = claude.selected_settings(str(tmp_path), {"CLAUDE_CONFIG_DIR": "relative-profile"}) - assert paths[0] == tmp_path / "relative-profile/settings.json" - - -def test_auth_route_identity_mismatch_fails_without_explicit_snapshot(tmp_path, monkeypatch): - monkeypatch.setattr(claude, "selected_settings", lambda *args: []) - monkeypatch.setattr(claude.shutil, "which", lambda _: "/fictional/claude") - def auth(command, **kwargs): - if command[-1] == "--version": - return subprocess.CompletedProcess(command, 0, "2.1.331", "") - selected = "--settings" not in command - value = {"loggedIn": True, "authMethod": "api_key" if selected else "claude.ai", "apiProvider": "firstParty"} - return subprocess.CompletedProcess(command, 0, json.dumps(value), "") - monkeypatch.setattr(claude.subprocess, "run", auth) - with pytest.raises(ValueError, match="authentication differs"): - claude.executable(cwd=str(tmp_path)) - - -def test_explicit_auth_snapshot_uses_private_file_same_cwd_and_no_argv_secrets(tmp_path, monkeypatch): - source = tmp_path / "auth.json" - secret = "fictional-private-credential" - write_json(source, {"env": {"ANTHROPIC_AUTH_TOKEN": secret}, "apiKeyHelper": "fictional-helper"}) - monkeypatch.setattr(claude.shutil, "which", lambda _: "/fictional/claude") - observed = [] - def auth(command, **kwargs): - assert kwargs["cwd"] == str(tmp_path) - assert not any(secret in item for item in command) - if command[-1] == "--version": - return subprocess.CompletedProcess(command, 0, "2.1.331", "") - if "--settings" in command: - path = Path(command[command.index("--settings") + 1]) - settings = json.loads(path.read_text(encoding="utf-8")) - assert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == secret - assert settings["apiKeyHelper"] == "fictional-helper" - assert settings["disableAllHooks"] is False - if os.name != "nt": - assert path.stat().st_mode & 0o077 == 0 - observed.append(path) - return subprocess.CompletedProcess(command, 0, '{"loggedIn":true,"authMethod":"api_key","apiProvider":"firstParty"}', "") - monkeypatch.setattr(claude.subprocess, "run", auth) - assert claude.executable(cwd=str(tmp_path), settings_path=str(source)) == "/fictional/claude" - assert len(observed) == 1 and not observed[0].exists() - - -def test_worker_auth_snapshot_is_pinned_for_probe_work_and_removed(project, cli, tmp_path): - source = tmp_path / "auth.json" - secret = "fictional-private-credential" - write_json(source, {"env": {"ANTHROPIC_AUTH_TOKEN": secret}, "modelOverrides": {"fictional-model": "provider-model"}}) - assert run(project, settings_path=str(source))["ok"] - for argv, _, _, _, _, _, settings in cli.calls: - assert not any(secret in item for item in argv) - assert settings["env"]["ANTHROPIC_AUTH_TOKEN"] == secret - assert settings["modelOverrides"] == {"fictional-model": "provider-model"} - assert not Path(argv[argv.index("--settings") + 1]).exists() - - -@pytest.mark.parametrize("value", [{"hooks": {}}, {"permissions": {}}, {"env": {"CHEF_HERMES_WORKER": "other"}}, - {"modelOverrides": {"model": {"nested": "other"}}}, {"apiKeyHelper": []}]) -def test_explicit_auth_subset_rejects_capability_or_invalid_shapes(tmp_path, value): - source = tmp_path / "auth.json" - write_json(source, value) - with pytest.raises(ValueError): - claude.auth_settings(str(source)) - - -def test_explicit_auth_native_shapes_allow_org_lists(tmp_path): - source = tmp_path / "auth.json" - for value in ([], ["fictional-org"]): - write_json(source, {"forceLoginOrgUUID": value, "forceLoginMethod": "gateway"}) - assert claude.auth_settings(str(source))["forceLoginOrgUUID"] == value - - -@pytest.mark.parametrize("missing", ["ready", "guard_ready"]) -def test_missing_ack_prevents_work_and_removes_context(project, cli, monkeypatch, missing): - def execute(*args): - result = cli.execute(*args) - Path(cli.calls[-1][5][missing]).unlink() - return result - monkeypatch.setattr(claude, "run_process", execute) - with pytest.raises(ValueError, match="preflight"): - run(project) - assert len(cli.calls) == 1 and not Path(cli.calls[0][2][claude.WORKER_ENV]).exists() - - -def test_mission_change_during_probe_prevents_work(project, cli, monkeypatch): - def execute(*args): - result = cli.execute(*args) - write_json(project.root / "state/ACTIVE", {"id": "other-mission", "session": "other-owner", "runtime": "hermes"}) - return result - monkeypatch.setattr(claude, "run_process", execute) - with pytest.raises(ValueError, match="mission changed"): - run(project) - assert len(cli.calls) == 1 - - -@pytest.mark.parametrize("role,tool,inputs", [ - ("researcher", "Bash", {"command": "echo forbidden"}), - ("code-reviewer", "Write", {"file_path": "notes.txt"}), - ("dev-small", "Agent", {"prompt": "nested"}), - ("dev-small", "Task", {"prompt": "nested"}), - ("dev-small", "Bash", {"command": "echo bounded", "run_in_background": True}), - ("dev-small", "Write", {"file_path": "../outside.txt"}), -]) -def test_hook_rejects_tools_outside_fixed_role_capabilities(project, cli, monkeypatch, role, tool, inputs): - def execute(command, prompt, env, timeout, cwd): - result = cli.execute(command, prompt, env, timeout, cwd) - if cli.calls[-1][5]["phase"] == "work": - output = cli.hook(command, {"hook_event_name": "PreToolUse", "cwd": cwd, - "tool_name": tool, "tool_input": inputs}, env, cwd) - assert output["hookSpecificOutput"]["permissionDecision"] == "deny" - return result - monkeypatch.setattr(claude, "run_process", execute) - assert run(project, role)["ok"] - - -@pytest.mark.parametrize("command", [ - "printf changed > ../outside.txt", - "python -c \"from pathlib import Path; Path('../outside.txt').write_text('changed')\"", - "cp notes.txt ../outside.txt", - "mv ../outside.txt renamed.txt", - "printf changed > .claude/settings.json", - "printf changed > state/ACTIVE", -]) -def test_canonical_hook_denies_supported_shell_writes(project, cli, monkeypatch, command): - def execute(argv, prompt, env, timeout, cwd): - result = cli.execute(argv, prompt, env, timeout, cwd) - if cli.calls[-1][5]["phase"] == "work": - output = cli.hook(argv, {"hook_event_name": "PreToolUse", "cwd": cwd, - "tool_name": "Bash", "tool_input": {"command": command}}, env, cwd) - assert output["hookSpecificOutput"]["permissionDecision"] == "deny" - return result - monkeypatch.setattr(claude, "run_process", execute) - assert run(project)["ok"] - assert not (project.root.parent / "outside.txt").exists() - - -@pytest.mark.parametrize("command", ["cat ../outside.txt", "rg needle notes.txt", "printf changed > result.txt"]) -def test_canonical_hook_keeps_reads_and_in_workspace_outputs(project, cli, monkeypatch, command): - def execute(argv, prompt, env, timeout, cwd): - result = cli.execute(argv, prompt, env, timeout, cwd) - if cli.calls[-1][5]["phase"] == "work": - output = cli.hook(argv, {"hook_event_name": "PreToolUse", "cwd": cwd, - "tool_name": "Bash", "tool_input": {"command": command}}, env, cwd) - assert output.get("hookSpecificOutput", {}).get("permissionDecision") != "deny" - return result - monkeypatch.setattr(claude, "run_process", execute) - assert run(project)["ok"] - - -def test_canonical_hook_rejects_write_through_workspace_symlink(project, cli, monkeypatch): - destination = project.root / "actual" - destination.mkdir() - try: - (project.root / "alias").symlink_to(destination, target_is_directory=True) - except OSError: - pytest.skip("host cannot create a symlink") - def execute(argv, prompt, env, timeout, cwd): - result = cli.execute(argv, prompt, env, timeout, cwd) - if cli.calls[-1][5]["phase"] == "work": - output = cli.hook(argv, {"hook_event_name": "PreToolUse", "cwd": cwd, - "tool_name": "Bash", "tool_input": {"command": "printf changed > alias/output.txt"}}, env, cwd) - assert output["hookSpecificOutput"]["permissionDecision"] == "deny" - return result - monkeypatch.setattr(claude, "run_process", execute) - assert run(project)["ok"] - - -def test_cross_runtime_context_reuse_is_denied(project, cli, monkeypatch): - def execute(command, prompt, env, timeout, cwd): - result = cli.execute(command, prompt, env, timeout, cwd) - with monkeypatch.context() as context: - context.setenv(claude.WORKER_ENV, env[claude.WORKER_ENV]) - with pytest.raises(ValueError, match="runtime does not match"): - hooks.normalize_payload({"cwd": cwd, "hook_event_name": "PreToolUse"}, "codex") - return result - monkeypatch.setattr(claude, "run_process", execute) - assert run(project)["ok"] - - -def test_hook_rejects_changed_implementation_digest(project, cli, monkeypatch): - def execute(command, prompt, env, timeout, cwd): - result = cli.execute(command, prompt, env, timeout, cwd) - if cli.calls[-1][5]["phase"] == "work": - path = Path(env[claude.WORKER_ENV]) - data = json.loads(path.read_text(encoding="utf-8")) - data["digest"] = "outdated" - write_json(path, data) - output = cli.hook(command, {"hook_event_name": "PreToolUse", "cwd": cwd, - "tool_name": "Read", "tool_input": {"file_path": "notes.txt"}}, env, cwd) - assert output["hookSpecificOutput"]["permissionDecision"] == "deny" - return result - monkeypatch.setattr(claude, "run_process", execute) - assert run(project)["ok"] - - -def test_project_guard_receives_owner_and_can_deny(project, cli, tmp_path): - checker = tmp_path / "guard.py" - checker.write_text("import json,sys\np=json.load(sys.stdin)\nassert p['session_id']=='orchard-owner'\nassert p['agent_id']=='chef-claude-worker'\nprint(json.dumps({'decision':'block','reason':'fictional policy'}))\n") - # A denied probe still succeeds; the fixed project guard is present in the - # immutable per-call context and is also applied to ordinary work tools. - original = cli.execute - def execute(command, prompt, env, timeout, cwd): - result = original(command, prompt, env, timeout, cwd) - if cli.calls[-1][5]["phase"] == "work": - output = cli.hook(command, {"hook_event_name": "PreToolUse", "cwd": cwd, - "tool_name": "Read", "tool_input": {"file_path": "notes.txt"}}, env, cwd) - assert "fictional policy" in output["hookSpecificOutput"]["permissionDecisionReason"] - return result - from unittest.mock import patch - with patch.object(claude, "run_process", execute): - assert claude.run("dev-small", "Inspect", 240, str(project.root), project.state, project.active, - [sys.executable, str(checker)])["ok"] - - -@pytest.mark.parametrize("event", [{"type": "result", "subtype": "error_during_execution", "is_error": True}, - {"type": "assistant", "message": "partial"}, - {"type": "result", "subtype": "success", "is_error": True}]) -def test_stream_error_or_missing_terminal_is_not_success(event): - result = claude.parse_result(subprocess.CompletedProcess([], 0, json.dumps(event), ""), "researcher") - assert not result["ok"] and result["error"] - - -def test_role_override_cannot_inject_cli_or_replace_instructions(): - assert claude.role_config("researcher", {"researcher": {"model": "fictional-model", "effort": "high"}})["model"] == "fictional-model" - for override in ({"instructions": "other"}, {"effort": "invalid"}, {"model": "a\nb"}): - with pytest.raises(ValueError): - claude.role_config("researcher", {"researcher": override}) - - -@pytest.mark.skipif(os.name == "nt", reason="Hermes CLI process groups target POSIX gateways") -def test_timeout_kills_descendant_that_ignores_term(tmp_path): - pidfile = tmp_path / "child.pid" - script = "import subprocess,sys,time\np=subprocess.Popen([sys.executable,'-c','import signal,time; signal.signal(signal.SIGTERM,signal.SIG_IGN); time.sleep(60)']);open(sys.argv[1],'w').write(str(p.pid));time.sleep(60)" - with pytest.raises(subprocess.TimeoutExpired): - claude.run_process([sys.executable, "-c", script, str(pidfile)], "", dict(os.environ), 0.5, str(tmp_path)) - pid = int(pidfile.read_text()) - # A killed child may briefly remain a zombie until the host reaps it. - for _ in range(20): - try: - os.kill(pid, 0) - except ProcessLookupError: - break - status = Path(f"/proc/{pid}/stat") - if status.exists() and status.read_text().split()[2] == "Z": - break - time.sleep(0.05) - else: - pytest.fail("worker descendant survived timeout") diff --git a/tests/integration/hermes/test_current_session.py b/tests/integration/hermes/test_current_session.py deleted file mode 100644 index 0385273..0000000 --- a/tests/integration/hermes/test_current_session.py +++ /dev/null @@ -1,232 +0,0 @@ -"""Current-session entry does not depend on a desktop or claim another mission.""" - -import json -import os -import sys -from contextvars import ContextVar -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from chef.guards import mission as guard -from chef.infrastructure.errors import UsageError -from chef.runtimes.hermes import plugin -from chef.slots import commands as slots - - -@pytest.fixture -def world(tmp_path, monkeypatch): - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "empty")) - project = tmp_path / "orchard" - project.mkdir() - folder = project / ".hermes/orchestrator" - folder.mkdir(parents=True) - adapter = {"schema": 1, "paths": {"stateDir": "state"}, "slots": { - "enabled": True, "vcs": "none", "root": str(tmp_path / "slots"), - "client": "test-{name}", "names": ["one"], "prepare": []}} - (folder / "adapter.json").write_text(json.dumps(adapter)) - assert slots.main(["--project", str(project), "--runtime", "hermes", "create", "one"]) == 0 - slot_adapter = tmp_path / "slots/one/.hermes/orchestrator" - slot_adapter.mkdir(parents=True) - (slot_adapter / "adapter.json").write_text(json.dumps(adapter)) - return project, tmp_path / "slots/one" - - -def test_entry_uses_slot_without_spawning_or_claiming_active(world, monkeypatch): - project, slot = world - monkeypatch.setattr(slots, "launch_mission", lambda *a: pytest.fail("must not open a terminal")) - context = slots.current_session_context(str(project), "one", "hermes-session") - assert Path(context["cwd"]) == slot.resolve() - assert context["mode"] == "new" and not context["mission"] - assert not (slot / "state/ACTIVE").exists() - - -def test_resume_preserves_owner_and_rejects_another_session(world): - project, slot = world - guard.write_active(str(slot / "state"), guard.Active("m-one", "original", "now", runtime="hermes")) - with pytest.raises(UsageError): - slots.current_session_context(str(project), "one", "other", resume=True) - with pytest.raises(UsageError): - slots.current_session_context(str(project), "one", "original") - context = slots.current_session_context(str(project), "one", "original", resume=True) - assert context["mission"] == "m-one" and context["mode"] == "resume" - assert guard.read_active(str(slot / "state")).session == "original" - - -def test_failure_and_unknown_slot_cannot_enter(world): - project, slot = world - with pytest.raises(UsageError): - slots.current_session_context(str(project), "missing", "s") - located = slots.locate(str(project), "hermes") - config = slots.Config(located, slots.read_adapter(located.adapter_path, "hermes"), "hermes") - slots.Rows(config.rows_path).upsert("one", state="failed:setup") - with pytest.raises(UsageError): - slots.current_session_context(str(project), "one", "s") - - -def test_hermes_run_returns_actionable_error_without_terminal(world): - project, _ = world - assert slots.main(["--project", str(project), "--runtime", "hermes", "run", "one", "task"]) == slots.USAGE - - - -@pytest.fixture -def registry_world(tmp_path, monkeypatch): - """Chef-studio layout: in-tree manager adapter, registry-only slot adapter.""" - hermes_home = tmp_path / "hermes-home" - monkeypatch.setenv("HERMES_HOME", str(hermes_home)) - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - project = tmp_path / "orchard" - project.mkdir() - folder = project / ".hermes/orchestrator" - folder.mkdir(parents=True) - adapter = {"schema": 1, "paths": {"stateDir": "state"}, "slots": { - "enabled": True, "vcs": "none", "root": str(tmp_path / "slots"), - "client": "test-{name}", "names": ["one"], "prepare": []}} - (folder / "adapter.json").write_text(json.dumps(adapter)) - assert slots.main(["--project", str(project), "--runtime", "hermes", "create", "one"]) == 0 - slot = tmp_path / "slots/one" - assert slot.is_dir() - assert not (slot / ".hermes/orchestrator/adapter.json").exists() - return project, slot, hermes_home - - -def test_registry_only_slot_enters_when_registered_under_hermes_home(registry_world): - project, slot, hermes_home = registry_world - registry = hermes_home / "chef/adapters" - registry.mkdir(parents=True) - (registry / "one/adapter.json").parent.mkdir(parents=True, exist_ok=True) - (registry / "one/adapter.json").write_text(json.dumps( - {"schema": 1, "paths": {"stateDir": "state"}} - )) - (registry / "projects.json").write_text(json.dumps( - [{"adapter": "one", "roots": [str(slot)]}] - )) - context = slots.current_session_context(str(project), "one", "hermes-session") - assert Path(context["cwd"]) == slot.resolve() - assert context["mode"] == "new" and not context["mission"] - - -def test_native_slot_and_mission_resolve_registry_in_request_profile(registry_world, monkeypatch): - project, slot, gateway_home = registry_world - profile_home = gateway_home / "profiles" / "orchard-bot" - registry = profile_home / "chef" / "adapters" - adapter_path = registry / "one" / "adapter.json" - adapter_path.parent.mkdir(parents=True) - adapter_path.write_text(json.dumps({ - "schema": 1, - "paths": {"stateDir": "state"}, - "guard": {"deny": [{"pattern": "garden-probe", "reason": "fictional restriction"}]}, - })) - (registry / "projects.json").write_text(json.dumps([{"adapter": "one", "roots": [str(slot)]}])) - home = ContextVar("hermes_home", default=gateway_home) - monkeypatch.setitem(sys.modules, "hermes_constants", SimpleNamespace(get_hermes_home=home.get)) - monkeypatch.setattr(plugin, "native_cwd", lambda _: str(project)) - monkeypatch.setattr(plugin, "bind_native_cwd", lambda *_: None) - bridge = plugin.Bridge() - args = {"project": str(project), "name": "one"} - - token = home.set(profile_home) - try: - result = json.loads(bridge.slot({**args, "dry_run": True}, "owner", "task")) - assert result.get("cwd") == str(slot.resolve()), result - assert result["dry_run"] and bridge.cwd("owner", "task") == str(project) - assert not (slot / "state" / "ACTIVE").exists() - result = json.loads(bridge.slot(args, "owner", "task")) - assert result.get("cwd") == str(slot.resolve()), result - assert json.loads(bridge.mission({"action": "open", "mission": "orchard-mission"}, "owner", "task"))["ok"] - assert guard.read_active(str(slot / "state")).session == "owner" - directive = bridge.before_tool("terminal", {"command": "garden-probe"}, "owner", "task") - assert directive and "fictional restriction" in directive["message"] - finally: - home.reset(token) - - assert os.environ["HERMES_HOME"] == str(gateway_home) - for other_home in (gateway_home, gateway_home / "profiles" / "meadow-bot"): - token = home.set(other_home) - try: - # A fresh session with no ACTIVE lookup must still report its own registry. - args = {"project": str(slot), "name": "one", "dry_run": True} - result = json.loads(bridge.slot(args, "other-owner", "other-task")) - assert str(other_home / "chef" / "adapters") in result["error"] - finally: - home.reset(token) - - -def test_missing_slot_registry_error_names_slot_and_tried_registry(registry_world): - project, slot, hermes_home = registry_world - with pytest.raises(UsageError) as raised: - slots.current_session_context(str(project), "one", "hermes-session") - text = str(raised.value) - assert "Hermes 슬롯 어댑터를 찾지 못함" in text - assert str(slot) in text - assert "hermes-home" in text.replace("\\", "/") - assert "chef/adapters" in text.replace("\\", "/") - - - -def test_chef_slot_follows_binding_when_gateway_env_differs(tmp_path, monkeypatch): - """Start writes the registry under HAN_ADAPTERS_DIR; chef_slot has only HERMES_HOME.""" - from chef.guards.slot_binding import read_slot_binding - - studio = tmp_path / "studio-registry" - studio.mkdir() - (studio / "one/adapter.json").parent.mkdir(parents=True) - (studio / "one/adapter.json").write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}})) - (studio / "projects.json").write_text(json.dumps([{"adapter": "one", "roots": [str(tmp_path / "slots/one")]}])) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(studio)) - monkeypatch.delenv("HERMES_HOME", raising=False) - project = tmp_path / "orchard" - project.mkdir() - folder = project / ".hermes/orchestrator" - folder.mkdir(parents=True) - adapter = {"schema": 1, "paths": {"stateDir": "state"}, "slots": { - "enabled": True, "vcs": "none", "root": str(tmp_path / "slots"), - "client": "test-{name}", "names": ["one"], "prepare": []}} - (folder / "adapter.json").write_text(json.dumps(adapter)) - assert slots.main(["--project", str(project), "--runtime", "hermes", "create", "one"]) == 0 - slot = tmp_path / "slots/one" - binding = read_slot_binding(str(slot)) - assert Path(binding["registry"]) == studio - monkeypatch.delenv("HAN_ADAPTERS_DIR") - monkeypatch.setenv("HERMES_HOME", str(tmp_path / "gateway-home")) - context = slots.current_session_context(str(project), "one", "hermes-session") - assert Path(context["cwd"]) == slot.resolve() - assert context["mode"] == "new" - - -def test_chef_slot_matches_missing_path_spelling_via_recorded_identity(tmp_path, monkeypatch): - """Registry roots may use a /Users spelling that does not exist; the live slot does.""" - hermes_home = tmp_path / "hermes-home" - monkeypatch.setenv("HERMES_HOME", str(hermes_home)) - monkeypatch.delenv("HAN_ADAPTERS_DIR", raising=False) - project = tmp_path / "orchard" - project.mkdir() - folder = project / ".hermes/orchestrator" - folder.mkdir(parents=True) - slots_root = tmp_path / "slots" - adapter = {"schema": 1, "paths": {"stateDir": "state"}, "slots": { - "enabled": True, "vcs": "none", "root": str(slots_root), - "client": "test-{name}", "names": ["one"], "prepare": []}} - (folder / "adapter.json").write_text(json.dumps(adapter)) - missing = tmp_path / "Users" / "sample-user" / "workspaces" / "orchard-slots" / "one" - registry = hermes_home / "chef/adapters" - registry.mkdir(parents=True) - (registry / "one/adapter.json").parent.mkdir(parents=True, exist_ok=True) - (registry / "one/adapter.json").write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}})) - (registry / "projects.json").write_text(json.dumps([{"adapter": "one", "roots": [str(missing)]}])) - assert slots.main(["--project", str(project), "--runtime", "hermes", "create", "one"]) == 0 - slot = slots_root / "one" - (slot / ".p4config").write_text("P4CLIENT=test-one\n", encoding="utf-8") - # Recreate binding after .p4config exists so the p4 client id is stored. - from chef.slots.configuration import Config - from chef.infrastructure.configuration import locate, read_adapter - from chef.guards.slot_binding import record_slot_registry, read_slot_binding - located = locate(str(project), "hermes") - record_slot_registry(Config(located, read_adapter(located.adapter_path, "hermes"), "hermes"), "one") - binding = read_slot_binding(str(slot)) - assert binding.get("adapter") == "one" - assert any(item["kind"] == "p4Client" and item["value"] == "test-one" for item in binding["identities"]) - context = slots.current_session_context(str(project), "one", "hermes-session") - assert Path(context["cwd"]) == slot.resolve() diff --git a/tests/integration/hermes/test_external_slots.py b/tests/integration/hermes/test_external_slots.py deleted file mode 100644 index f45183b..0000000 --- a/tests/integration/hermes/test_external_slots.py +++ /dev/null @@ -1,445 +0,0 @@ -"""Native external-slot ownership without a real gateway or workspace service.""" - -import json -from pathlib import Path -import shlex -import sys -from contextvars import ContextVar -from threading import Event, Thread, current_thread -from types import SimpleNamespace - -import pytest - -from chef.guards import mission -from chef.infrastructure.errors import UsageError -from chef.infrastructure.locking import LockBusy -from chef.runtimes.hermes import external_slots, plugin, workers - - -@pytest.fixture -def world(tmp_path, monkeypatch): - registry = tmp_path / "adapters" - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home")) - manager = tmp_path / "orchard" - workspace = tmp_path / "orchard.one" - manager.mkdir() - workspace.mkdir() - adapter_path = registry / "orchard" / "adapter.json" - adapter_path.parent.mkdir(parents=True) - adapter_path.write_text(json.dumps({ - "schema": 1, "paths": {"stateDir": "state"}, "agents": {"allow": ["chef:researcher"]}, - "runtimes": {"hermes": {"externalSlots": { - "root": str(tmp_path), "provider": [sys.executable], - "protectedCommands": ["reserve (?:lock|unlock)"], - "workspaces": {"one": {"path": str(workspace)}}}}}, - })) - (registry / "projects.json").write_text(json.dumps([{ - "adapter": "orchard", "roots": [str(manager), str(workspace)]}])) - monkeypatch.setattr(plugin, "native_cwd", lambda _: str(manager)) - monkeypatch.setattr(plugin, "bind_native_cwd", lambda *_: None) - monkeypatch.setattr(plugin, "originating_request", lambda _: "original-request") - calls = [] - - def provider(self, action, record=None, clean=False): - calls.append((action, (record or {}).get("key"))) - - monkeypatch.setattr(external_slots.Slot, "call", provider) - return manager, workspace, calls - - -def select(bridge, manager, *, name="one", session="owner", dry_run=False, resume=False): - return json.loads(bridge.slot({"project": str(manager), "name": name, "dry_run": dry_run, "resume": resume}, - session_id=session, task_id=session)) - - -def terminal(bridge, command, session="owner", **extra): - marker = mission.MARKER.fullmatch(command) - if marker and not extra: - args = {"action": marker[1], "mission": marker[2]} - denied = bridge.before_tool("chef_mission", args, session_id=session, task_id=session) - if denied: - return denied - result = json.loads(bridge.mission(args, session_id=session, task_id=session)) - return {"action": "block", "message": result["error"]} if "error" in result else None - return bridge.before_tool("terminal", {"command": command, **extra}, session_id=session, task_id=session) - - -def test_select_is_read_only_and_close_uses_original_request(world, monkeypatch): - manager, workspace, calls = world - bridge = plugin.Bridge() - assert Path(select(bridge, manager, dry_run=True)["cwd"]) == workspace - context = select(bridge, manager) - slot = external_slots.from_context(context) - assert not slot.journal.exists() and set(action for action, _ in calls) == {"status"} - assert terminal(bridge, "git status")["action"] == "block" - assert terminal(bridge, "echo han-mission open garden && git status")["action"] == "block" - assert terminal(bridge, "echo han-mission open garden") is None - assert mission.read_active(slot.state).id == "garden" - assert terminal(bridge, "git status") is None - assert "belong to the mission guard" in terminal(bridge, "reserve unlock")["message"] - assert terminal(bridge, "git status", workdir=str(manager))["action"] == "block" - assert "error" in select(plugin.Bridge(), manager, session="other", resume=True) - assert select(bridge, manager, resume=True)["mission"] == "garden" - monkeypatch.setattr(plugin, "originating_request", lambda _: "next-request") - assert terminal(bridge, "echo han-mission close garden") is None - assert calls[-1] == ("release", "original-request") - assert not slot.journal.exists() and not mission.read_active(slot.state).id - - -def test_close_restores_each_task_and_allows_only_declared_idle_reads(world, tmp_path, monkeypatch): - manager, workspace, calls = world - original = tmp_path / "original" - original.mkdir() - cwds = {"owner": str(manager), "second-task": str(original)} - monkeypatch.setattr(plugin, "native_cwd", lambda task: cwds.get(task, str(manager))) - monkeypatch.setattr(plugin, "bind_native_cwd", cwds.__setitem__) - status = [sys.executable, str(manager / "inspect.py"), "status"] - listing = [sys.executable, str(manager / "inspect.py"), "list"] - adapter_path = tmp_path / "adapters" / "orchard" / "adapter.json" - adapter = json.loads(adapter_path.read_text()) - adapter["runtimes"]["hermes"]["externalSlots"]["readOnlyCommands"] = [status, listing] - adapter_path.write_text(json.dumps(adapter)) - bridge = plugin.Bridge() - assert select(bridge, manager)["reservation"] == "UNLOCKED" - assert terminal(bridge, "echo han-mission open garden") is None - assert json.loads(bridge.slot({"project": str(manager), "name": "one", "resume": True}, - session_id="owner", task_id="second-task"))["reservation"] == "LOCKED" - assert cwds == {"owner": str(workspace), "second-task": str(workspace)} - assert terminal(bridge, "echo han-mission close garden") is None - assert cwds == {"owner": str(manager), "second-task": str(original)} - assert not bridge.bindings and bridge.request("terminal", {"command": "pwd"}, "owner", "owner") is None - assert terminal(bridge, shlex.join(status), workdir=str(workspace)) is None - assert terminal(bridge, shlex.join(listing), workdir=str(manager)) is None - monkeypatch.setenv("HOME", str(tmp_path)) - monkeypatch.setenv("USERPROFILE", str(tmp_path)) - for workdir in (None, ".", "~/orchard"): - assert terminal(bridge, shlex.join(listing), workdir=workdir)["action"] == "block" - assert terminal(bridge, shlex.join(listing), workdir=str(manager), background=True)["action"] == "block" - for suffix in ("; echo changed", " > note", " $(echo changed)", "\n echo changed"): - assert terminal(bridge, shlex.join(status) + suffix, workdir=str(workspace))["action"] == "block" - assert bridge.before_tool("write_file", {"path": str(workspace / "note"), "content": "x"}, "owner", "owner")["action"] == "block" - - # Another session can acquire the released slot and its guards still apply. - assert select(bridge, manager, session="other")["external"] - assert terminal(bridge, "echo han-mission open second", session="other") is None - denied = terminal(bridge, shlex.join(status), workdir=str(workspace)) - assert "another active mission" in denied["message"] - assert terminal(bridge, "echo han-mission close second", workdir=str(workspace))["action"] == "block" - assert mission.read_active(str(workspace / "state")).session == "other" - assert [action for action, _ in calls].count("release") == 1 - - -def test_detached_reads_cannot_override_guard_rules_or_an_unresolved_journal(world, tmp_path): - manager, workspace, _ = world - argv = [sys.executable, str(manager / "inspect.py"), "status"] - command = shlex.join(argv) - adapter_path = tmp_path / "adapters" / "orchard" / "adapter.json" - adapter = json.loads(adapter_path.read_text()) - settings = adapter["runtimes"]["hermes"]["externalSlots"] - settings["readOnlyCommands"] = [argv] - settings["protectedCommands"] = ["status"] - adapter_path.write_text(json.dumps(adapter)) - bridge = plugin.Bridge() - assert select(bridge, manager)["external"] - assert terminal(bridge, "echo han-mission open seed") is None - assert terminal(bridge, "echo han-mission close seed") is None - assert "belong to the mission guard" in terminal(bridge, command, workdir=str(workspace))["message"] - settings["protectedCommands"] = [] - adapter["guard"] = {"deny": [{"pattern": "status", "reason": "fictional deny rule"}]} - adapter_path.write_text(json.dumps(adapter)) - assert "fictional deny rule" in terminal(bridge, command, workdir=str(workspace))["message"] - adapter["guard"] = {} - adapter_path.write_text(json.dumps(adapter)) - journal, _ = external_slots.reservation_paths(str(workspace.resolve())) - journal.parent.mkdir(parents=True, exist_ok=True) - journal.write_text("{}") - assert "unresolved reservation" in terminal(bridge, command, workdir=str(workspace))["message"] - - -def test_detached_slot_read_checks_provider_when_another_profile_has_a_different_state_dir(world, tmp_path, monkeypatch): - manager, workspace, _ = world - argv = [sys.executable, str(manager / "inspect.py"), "status"] - default_registry = tmp_path / "adapters" - originally = json.loads((default_registry / "orchard" / "adapter.json").read_text()) - originally["runtimes"]["hermes"]["externalSlots"]["readOnlyCommands"] = [argv] - homes = [tmp_path / "home" / "profiles" / name for name in ("fern", "spruce")] - for home in homes: - registry = home / "chef" / "adapters" - (registry / "orchard").mkdir(parents=True) - (registry / "projects.json").write_bytes((default_registry / "projects.json").read_bytes()) - (registry / "orchard" / "adapter.json").write_text(json.dumps({ - **originally, "paths": {"stateDir": home.name + "-state"}, - })) - monkeypatch.delenv("HAN_ADAPTERS_DIR") - current_home = ContextVar("hermes_home", default=homes[0]) - monkeypatch.setitem(sys.modules, "hermes_constants", SimpleNamespace(get_hermes_home=current_home.get)) - owner = [] - - def provider(slot, action, record=None, clean=False): - if action == "status" and owner: - raise UsageError("provider reports the workspace is occupied") - if action == "acquire": - assert not owner - owner.append(record["who"]) - if action in ("check", "release"): - assert owner == [record["who"]] - if action == "release": - owner.clear() - - monkeypatch.setattr(external_slots.Slot, "call", provider) - first, second = plugin.Bridge(), plugin.Bridge() - assert select(first, manager)["external"] - assert terminal(first, "echo han-mission open seed") is None - assert terminal(first, "echo han-mission close seed") is None - assert terminal(first, shlex.join(argv), workdir=str(workspace)) is None - token = current_home.set(homes[1]) - try: - assert select(second, manager, session="other")["external"] - assert terminal(second, "echo han-mission open tree", session="other") is None - finally: - current_home.reset(token) - assert not (workspace / "fern-state" / "ACTIVE").exists() - assert "provider reports the workspace is occupied" in terminal( - first, shlex.join(argv), workdir=str(workspace) - )["message"] - assert owner == ["other"] - - -def test_close_blocks_concurrent_resume_binding(world, monkeypatch): - manager, _, _ = world - bridge = plugin.Bridge() - assert select(bridge, manager)["external"] - assert terminal(bridge, "echo han-mission open garden") is None - checking, proceed = Event(), Event() - outcomes = [] - closing = Thread(target=lambda: outcomes.append(terminal(bridge, "echo han-mission close garden"))) - - def provider(slot, action, record=None, clean=False): - if action == "check" and current_thread() is closing: - checking.set() - assert proceed.wait(10) - - monkeypatch.setattr(external_slots.Slot, "call", provider) - closing.start() - try: - assert checking.wait(10) - for task in ("owner", "other-task"): - result = json.loads(bridge.slot({"project": str(manager), "name": "one", "resume": True}, - session_id="owner", task_id=task)) - assert "transition is in progress" in result.get("error", ""), result - finally: - proceed.set() - closing.join(10) - assert outcomes == [None] - assert not bridge.bindings - - -def test_selection_records_the_native_cwd_observed_under_the_binding_lock(world, monkeypatch): - manager, workspace, _ = world - # A previous close can restore the cwd between the backend probe and the bind. - observed = iter((str(workspace), str(manager))) - monkeypatch.setattr(plugin, "native_cwd", lambda _: next(observed, str(manager))) - changes = [] - monkeypatch.setattr(plugin, "bind_native_cwd", lambda task, cwd: changes.append(cwd)) - bridge = plugin.Bridge() - assert select(bridge, manager)["external"] - assert terminal(bridge, "echo han-mission open garden") is None - assert terminal(bridge, "echo han-mission close garden") is None - assert changes == [str(workspace), str(manager)] - - -def test_native_restore_error_after_release_still_detaches_other_tasks(world, monkeypatch): - manager, workspace, calls = world - cwds = {} - monkeypatch.setattr(plugin, "native_cwd", lambda task: cwds.get(task, str(manager))) - - def bind(task, cwd): - if task == "owner" and cwd == str(manager): - raise ValueError("fictional native failure") - cwds[task] = cwd - - monkeypatch.setattr(plugin, "bind_native_cwd", bind) - bridge = plugin.Bridge() - assert select(bridge, manager)["external"] - assert terminal(bridge, "echo han-mission open garden") is None - assert json.loads(bridge.slot({"project": str(manager), "name": "one", "resume": True}, - session_id="owner", task_id="second-task"))["external"] - assert "was released" in terminal(bridge, "echo han-mission close garden")["message"] - assert cwds["second-task"] == str(manager) and not bridge.bindings - assert not mission.read_active(str(workspace / "state")).id - assert calls[-1] == ("release", "original-request") - - -def test_existing_gateway_journal_keeps_its_lock_until_release(world, tmp_path, monkeypatch): - manager, workspace, calls = world - previous = plugin.Bridge() - context = select(previous, manager) - legacy = external_slots.from_context(context).journal - assert terminal(previous, "echo han-mission open garden") is None - - profile = tmp_path / "home" / "profiles" / "fern" - monkeypatch.setitem(sys.modules, "hermes_constants", SimpleNamespace(get_hermes_home=lambda: profile)) - bridge = plugin.Bridge() - assert "error" in select(bridge, manager, session="other", resume=True) - assert select(bridge, manager, resume=True)["mission"] == "garden" - assert external_slots.from_context(context).journal == legacy - with monkeypatch.context() as child: - child.delitem(sys.modules, "hermes_constants") - child.setenv("HERMES_HOME", str(profile)) - assert not workers.worker_denial({ - "cwd": str(workspace), "tool_name": "Bash", "tool_input": {"command": "git status"}, - "han_hermes_worker": {"external": context, "gatewayHome": str(tmp_path / "home"), - "state": context["state"], "cwd": str(workspace), - "session": "owner", "mission": "garden"}, - }) - assert terminal(bridge, "echo han-mission close garden") is None - assert calls[-1] == ("release", "original-request") - assert not legacy.exists() and not mission.read_active(str(workspace / "state")).id - assert external_slots.from_context(context).journal.parent == profile / "chef" / "external-slots" - - -def test_gateway_and_profile_journals_require_inspection(world, tmp_path, monkeypatch): - manager, workspace, calls = world - bridge = plugin.Bridge() - context = select(bridge, manager) - old_journal = external_slots.from_context(context).journal - assert terminal(bridge, "echo han-mission open garden") is None - profile = tmp_path / "home" / "profiles" / "fern" - new_journal = profile / "chef" / "external-slots" / old_journal.name - new_journal.parent.mkdir(parents=True) - snapshot = old_journal.read_bytes() - new_journal.write_bytes(snapshot) - monkeypatch.setitem(sys.modules, "hermes_constants", SimpleNamespace(get_hermes_home=lambda: profile)) - assert "both Hermes homes" in terminal(bridge, "echo han-mission close garden")["message"] - assert old_journal.read_bytes() == new_journal.read_bytes() == snapshot - assert mission.read_active(str(workspace / "state")).id == "garden" - assert all(action != "release" for action, _ in calls) - - -@pytest.mark.parametrize("state_dir", ["state", "other-state"]) -def test_two_homes_cannot_open_the_same_workspace_concurrently(world, tmp_path, monkeypatch, state_dir): - manager, workspace, calls = world - gateway = tmp_path / "home" - profile = gateway / "profiles" / "fern" - original = tmp_path / "adapters" - for home in (gateway, profile): - registry = home / "chef" / "adapters" - (registry / "orchard").mkdir(parents=True) - for filename in ("orchard/adapter.json", "projects.json"): - (registry / filename).write_bytes((original / filename).read_bytes()) - profile_adapter = profile / "chef" / "adapters" / "orchard" / "adapter.json" - data = json.loads(profile_adapter.read_text()) - data["paths"]["stateDir"] = state_dir - profile_adapter.write_text(json.dumps(data)) - monkeypatch.delenv("HAN_ADAPTERS_DIR") - current_home = ContextVar("hermes_home", default=gateway) - monkeypatch.setitem(sys.modules, "hermes_constants", SimpleNamespace(get_hermes_home=current_home.get)) - default_bridge, profile_bridge = plugin.Bridge(), plugin.Bridge() - assert select(default_bridge, manager)["external"] - token = current_home.set(profile) - assert select(profile_bridge, manager, session="other")["external"] - current_home.reset(token) - inspecting, proceed = Event(), Event() - outcome = [] - - def provider(slot, action, record=None, clean=False): - calls.append((action, (record or {}).get("key"))) - if action == "status" and current_home.get() == gateway: - inspecting.set() - assert proceed.wait(10) - - monkeypatch.setattr(external_slots.Slot, "call", provider) - first = Thread(target=lambda: outcome.append(terminal(default_bridge, "echo han-mission open garden"))) - first.start() - try: - assert inspecting.wait(10) - token = current_home.set(profile) - try: - second = terminal(profile_bridge, "echo han-mission open garden", session="other") - finally: - current_home.reset(token) - assert second and "transition is in progress" in second["message"] - assert not list((profile / "chef" / "external-slots").glob("*.json")) - finally: - proceed.set() - first.join(10) - assert outcome == [None] - assert sum(action == "acquire" for action, _ in calls) == 1 - assert mission.read_active(str(workspace / "state")).session == "owner" - assert terminal(default_bridge, "echo han-mission close garden") is None - - -def test_workspace_transition_uses_filesystem_identity(tmp_path): - folder = tmp_path / "workspace" - folder.mkdir() - alias = tmp_path / "alias" - try: - alias.symlink_to(folder, target_is_directory=True) - except OSError: - pytest.skip("directory links are unavailable") - with external_slots.workspace_transition(str(folder)): - with pytest.raises(LockBusy, match="transition is in progress"): - with external_slots.workspace_transition(str(alias)): - pytest.fail("both paths refer to the same workspace") - - -def test_release_failure_blocks_writes_and_new_admission(world, monkeypatch): - manager, _, calls = world - bridge = plugin.Bridge() - slot = external_slots.from_context(select(bridge, manager)) - assert terminal(bridge, "echo han-mission open garden") is None - - def provider(self, action, record=None, clean=False): - if action == "release": - raise UsageError("external release failed") - - monkeypatch.setattr(external_slots.Slot, "call", provider) - assert "release failed" in terminal(bridge, "echo han-mission close garden")["message"] - assert slot.record()["phase"] == "closing" - assert mission.read_active(slot.state).id == "garden" - assert terminal(bridge, "git status")["action"] == "block" - assert "error" in select(plugin.Bridge(), manager, session="other") - assert ("acquire", "original-request") in calls - - -def test_unknown_acquisition_retains_evidence_but_does_not_open(world, monkeypatch): - manager, _, _ = world - bridge = plugin.Bridge() - slot = external_slots.from_context(select(bridge, manager)) - - def provider(self, action, record=None, clean=False): - if action == "acquire": - raise UsageError("external acquire timed out") - - monkeypatch.setattr(external_slots.Slot, "call", provider) - assert terminal(bridge, "echo han-mission open garden")["action"] == "block" - assert slot.record()["phase"] == "opening" - assert not mission.read_active(slot.state).id - assert "error" in select(bridge, manager) - - -def test_transition_and_delegate_are_serialized(world, monkeypatch): - manager, _, _ = world - bridge = plugin.Bridge() - select(bridge, manager) - assert terminal(bridge, "echo han-mission open garden") is None - - def worker(args, **kwargs): - assert kwargs["external"]["slot"] == "one" - assert terminal(bridge, "echo han-mission close garden")["action"] == "block" - return {"ok": True} - - monkeypatch.setattr(workers, "delegate", worker) - assert json.loads(bridge.delegate({"role": "researcher", "prompt": "read"}, "owner", "owner"))["ok"] - assert terminal(bridge, "echo han-mission close garden") is None - - -def test_unbound_markers_and_undeclared_names_are_blocked(world): - manager, workspace, _ = world - assert "error" in select(plugin.Bridge(), manager, name="orchard.one") - assert terminal(plugin.Bridge(), "echo han-mission open garden", workdir=str(workspace))["action"] == "block" - outcome = mission.decide({"han_runtime": "hermes", "cwd": str(workspace), "session_id": "owner", - "tool_name": "Bash", "tool_input": {"command": "echo han-mission open garden"}}) - assert outcome.deny - assert not (workspace / "state" / "ACTIVE").exists() diff --git a/tests/integration/hermes/test_mission_operations.py b/tests/integration/hermes/test_mission_operations.py deleted file mode 100644 index 75b5cd8..0000000 --- a/tests/integration/hermes/test_mission_operations.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Mission authority is committed by a tool handler, after every pre-tool check.""" - -import json - -import pytest - -from chef.guards import mission -from chef.runtimes.hermes import plugin - - -@pytest.fixture -def managed(tmp_path, monkeypatch): - root = tmp_path / "meadow" - adapter = root / ".hermes/orchestrator/adapter.json" - adapter.parent.mkdir(parents=True) - adapter.write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}})) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "empty")) - monkeypatch.setattr(plugin, "native_cwd", lambda _: str(root)) - return root, plugin.Bridge() - - -def dispatch(bridge, args, owner="owner"): - return json.loads(bridge.mission(args, session_id=owner, task_id="task")) - - -def test_prechecks_do_not_open_or_close_the_mission(managed): - root, bridge = managed - opening = {"action": "open", "mission": "seed"} - assert bridge.before_tool("chef_mission", opening, "owner", "task") is None - assert not (root / "state/ACTIVE").exists() - assert dispatch(bridge, opening)["ok"] - closing = {"action": "close", "mission": "seed"} - assert bridge.before_tool("chef_mission", closing, "owner", "task") is None - # A later plugin may deny the request. No handler means no state change. - assert mission.read_active(str(root / "state")).id == "seed" - assert dispatch(bridge, closing)["ok"] - assert not (root / "state/ACTIVE").exists() - - -def test_handler_rechecks_ownership_and_status_is_read_only(managed): - root, bridge = managed - assert dispatch(bridge, {"action": "open", "mission": "seed"})["ok"] - assert "error" in dispatch(bridge, {"action": "close", "mission": "seed"}, "other") - assert dispatch(bridge, {"action": "status"})["owned"] - assert not dispatch(bridge, {"action": "status"}, "other")["owned"] - assert mission.read_active(str(root / "state")).session == "owner" - - -def test_shell_marker_cannot_mutate_state_before_later_guards(managed): - root, bridge = managed - result = bridge.before_tool("terminal", {"command": "echo han-mission open seed"}, "owner", "task") - assert result["action"] == "block" and "chef_mission" in result["message"] - assert not (root / "state/ACTIVE").exists() - - -def test_managed_close_detaches_tasks_and_restores_their_original_directory(managed, monkeypatch): - root, bridge = managed - restored = [] - monkeypatch.setattr(plugin, "bind_native_cwd", lambda task, cwd: restored.append((task, cwd))) - bridge.bindings[("owner", "task")] = {"cwd": str(root), "return_cwd": str(root.parent)} - assert dispatch(bridge, {"action": "open", "mission": "seed"})["ok"] - assert dispatch(bridge, {"action": "close", "mission": "seed"})["ok"] - assert restored == [("task", str(root.parent))] - assert not bridge.bindings and "owner" not in bridge.released_slots - - -@pytest.mark.parametrize("args", [{"action": "close", "mission": "seed"}, - {"action": "open", "mission": "../seed"}, {"action": "open", "mission": "seed", "cwd": "/"}]) -def test_missing_owner_or_untrusted_arguments_cannot_change_state(managed, args): - root, bridge = managed - assert "error" in dispatch(bridge, args) - assert not (root / "state/ACTIVE").exists() diff --git a/tests/integration/hermes/test_native_bridge.py b/tests/integration/hermes/test_native_bridge.py deleted file mode 100644 index 8191bbd..0000000 --- a/tests/integration/hermes/test_native_bridge.py +++ /dev/null @@ -1,231 +0,0 @@ -"""Native Hermes policy boundary with fictional local workspaces.""" - -import json -import os -import sys -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from chef.runtimes.hermes import plugin - - -@pytest.fixture -def world(tmp_path, monkeypatch): - project = tmp_path / "comet" - registration = project / ".hermes" / "orchestrator" - registration.mkdir(parents=True) - adapter = { - "schema": 1, "project": "Comet", "paths": {"vcsRoot": ".", "stateDir": "state"}, - "guard": {"coordinatorWrite": ["state/**"], "deny": [{"pattern": "dangerous-operation", "reason": "fictional operation denied"}]}, - "agents": {"allow": ["chef:researcher"]}, - } - (registration / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - state = project / "state" - state.mkdir() - (state / "ACTIVE").write_text(json.dumps({"id": "mission", "session": "owner", "runtime": "hermes"}), encoding="utf-8") - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "empty-registry")) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - monkeypatch.setattr(plugin, "native_cwd", lambda _: str(project)) - bridge = plugin.Bridge() - return SimpleNamespace(project=project, bridge=bridge, adapter=adapter, registration=registration) - - -def call(world, tool, args, session="owner", **kwargs): - return world.bridge.before_tool(tool, args, session_id=session, task_id="task", **kwargs) - - -def test_bootstrap_context_exposes_actual_python_even_before_adapter_selection(world, monkeypatch): - for located in (None, SimpleNamespace(project=str(world.project))): - monkeypatch.setattr(plugin.mission, "locate_adapter", lambda *_: located) - context = world.bridge.context(session_id="owner", task_id="task")["context"] - assert json.dumps(sys.executable) in context - assert "absolute interpreter path" in context - def unavailable(*_): - raise ValueError("fictional registry unavailable") - monkeypatch.setattr(plugin.mission, "locate_adapter", unavailable) - assert json.dumps(sys.executable) in world.bridge.context(session_id="owner", task_id="task")["context"] - - -def test_native_terminal_denial_prevents_execution(world): - assert call(world, "terminal", {"command": "dangerous-operation"})["action"] == "block" - assert call(world, "terminal", {"command": "echo safe"}) is None - - -def test_worker_status_forwards_the_trusted_task_workspace(world, monkeypatch, tmp_path): - from chef.runtimes.hermes import workers - - calls = [] - def status(adapter, research, native=None, cwd=None): - calls.append((adapter, research, native, cwd)) - return {"available": True} - monkeypatch.setattr(workers, "status", status) - monkeypatch.setattr(plugin, "native_cwd", lambda _: str(tmp_path / "unrelated")) - world.bridge.bindings[("owner", "task")] = {"cwd": str(world.project)} - result = json.loads(world.bridge.worker_status({}, session_id="owner", task_id="task", cwd="untrusted")) - assert result == {"available": True} - assert len(calls) == 1 and calls[0][3] == str(world.project) - assert calls[0][0]["project"] == "Comet" - assert calls[0][1] is world.bridge.research and calls[0][2] is world.bridge.native - - -@pytest.mark.parametrize("tool,args", [ - ("terminal", {"command": "echo han-mission resume mission"}), - ("write_file", {"path": "state/note.md", "content": "x"}), - ("patch", {"mode": "replace", "path": "state/note.md", "old_string": "x", "new_string": "y"}), -]) -def test_another_session_cannot_take_active_workspace(world, tool, args): - before = (world.project / "state/ACTIVE").read_bytes() - assert call(world, tool, args, session="stranger")["action"] == "block" - assert (world.project / "state/ACTIVE").read_bytes() == before - - -@pytest.mark.parametrize("tool,args", [ - ("write_file", {"path": "source.py", "content": "x"}), - ("patch", {"mode": "replace", "path": "source.py", "old_string": "x", "new_string": "y"}), - ("patch", {"mode": "patch", "patch": "*** Begin Patch\n*** Add File: source.py\n+x\n*** End Patch"}), -]) -def test_coordinator_write_policy_applies_to_each_native_write_form(world, tool, args): - assert call(world, tool, args)["action"] == "block" - - -def test_protected_question_cannot_be_patched(world): - result = call(world, "patch", {"mode": "patch", "patch": "*** Begin Patch\n*** Add File: state/mission/ask-1.md\n+x\n*** End Patch"}) - assert result and result["action"] == "block" - - -def test_native_delegation_and_code_execution_are_not_role_worker_bypasses(world): - for tool in ("delegate_task", "execute_code"): - assert call(world, tool, {"goal": "pretend review"})["action"] == "block" - assert call(world, "chef_delegate", {"role": "chef:researcher", "task": "inspect"}) is None - assert call(world, "chef_delegate", {"role": "unlisted", "task": "inspect"})["action"] == "block" - - -def test_model_supplied_identity_never_weakens_policy(world): - assert call(world, "write_file", {"path": "source.py", "content": "x", "agent_id": "fake", "session_id": "fake"})["action"] == "block" - - -def test_ignored_native_context_keys_cannot_redirect_guard(world, tmp_path): - assert call(world, "terminal", {"command": "dangerous-operation", "cwd": str(tmp_path), "shell": "powershell"})["action"] == "block" - payload = plugin.canonical_payload("terminal", {"command": "echo safe", "cwd": "/unrelated", "shell": "pwsh"}, "owner", "task", str(world.project)) - assert "cwd" not in payload["tool_input"] and "shell" not in payload["tool_input"] - - -def test_guard_failure_and_missing_trusted_identity_fail_closed(world, monkeypatch): - assert world.bridge.before_tool("terminal", {"command": "echo safe"})["action"] == "block" - def broken(*_): - raise RuntimeError("synthetic failure") - monkeypatch.setattr(plugin.mission, "decide", broken) - assert call(world, "terminal", {"command": "echo safe"})["action"] == "block" - - -@pytest.mark.parametrize("guard", [{"deny": ["("]}, {"coordinatorWrite": "invalid"}, ["invalid"]]) -def test_invalid_configured_policy_never_silently_allows_tools(world, guard): - world.adapter["guard"] = guard - (world.registration / "adapter.json").write_text(json.dumps(world.adapter), encoding="utf-8") - assert call(world, "terminal", {"command": "echo safe"})["action"] == "block" - - -def test_restart_with_no_memory_bindings_still_checks_owned_question_integrity(world, monkeypatch): - checked = [] - def check(payload, runtime): - checked.append(payload) - return {"decision": "block", "reason": "fictional missing question receipt"} - monkeypatch.setattr(plugin.integrity, "decide", check) - assert not world.bridge.bindings - outcome = world.bridge.verify(session_id="owner", task_id="task") - assert outcome == {"action": "continue", "message": "fictional missing question receipt"} - assert checked[0]["cwd"] == str(world.project) - - -def test_request_failure_is_carried_to_pretool_instead_of_raising(world, monkeypatch): - def broken(*_): - raise RuntimeError("synthetic failure") - monkeypatch.setattr(plugin, "native_cwd", broken) - result = world.bridge.request("terminal", {"command": "echo safe"}, session_id="owner", task_id="task") - assert call(world, "terminal", result["args"])["action"] == "block" - - -def test_bound_tasks_get_independent_terminal_and_file_paths(world): - other = world.project.parent / "other-slot" - for sid, cwd in (("owner", world.project), ("second", other)): - world.bridge.bindings[(sid, sid)] = {"cwd": str(cwd)} - terminal = world.bridge.request("terminal", {"command": "pwd"}, session_id=sid, task_id=sid) - assert terminal["args"]["workdir"] == str(cwd) - file = world.bridge.request("write_file", {"path": "file.txt", "content": "x"}, session_id=sid, task_id=sid) - assert file["args"]["path"] == str(cwd / "file.txt") - patch = world.bridge.request("patch", {"mode": "patch", "patch": "*** Update File: file.txt\n@@\n-x\n+y"}, session_id=sid, task_id=sid) - assert str(cwd / "file.txt") in patch["args"]["patch"] - - -def test_explicit_workdir_cannot_escape_original_ownership_check(world, tmp_path): - world.bridge.bindings[("stranger", "task")] = {"cwd": str(world.project)} - assert call(world, "terminal", {"command": "echo safe", "workdir": str(tmp_path)}, session="stranger") is None - assert call(world, "terminal", {"command": "touch changed.txt", "workdir": str(tmp_path)}, session="stranger")["action"] == "block" - - -def test_case_distinct_projects_are_not_deduplicated_in_patch_ownership(world, tmp_path): - foreign = tmp_path / "Comet" - foreign.mkdir(exist_ok=True) - if os.path.samefile(foreign, world.project): - pytest.skip("volume does not support case-distinct project directories") - registration = foreign / ".hermes" / "orchestrator" - registration.mkdir(parents=True) - # Allow ordinary source writes so the ownership check is the only reason - # for blocking this multi-project operation. - body = {"schema": 1, "paths": {"stateDir": "state"}} - (registration / "adapter.json").write_text(json.dumps(body), encoding="utf-8") - (world.registration / "adapter.json").write_text(json.dumps(body), encoding="utf-8") - (foreign / "state").mkdir() - (foreign / "state" / "ACTIVE").write_text(json.dumps({ - "id": "foreign-mission", "session": "different-owner", "runtime": "hermes", - }), encoding="utf-8") - patch = ( - f"*** Begin Patch\n*** Add File: {foreign}/source.py\n+x\n" - f"*** Add File: {world.project}/source.py\n+x\n*** End Patch" - ) - result = call(world, "patch", {"mode": "patch", "patch": patch}) - assert result and result["action"] == "block" - assert "another active mission session" in result["message"] - - -def test_dry_slot_selection_does_not_change_binding_or_native_context(world, monkeypatch): - from chef.slots import commands - calls = [] - context = {"cwd": str(world.project), "runtime": "hermes", "session_id": "owner"} - monkeypatch.setattr(commands, "current_session_context", lambda *a, **kw: (calls.append(kw) or context)) - monkeypatch.setattr(plugin, "bind_native_cwd", lambda *a: pytest.fail("dry run must not bind")) - result = json.loads(world.bridge.slot({"project": str(world.project), "name": "slot-a", "dry_run": True}, session_id="owner", task_id="task")) - assert result == context and not world.bridge.bindings - assert calls == [{"resume": False, "dry_run": True}] - - -def test_failed_binding_change_never_runs_preparation(world, monkeypatch): - from chef.slots import commands - calls = [] - monkeypatch.setattr(commands, "current_session_context", lambda *a, **kw: (calls.append(kw) or {"cwd": "/fictional/different"})) - world.bridge.bindings[("owner", "task")] = {"cwd": str(world.project)} - result = json.loads(world.bridge.slot({"project": str(world.project), "name": "slot-b"}, session_id="owner", task_id="task")) - assert "error" in result and calls == [{"resume": False, "dry_run": True}] - - -def test_native_registration_wires_guards_middleware_tools_and_skills(monkeypatch): - class Context: - def __init__(self): - self.hooks, self.middleware, self.tools, self.skills = {}, {}, {}, {} - def register_hook(self, name, callback): - self.hooks[name] = callback - def register_middleware(self, name, callback): - self.middleware[name] = callback - def register_tool(self, name, toolset, schema, handler): - self.tools[name] = (schema, handler) - def register_skill(self, name, path, description): - self.skills[name] = path - monkeypatch.setattr(plugin.sys, "platform", "linux") - ctx = Context() - plugin.register(ctx) - assert set(ctx.hooks) == {"pre_tool_call", "pre_llm_call", "pre_verify"} - assert set(ctx.middleware) == {"tool_request"} - assert set(ctx.tools) == {"chef_slot", "chef_mission", "chef_delegate", "chef_worker_status"} - assert set(ctx.skills) == set(plugin.SKILLS) diff --git a/tests/integration/hermes/test_native_workers.py b/tests/integration/hermes/test_native_workers.py deleted file mode 100644 index 4bcc27a..0000000 --- a/tests/integration/hermes/test_native_workers.py +++ /dev/null @@ -1,331 +0,0 @@ -"""Standalone leaf capabilities exercised with invented workspaces and host events.""" - -import json -import os -import shlex -import subprocess -import sys -import threading -import time -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from chef.guards import adapters, mission -from chef.runtimes.hermes import native, plugin, research, workers - - -pytestmark = pytest.mark.skipif(os.name != "posix", reason="native Hermes requires POSIX file/process capabilities") - - -@pytest.fixture -def workspace(tmp_path, monkeypatch): - root = tmp_path / "comet" - root.mkdir() - adapter = root / ".hermes/orchestrator/adapter.json" - adapter.parent.mkdir(parents=True) - adapter.write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}, - "guard": {"deny": [{"pattern": "forbidden-command", "reason": "invented policy"}]}})) - state = root / "state" - (state / "seed").mkdir(parents=True) - (state / "ACTIVE").write_text(json.dumps({"id": "seed", "session": "parent", "runtime": "hermes"})) - (state / "seed/mission.md").write_text("# Invented task\n") - for name in ("HAN_ADAPTERS_DIR", "HAN_REPO", "CLAUDE_PROJECT_DIR", workers.WORKER_ENV): - monkeypatch.delenv(name, raising=False) - monkeypatch.setattr(adapters, "in_place_adapters_dir", lambda: str(tmp_path / "absent")) - monkeypatch.setattr(research, "profile_config", lambda: {"delegation": {"inherit_mcp_toolsets": False}}) - return SimpleNamespace(root=root, state=state, active=mission.read_active(str(state))) - - -@pytest.fixture -def host(workspace, monkeypatch): - class Lifecycle: - def launch(self, request): - self.request = request - bridge.native.started(parent_session_id="foreign", child_session_id="intruder", - child_subagent_id="wrong", child_goal=request["goal"]) - bridge.native.started(parent_session_id="parent", child_session_id="child-session", - child_subagent_id="child", child_goal=request["goal"]) - return {"subagent_id": "child", "role": "leaf", "model": request.get("model", "invented-model"), - "provider": request.get("provider", "invented-provider")} - - def wait(self, handle, timeout_seconds): - self.observe() - return {"completed": self.complete} - - def result(self, handle): - return {"ready": True, "terminal_state": "SUCCEEDED", "summary": "observed"} - - def cancel(self, handle, reason): - self.cancelled = True - assert "error" in call(native.READ, {"operation": "list"}) - - lifecycle = Lifecycle() - lifecycle.observe = lambda: None - lifecycle.complete, lifecycle.cancelled = True, False - bridge = plugin.Bridge(lifecycle) - monkeypatch.setattr(plugin, "native_cwd", lambda _: str(workspace.root)) - - def call(tool, args, session="child-session"): - return json.loads(bridge.native.tool(tool, args, session_id=session, task_id="child-task")) - - def run(role="dev-small", config=None): - return bridge.native.run(role, "Implement the invented brief.", 10, str(workspace.root), - str(workspace.state), workspace.active, None, None, config=config) - - return SimpleNamespace(bridge=bridge, lifecycle=lifecycle, call=call, run=run) - - -def test_developer_native_write_patch_and_test_flow(workspace, host): - def observe(): - assert host.call(native.WRITE, {"operation": "write", "path": "sample.py", "content": "value = 1\n"})["bytes"] == 10 - assert host.call(native.WRITE, {"operation": "patch", "path": "sample.py", "old_text": "= 1", "new_text": "= 2"})["bytes"] == 10 - command = shlex.quote(sys.executable) + ' -c "from sample import value; assert value == 2; print(value)"' - result = host.call(native.SHELL, {"command": command}) - assert result["exit_code"] == 0 and result["stdout"].strip() == "2", result - assert host.call(native.READ, {"operation": "read", "path": "sample.py"})["text"] == "value = 2\n" - assert host.bridge.before_tool("delegate_task", {}, "child-session", "child-task")["action"] == "block" - assert host.bridge.before_tool("terminal", {}, "child-session", "child-task")["action"] == "block" - assert "error" in host.call(native.READ, {"operation": "list"}, session="intruder") - host.lifecycle.observe = observe - assert host.run()["ok"] - request = host.lifecycle.request - assert request["allowed_toolsets"] == [native.READ_TOOLSET, native.WRITE_TOOLSET, native.SHELL_TOOLSET] - assert "working_directory" not in request and "model" not in request and "provider" not in request - assert host.bridge.before_tool("terminal", {}, "child-session", "child-task")["action"] == "block" - assert "error" in host.call(native.READ, {"operation": "list"}) - - -@pytest.mark.parametrize("role", workers.ROLES) -def test_role_tools_and_explicit_routing(workspace, host, role): - def observe(): - direct = host.call(native.WRITE, {"operation": "write", "path": "sample.txt", "content": "text"}) - shell = host.call(native.SHELL, {"command": "printf evidence"}) - assert ("error" not in direct) == (role in native.DEVELOPERS) - assert ("error" not in shell) == (role not in workers.READ_ONLY) - host.lifecycle.observe = observe - assert host.run(role, {"model": "chosen", "provider": "chosen-provider"})["ok"] - assert host.lifecycle.request["model"] == "chosen" - assert host.lifecycle.request["provider"] == "chosen-provider" - assert host.lifecycle.request["role"] == "leaf" - assert "Codex" not in host.lifecycle.request["context"] - - -@pytest.mark.parametrize("config", [False, [], "", 0]) -def test_invalid_falsey_routing_is_rejected_before_assignment_or_launch(host, monkeypatch, config): - assignments = [] - def assignment(*args, **kwargs): - assignments.append((args, kwargs)) - raise AssertionError("invalid routing must not create an assignment") - monkeypatch.setattr(host.bridge.native, "assignment", assignment) - with pytest.raises(ValueError, match="native role routing"): - host.run(config=config) - assert not assignments and not hasattr(host.lifecycle, "request") - - -def test_paged_read_and_path_denials(workspace, host, tmp_path): - (workspace.root / "long.txt").write_text("a" * research.READ_LIMIT + "tail") - outside = tmp_path / "outside.txt" - outside.write_text("private invented text") - (workspace.root / "alias").symlink_to(outside) - (workspace.root / "alias-dir").symlink_to(tmp_path, target_is_directory=True) - instructions = workspace.root / ".codex/agents/reviewer.toml" - instructions.parent.mkdir(parents=True) - instructions.write_text("Review the invented sample read-only.") - def observe(): - first = host.call(native.READ, {"operation": "read", "path": "long.txt"}) - assert first["truncated"] and first["next_offset"] == research.READ_LIMIT - assert host.call(native.READ, {"operation": "read", "path": "long.txt", "offset": first["next_offset"]})["text"] == "tail" - assert host.call(native.READ, {"operation": "read", "path": ".codex/agents/reviewer.toml"})["text"] == instructions.read_text() - assert "error" in host.call(native.WRITE, {"operation": "write", "path": ".codex/agents/reviewer.toml", "content": "wrong"}) - for path in ("../outside.txt", str(outside), "alias", "alias-dir/outside.txt", "state/ACTIVE", ".hermes/orchestrator/adapter.json", ".git/config"): - assert "error" in host.call(native.READ, {"operation": "read", "path": path}) - assert "error" in host.call(native.WRITE, {"operation": "write", "path": path, "content": "wrong"}) - assert "error" in host.call(native.READ, {"operation": "read", "path": "long.txt", "session_id": "parent"}) - assert "error" in host.call(native.READ, {"operation": "list", "offset": 1}) - host.lifecycle.observe = observe - host.run() - assert outside.read_text() == "private invented text" - - -def test_project_role_and_external_read_sources_are_bound_to_the_job(workspace, host, tmp_path): - import hashlib - - guide = tmp_path.resolve() / "selected-guide.md" - guide.write_text("Approved selected reference.") - role = workspace.root / ".codex/agents/sample.toml" - role.parent.mkdir(parents=True) - role.write_text('model = "chosen"\nmodel_reasoning_effort = "high"\ndeveloper_instructions = "Read the selected guide and review sample.py."\n') - adapter_path = workspace.root / ".hermes/orchestrator/adapter.json" - adapter = json.loads(adapter_path.read_text()) - adapter["workers"] = {"readOnlySources": {str(guide): hashlib.sha256(guide.read_bytes()).hexdigest()}, - "roleContracts": {"code-reviewer": {"path": ".codex/agents/sample.toml", - "sha256": hashlib.sha256(role.read_bytes()).hexdigest(), "modelPolicy": "definition"}}} - adapter_path.write_text(json.dumps(adapter)) - def observe(): - assert host.call(native.READ, {"operation": "read", "path": str(guide)})["text"] == guide.read_text() - assert "error" in host.call(native.WRITE, {"operation": "write", "path": str(guide), "content": "wrong"}) - guide.write_text("Unapproved change.") - assert "error" in host.call(native.READ, {"operation": "read", "path": str(guide)}) - host.lifecycle.observe = observe - assert host.run("code-reviewer")["ok"] - assert host.lifecycle.request["model"] == "chosen" - assert "model_reasoning_effort" not in host.lifecycle.request - assert "reasoning_effort" not in host.lifecycle.request - assert "Read the selected guide and review sample.py." in host.lifecycle.request["context"] - - -def test_readonly_and_concurrently_modified_files_are_preserved(workspace, monkeypatch): - target = workspace.root / "sample.txt" - target.write_text("original") - manager = native.NativeWorkers(None) - with manager.assignment("dev-small", workspace.root, workspace.state, workspace.active, None, None) as job: - target.chmod(0o444) - with pytest.raises(ValueError, match="read-only"): - job.call(native.WRITE, {"operation": "write", "path": "sample.txt", "content": "replacement"}, "task") - assert target.read_text() == "original" - target.chmod(0o644) - original = job.file_version - calls = 0 - def version(directory, name): - nonlocal calls - calls += 1 - if calls == 2: - target.write_text("concurrent") - return original(directory, name) - monkeypatch.setattr(job, "file_version", version) - with pytest.raises(ValueError, match="destination changed"): - job.call(native.WRITE, {"operation": "patch", "path": "sample.txt", "old_text": "original", "new_text": "replacement"}, "task") - assert target.read_text() == "concurrent" - assert not list(workspace.root.glob(".chef-write-*")) - - -def test_guard_command_receives_child_only_schema1_context_for_each_tool(workspace, tmp_path): - guard = tmp_path / "guard.py" - log = tmp_path / "calls.jsonl" - guard.write_text("import json, os, pathlib, sys\n" - "payload = json.load(sys.stdin)\n" - "context = json.loads(pathlib.Path(os.environ['CHEF_HERMES_WORKER']).read_text())\n" - "assert context['schema'] == 1 and context['pid'] > 0\n" - "assert context['role'] == 'dev-small' and context['session'] == payload['session_id'] == 'parent'\n" - "assert context['cwd'] == payload['cwd'] and context['backend'] == 'hermes'\n" - "with pathlib.Path(sys.argv[1]).open('a') as stream: stream.write(payload['tool_name'] + '\\n')\n") - original = os.environ.get(workers.WORKER_ENV) - with native.NativeWorkers(None).assignment("dev-small", workspace.root, workspace.state, workspace.active, - [sys.executable, str(guard), str(log)], None) as job: - context = job.context_path - assert job.call(native.READ, {"operation": "list"}, "task")["entries"] == [] - job.call(native.WRITE, {"operation": "write", "path": "sample.txt", "content": "text"}, "task") - job.call(native.SHELL, {"command": "printf checked"}, "task") - assert log.read_text().splitlines() == [native.READ, "Write", "Bash"] - assert not context.exists() and os.environ.get(workers.WORKER_ENV) == original - - -def test_write_and_patch_guards_receive_source_and_deny_before_mutation(workspace, tmp_path, monkeypatch): - guard = tmp_path / "content_guard.py" - log = tmp_path / "content_payloads.jsonl" - guard.write_text("import json, pathlib, sys\n" - "payload = json.load(sys.stdin)\n" - "with pathlib.Path(sys.argv[1]).open('a') as stream: stream.write(json.dumps(payload) + '\\n')\n" - "inputs = payload['tool_input']\n" - "if 'blocked-text' in inputs.get('content', '') or 'blocked-text' in inputs.get('new_string', ''):\n" - " print(json.dumps({'decision': 'block', 'reason': 'content policy rejected source'}))\n") - shared = [] - decide = mission.decide - def observe(payload): - shared.append(payload) - return decide(payload) - monkeypatch.setattr(mission, "decide", observe) - target = workspace.root / "sample.txt" - target.write_text("original text") - with native.NativeWorkers(None).assignment("dev-small", workspace.root, workspace.state, workspace.active, - [sys.executable, str(guard), str(log)], None) as job: - for path in ("new.txt", "sample.txt"): - with pytest.raises(ValueError, match="content policy rejected source"): - job.call(native.WRITE, {"operation": "write", "path": path, "content": "blocked-text"}, "task") - with pytest.raises(ValueError, match="content policy rejected source"): - job.call(native.WRITE, {"operation": "patch", "path": "sample.txt", - "old_text": "original", "new_text": "blocked-text"}, "task") - assert not (workspace.root / "new.txt").exists() and target.read_text() == "original text" - job.call(native.WRITE, {"operation": "patch", "path": "sample.txt", - "old_text": "original", "new_text": "reviewed"}, "task") - project = [json.loads(line) for line in log.read_text().splitlines()] - assert len(project) == len(shared) == 4 - for project_payload, shared_payload in zip(project, shared): - assert project_payload["tool_input"] == shared_payload["tool_input"] - assert project[0]["tool_name"] == "Write" - assert project[0]["tool_input"] == {"file_path": str(workspace.root / "new.txt"), "content": "blocked-text"} - assert project[2]["tool_name"] == "Edit" - assert project[2]["tool_input"] == {"file_path": str(target), "old_string": "original", "new_string": "blocked-text"} - assert project[3]["tool_input"] == {"file_path": str(target), "old_string": "original", "new_string": "reviewed"} - assert target.read_text() == "reviewed text" and not list(workspace.root.glob(".chef-write-*")) - - -def test_shared_policy_and_protected_state_denials(workspace): - manager = native.NativeWorkers(None) - with manager.assignment("dev-small", workspace.root, workspace.state, workspace.active, None, None) as job: - with pytest.raises(ValueError, match="invented policy"): - job.call(native.SHELL, {"command": "forbidden-command"}, "task") - with pytest.raises(ValueError): - job.call(native.SHELL, {"command": "printf changed > state/ACTIVE"}, "task") - with pytest.raises(ValueError): - job.call(native.SHELL, {"command": "echo han-mission close seed"}, "task") - # The command name is opaque to literal-target extraction. Its mutation - # must still invalidate the assignment without rolling back the file. - helper = workspace.root / "helper.py" - helper.write_text("from pathlib import Path\nPath('state/seed/mission.md').write_text('changed')\n") - with pytest.raises(ValueError, match="protected mission state changed"): - job.call(native.SHELL, {"command": shlex.quote(sys.executable) + " helper.py"}, "task") - with pytest.raises(ValueError, match="no longer active"): - job.call(native.READ, {"operation": "list"}, "task") - assert (workspace.state / "seed/mission.md").read_text() == "changed" - - -def test_timeout_revokes_before_cancel_and_foreign_owner_blocks_all_tools(workspace, host): - host.lifecycle.complete = False - with pytest.raises(ValueError, match="timed out"): - host.run() - assert host.lifecycle.cancelled - assert host.bridge.before_tool("delegate_task", {}, "child-session", "task")["action"] == "block" - with native.NativeWorkers(None).assignment("dev-small", workspace.root, workspace.state, workspace.active, None, None) as job: - (workspace.state / "ACTIVE").write_text(json.dumps({"id": "seed", "session": "foreign", "runtime": "hermes"})) - for tool, args in ((native.READ, {"operation": "list"}), - (native.WRITE, {"operation": "write", "path": "sample.txt", "content": "wrong"}), - (native.SHELL, {"command": "printf wrong"})): - with pytest.raises(ValueError, match="no longer active"): - job.call(tool, args, "task") - assert not (workspace.root / "sample.txt").exists() - - -def test_shell_timeout_output_limit_and_cancel_drain_process_group(workspace): - manager = native.NativeWorkers(None) - with manager.assignment("verifier", workspace.root, workspace.state, workspace.active, None, None) as job: - with pytest.raises(ValueError, match="timed out"): - job.call(native.SHELL, {"command": "sleep 30", "timeout": 1}, "task") - command = shlex.quote(sys.executable) + ' -c "print(\'x\' * 200000)"' - # Fast exits are truncated; a running noisy process is stopped. - try: - result = job.call(native.SHELL, {"command": command}, "task") - assert result["truncated"] and len(result["stdout"]) == native.OUTPUT_LIMIT - except ValueError as exc: - assert "output limit" in str(exc) - errors = [] - def command_call(): - try: - job.call(native.SHELL, {"command": "sleep 30"}, "task") - except ValueError as exc: - errors.append(str(exc)) - thread = threading.Thread(target=command_call) - thread.start() - deadline = time.monotonic() + 5 - while job.process is None and time.monotonic() < deadline: - time.sleep(.01) - assert job.process is not None - pid = job.process.pid - job.revoke() - job.drain() - thread.join(timeout=5) - assert not thread.is_alive() and errors - with pytest.raises(ProcessLookupError): - os.kill(pid, 0) diff --git a/tests/integration/hermes/test_posix_paths.py b/tests/integration/hermes/test_posix_paths.py deleted file mode 100644 index 160829b..0000000 --- a/tests/integration/hermes/test_posix_paths.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Native POSIX path spelling must not redirect project authority checks.""" - -import json -import os - -import pytest - -from chef.runtimes.hermes.plugin import Bridge -from chef.slots import commands -from chef.slots.storage import Rows - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX literal backslash directory") -def test_literal_backslash_foreign_project_is_checked_for_native_write(tmp_path): - for name, owner in (("garden", "owner"), ("foreign\\garden", "other-owner")): - project = tmp_path / name - registration = project / ".hermes" / "orchestrator" - registration.mkdir(parents=True) - (registration / "adapter.json").write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}}), encoding="utf-8") - (project / "state").mkdir() - (project / "state" / "ACTIVE").write_text(json.dumps({"id": "garden-mission", "session": owner, "runtime": "hermes"}), encoding="utf-8") - bridge = Bridge() - bridge.bindings[("owner", "task")] = {"cwd": str(tmp_path / "garden")} - foreign = tmp_path / "foreign\\garden" - result = bridge.before_tool("write_file", {"path": str(foreign / "source.py"), "content": "fictional"}, "owner", "task") - assert result and result["action"] == "block" - assert "another active mission session" in result["message"] - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX literal backslash directory") -def test_slot_metadata_preserves_native_backslash_root(tmp_path): - project = tmp_path / "garden" - registration = project / ".hermes" / "orchestrator" - registration.mkdir(parents=True) - root = tmp_path / "slots\\literal" - body = {"schema": 1, "paths": {"stateDir": "state"}, "slots": { - "enabled": True, "root": str(root), "client": "garden-{name}", "names": ["one"], "vcs": "none", "prepare": [], - }} - (registration / "adapter.json").write_text(json.dumps(body), encoding="utf-8") - assert commands.main(["--runtime", "hermes", "--project", str(project), "create", "one"]) == 0 - assert Rows(str(project / "state" / "slots.tsv")).find("one")["path"] == str(root / "one") diff --git a/tests/integration/hermes/test_runtime.py b/tests/integration/hermes/test_runtime.py deleted file mode 100644 index 7511f0f..0000000 --- a/tests/integration/hermes/test_runtime.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Runtime contracts using entirely fictional projects and isolated homes.""" - -import json -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from chef.cli import check_guard, doctor, distill, mission_entry -from chef.guards import adapters, mission, subagents -from chef.mission import state -from chef.mission.contracts import Context -from chef.runtimes import hooks -from chef.slots import contracts - - -def write_json(path, value): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(value), encoding="utf-8") - return path - - -@pytest.fixture(autouse=True) -def isolated_environment(tmp_path, monkeypatch): - for key in ( - "HAN_ADAPTERS_DIR", "HAN_REPO", "CLAUDE_PROJECT_DIR", - "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "CLAUDE_ENV_FILE", "HAN_GUARD_LOG", - "HAN_DISTILL_LOG", "GROK_HOOK_EVENT", "GROK_SESSION_ID", "HERMES_SESSION_ID", - ): - monkeypatch.delenv(key, raising=False) - monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes-home")) - monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) - monkeypatch.setattr(adapters, "in_place_adapters_dir", lambda: str(tmp_path / "absent")) - - -def adapter(project, extra=None, kind=".hermes"): - return write_json(project / kind / "orchestrator" / "adapter.json", { - "schema": 1, - "project": "fictional-garden", - "paths": {"stateDir": "state"}, - **(extra or {}), - }) - - -def payload(project, tool, tool_input, **extra): - return { - "han_runtime": "hermes", "hook_event_name": "PreToolUse", - "session_id": "garden-owner", "cwd": str(project), - "tool_name": tool, "tool_input": tool_input, **extra, - } - - -def test_nearest_hermes_adapter_precedes_other_runtime_and_ambient_project(tmp_path, monkeypatch): - project = tmp_path / "garden" - child = project / "src" - child.mkdir(parents=True) - adapter(tmp_path, kind=".hermes") - adapter(project, kind=".claude") - selected = adapter(project) - other = tmp_path / "other" - adapter(other) - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(other)) - found = adapters.find_adapter({"cwd": str(child), "han_runtime": "hermes"}) - assert Path(found.project) == project - assert Path(found.adapter_path) == selected - - -def test_hermes_overlay_and_local_overlay_are_applied_to_same_adapter(tmp_path): - selected = adapter(tmp_path, { - "vars": {"common": "base"}, - "runtimes": {"hermes": {"project": "hermes-garden", "vars": {"runtime": "base"}}}, - }) - write_json(selected.parent / "local.json", { - "vars": {"common": "local"}, - "runtimes": {"hermes": {"vars": {"runtime": "local"}}}, - }) - problems = [] - loaded = adapters.load_adapter(str(selected), problems, "hermes") - assert not problems - assert loaded["project"] == "hermes-garden" - assert loaded["vars"] == {"common": "local", "runtime": "local"} - assert adapters.load_adapter(str(selected), [], "claude")["project"] == "fictional-garden" - - -def test_registry_uses_explicit_environment_before_hermes_home(tmp_path, monkeypatch): - home_registry = tmp_path / "hermes-home" / "chef" / "adapters" - home_registry.mkdir(parents=True) - assert adapters.resolve_registry("hermes") == adapters.Registry(str(home_registry), "hermesHome") - selected = tmp_path / "explicit-adapters" - selected.mkdir() - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(selected)) - assert adapters.resolve_registry("hermes") == adapters.Registry(str(selected), "env") - - -def test_canonical_bridge_payload_keeps_owner_and_does_not_trust_environment(tmp_path, monkeypatch): - monkeypatch.setenv("HERMES_SESSION_ID", "ambient-session") - original = payload(tmp_path, "Bash", {"command": "python task.py"}, agent_id="trusted-child") - normalized = hooks.normalize_payload(original) - assert normalized["session_id"] == "garden-owner" - assert normalized["agent_id"] == "trusted-child" - assert normalized["tool_input"] == original["tool_input"] - assert hooks.runtime_of({}) == "claude" - - -def test_hermes_owner_marker_records_runtime_and_command_guard_applies(tmp_path): - adapter(tmp_path, {"guard": {"deny": [{"pattern": "forbidden-action", "reason": "fictional restriction"}]}}) - outcome = mission.decide(payload(tmp_path, "Bash", {"command": "echo han-mission open garden-mission"}), marker_mode="execute") - assert not outcome.deny - active = mission.read_active(str(tmp_path / "state")) - assert (active.id, active.session, active.runtime) == ("garden-mission", "garden-owner", "hermes") - outcome = mission.decide(payload(tmp_path, "Bash", {"command": "forbidden-action"})) - assert outcome.deny.startswith("fictional restriction") - - -def test_trusted_child_cannot_replace_parent_active(tmp_path): - adapter(tmp_path) - write_json(tmp_path / "state" / "ACTIVE", { - "id": "garden-mission", "session": "garden-owner", "openedAt": "2026-01-01", "runtime": "hermes", - }) - outcome = mission.decide(payload(tmp_path, "Bash", {"command": "echo han-mission close garden-mission"}, agent_id="trusted-child")) - assert outcome.deny and "Hermes" in outcome.deny - assert mission.read_active(str(tmp_path / "state")).id == "garden-mission" - - -def test_canonical_hermes_delegation_checks_chef_role(tmp_path): - adapter(tmp_path, {"agents": {"allow": ["chef:researcher"]}}) - assert not subagents.decide(payload(tmp_path, "delegate_task", {"subagent_type": "chef:researcher"})).deny - assert subagents.decide(payload(tmp_path, "delegate_task", {"subagent_type": "other-role"})).deny - - -def test_hermes_transcripts_do_not_guess_another_runtime_file(tmp_path, monkeypatch): - folder = tmp_path / "state" / "garden-mission" - folder.mkdir(parents=True) - (folder / "sessions.tsv").write_text("at\taction\tsession\ttranscript\nnow\topen\tgarden-owner\t\n", encoding="utf-8") - monkeypatch.setattr(state, "search_claude", lambda *args: pytest.fail("must not inspect another runtime")) - context = Context({}, str(folder.parent), folder.name, "hermes", str(tmp_path)) - assert state.cmd_transcripts(context, SimpleNamespace()) == ["없음: garden-owner"] - - -def test_runtime_choices_and_hermes_distill_home(tmp_path): - assert "hermes" in contracts.RUNTIMES - assert "hermes" not in contracts.TERMINAL_RUNTIMES - assert "hermes" in mission_entry.RUNTIMES - assert check_guard.consume_runtime(["--runtime", "hermes"], "claude")[1] == "hermes" - assert Path(distill.log_path("hermes")).is_relative_to(tmp_path / "hermes-home") - report = doctor.Report() - selected = adapter(tmp_path, {"runtimes": {"hermes": {"rolePolicy": {"model": "definition", "subagents": True}}}}) - doctor.check_role_policy(report, "garden", str(selected)) - assert not report.failed - - -def test_hermes_registry_uses_home_even_when_folder_is_missing(tmp_path): - expected = tmp_path / "hermes-home" / "chef" / "adapters" - assert not expected.exists() - assert adapters.resolve_registry("hermes") == adapters.Registry(str(expected), "hermesHome") - - -def test_in_place_registry_is_not_used_for_a_foreign_project(tmp_path, monkeypatch): - repo_adapters = tmp_path / "chef-repo" / "adapters" - repo_adapters.mkdir(parents=True) - monkeypatch.setattr(adapters, "in_place_adapters_dir", lambda: str(repo_adapters)) - foreign = tmp_path / "other-project" - foreign.mkdir() - assert adapters.resolve_registry("claude", project=str(foreign)) == adapters.Registry("", "none") - inside = tmp_path / "chef-repo" / "src" - inside.mkdir() - assert adapters.resolve_registry("claude", project=str(inside)) == adapters.Registry( - str(repo_adapters), "in-place" - ) - message = adapters.registry_missing_message("claude", project=str(foreign)) - assert "in-place" in message and "건너뜀" in message diff --git a/tests/integration/hermes/test_worker_contracts.py b/tests/integration/hermes/test_worker_contracts.py deleted file mode 100644 index 9859ed5..0000000 --- a/tests/integration/hermes/test_worker_contracts.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Invented external documents and role definitions keep explicit authority.""" - -import hashlib -import json -import os - -import pytest - -from chef.runtimes.hermes.contracts import ReadSources, preflight, role_contract - - -def fingerprint(path): - return hashlib.sha256(path.read_bytes()).hexdigest() - - -def test_exact_source_hash_and_paging_are_checked_on_every_read(tmp_path): - document = tmp_path.resolve() / "guide.md" - document.write_text("approved guidance") - sources = ReadSources({str(document): fingerprint(document)}) - assert sources.read(str(document), 9)["text"] == "guidance" - with pytest.raises(ValueError, match="approved"): - sources.read(str(tmp_path / "unlisted.md")) - document.write_text("changed guidance") - with pytest.raises(ValueError, match="changed"): - sources.read(str(document)) - - -def test_role_policy_is_validated_before_a_model_can_be_launched(tmp_path): - role = tmp_path.resolve() / "role.toml" - role.write_text('model = "chosen-model"\nmodel_reasoning_effort = "high"\ndeveloper_instructions = "Review sample files."\n') - settings = {"roleContracts": {"researcher": {"path": role.name, "sha256": fingerprint(role), "modelPolicy": "definition"}}} - preflight(settings, tmp_path, ["researcher"]) - routing, body = role_contract(settings, tmp_path, "researcher") - assert routing == {"model": "chosen-model"} and body == "Review sample files." - with pytest.raises(ValueError, match="conflicts"): - role_contract(settings, tmp_path, "researcher", {"model": "another"}) - role.write_text('developer_instructions = "unapproved"\n') - with pytest.raises(ValueError, match="changed"): - role_contract(settings, tmp_path, "researcher") - - -def test_inherited_hermes_model_does_not_import_codex_effort(tmp_path): - role = tmp_path.resolve() / "role.toml" - role.write_text('model_reasoning_effort = "high"\ndeveloper_instructions = "Inspect sample files."\n') - settings = {"roleContracts": {"researcher": {"path": role.name, "sha256": fingerprint(role), "modelPolicy": "inherit"}}} - assert role_contract(settings, tmp_path, "researcher") == ({}, "Inspect sample files.") - - -@pytest.mark.skipif(os.name != "posix", reason="Hermes descriptor reads require POSIX") -def test_approved_source_cannot_be_replaced_by_a_link(tmp_path): - document = tmp_path.resolve() / "guide.md" - other = tmp_path.resolve() / "other.md" - document.write_text("approved") - other.write_text("approved") - sources = ReadSources({str(document): fingerprint(document)}) - document.unlink() - document.symlink_to(other) - with pytest.raises(ValueError, match="links"): - sources.read(str(document)) diff --git a/tests/integration/hermes/test_workers.py b/tests/integration/hermes/test_workers.py deleted file mode 100644 index 691ff4a..0000000 --- a/tests/integration/hermes/test_workers.py +++ /dev/null @@ -1,735 +0,0 @@ -"""Hermes role worker authority and hook acknowledgements with fictional homes.""" - -import io -import contextlib -import json -import os -import subprocess -import sys -import time -import tomllib -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from chef.guards import adapters, mission, subagents -from chef.runtimes import hooks -from chef.runtimes.hermes import plugin, research, workers - - -def write_json(path, value): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(value), encoding="utf-8") - - -@pytest.fixture -def project(tmp_path, monkeypatch): - root = tmp_path / "garden with spaces" - root.mkdir() - selected = root / ".hermes/orchestrator/adapter.json" - write_json(selected, { - "schema": 1, "project": "fictional-orchard", "paths": {"stateDir": "state"}, - "agents": {"allow": ["chef:*"]}, - "workers": {"backend": "codex"}, - "guard": {"deny": [{"pattern": "forbidden-action", "reason": "fictional command blocked"}]}, - }) - active = root / "state/ACTIVE" - write_json(active, { - "id": "garden-mission", "session": "garden-owner", "runtime": "hermes", - "openedAt": "2026-01-01", - }) - (root / "state/garden-mission").mkdir() - (root / "state/garden-mission/mission.md").write_text("# Fictional mission\n") - for name in ("HAN_ADAPTERS_DIR", "HAN_REPO", "CLAUDE_PROJECT_DIR", "GROK_SESSION_ID", - "GROK_HOOK_EVENT", "CHEF_HERMES_WORKER"): - monkeypatch.delenv(name, raising=False) - monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes-home")) - monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) - monkeypatch.setattr(adapters, "in_place_adapters_dir", lambda: str(tmp_path / "absent")) - return SimpleNamespace(root=root, adapter=selected, active=active) - - -@pytest.fixture -def codex(monkeypatch): - auth_calls = [] - worker_calls = [] - - def auth(command, **kwargs): - auth_calls.append((command, kwargs)) - assert command == ["/fictional/codex", "login", "status"] - return SimpleNamespace(returncode=0, stdout="Logged in using ChatGPT", stderr="") - - def run(command, prompt, env, timeout): - context_path = Path(env[workers.WORKER_ENV]) - data = json.loads(context_path.read_text(encoding="utf-8")) - worker_calls.append((command, prompt, dict(env), timeout, data)) - with monkeypatch.context() as context: - context.setenv(workers.WORKER_ENV, str(context_path)) - normalized = hooks.normalize_payload({ - "han_runtime": "codex", "hook_event_name": "SessionStart", - "session_id": "native-codex-worker-session", "cwd": data["cwd"], - }) - probe_payload = { - "session_id": "native-codex-worker-session", "cwd": data["cwd"], - "hook_event_name": "PreToolUse", "tool_name": "Bash", - "tool_input": {"command": "echo han-mission open chef-worker-probe"}, - } - output = io.StringIO() - context.setattr(mission.sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(probe_payload).encode()))) - context.setattr(mission.sys, "stdout", output) - assert mission.main("codex") == 0 - assert json.loads(output.getvalue())["hookSpecificOutput"]["permissionDecision"] == "deny" - assert normalized["session_id"] == "garden-owner" - assert normalized["agent_id"] == "chef-codex-worker" - assert normalized["han_hermes_worker"]["digest"] == workers.implementation_digest() - return SimpleNamespace(returncode=0, stdout='{"type":"item.completed","item":{"type":"agent_message","text":"fictional result"}}\n', stderr="") - - monkeypatch.setattr(workers.shutil, "which", lambda name: "/fictional/codex" if name == "codex" else None) - monkeypatch.setattr(workers.subprocess, "run", auth) - monkeypatch.setattr(workers, "run_codex", run) - return SimpleNamespace(auth_calls=auth_calls, calls=worker_calls, auth=auth, run=run) - - -def delegate(project, **args): - return workers.delegate({"role": "chef:dev-small", "prompt": "Inspect the fictional garden.", **args}, - session_id="garden-owner", cwd=str(project.root)) - - -def test_worker_requires_subscription_and_matching_hook_probe(project, codex, monkeypatch): - for name in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE"): - monkeypatch.setenv(name, "fictional-unusable-value") - prompt = 'Keep quotes "and spaces"; $HOME stays data.\nSecond line.' - result = delegate(project, prompt=prompt, timeout=240) - assert result == {"ok": True, "runtime": "codex", "role": "chef:dev-small", - "exit_code": 0, "result": "fictional result", "error": ""} - assert len(codex.auth_calls) == 1 and len(codex.calls) == 2 - probe, worker = codex.calls - assert probe[0][probe[0].index("--sandbox") + 1] == "read-only" - assert probe[3] == 120 - assert worker[0][worker[0].index("--sandbox") + 1] == "workspace-write" - assert worker[1] == prompt and prompt not in worker[0] - assert worker[3] == 240 - assert probe[4]["session"] == worker[4]["session"] == "garden-owner" - assert probe[4]["cwd"] == str(project.root.resolve()) - for call in (probe, worker): - assert all(name not in call[2] for name in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE")) - assert call[2]["PWD"] == str(project.root) - assert not Path(worker[2][workers.WORKER_ENV]).exists() - assert mission.read_active(str(project.root / "state")).session == "garden-owner" - - -def test_worker_hook_process_inherits_request_profile(project, codex, monkeypatch): - gateway = Path(os.environ["HERMES_HOME"]) - profile = gateway / "profiles" / "garden" - registry = profile / "chef" / "adapters" - selected = registry / "garden" / "adapter.json" - selected.parent.mkdir(parents=True) - project.adapter.rename(selected) - write_json(registry / "projects.json", [{"adapter": "garden", "roots": [str(project.root)]}]) - monkeypatch.setitem(sys.modules, "hermes_constants", SimpleNamespace(get_hermes_home=lambda: profile)) - assert delegate(project)["ok"] - for _, _, env, _, _ in codex.calls: - assert env["HERMES_HOME"] == str(profile) - with monkeypatch.context() as child: - child.delitem(sys.modules, "hermes_constants") - child.setenv("HERMES_HOME", env["HERMES_HOME"]) - located = adapters.find_adapter({"cwd": str(project.root), "han_runtime": "hermes"}) - assert Path(located.adapter_path) == selected - assert os.environ["HERMES_HOME"] == str(gateway) - - -def test_uninitialized_mission_is_rejected_before_any_model_or_auth_call(project, codex): - (project.root / "state/garden-mission/mission.md").unlink() - with pytest.raises(ValueError, match="initialize"): - delegate(project) - assert not codex.calls and not codex.auth_calls - - -def test_opaque_helper_state_mutation_invalidates_worker_result_without_rollback(project, codex, monkeypatch): - control = project.root / "state/garden-mission/units.tsv" - control.parent.mkdir(exist_ok=True) - control.write_text("original") - calls = [] - - def run(command, prompt, env, timeout): - result = codex.run(command, prompt, env, timeout) - calls.append(command) - if len(calls) == 2: - control.write_text("unexpected helper mutation") - return result - - monkeypatch.setattr(workers, "run_codex", run) - with pytest.raises(ValueError, match="protected mission state changed"): - delegate(project) - assert control.read_text() == "unexpected helper mutation" - - -@pytest.mark.parametrize("role", workers.ROLES) -def test_role_command_preserves_model_instructions_and_native_argument_boundaries(project, role): - command = workers.command_for("/fictional/codex", role, str(project.root)) - assert command[:3] == ["/fictional/codex", "--no-daemon", "exec"] - source = tomllib.loads((workers.PLUGIN_ROOT / "codex/agents" / f"chef-{role}.toml").read_text(encoding="utf-8")) - assert command[command.index("-C") + 1] == str(project.root) - if source.get("model"): - assert command[command.index("--model") + 1] == source["model"] - else: - assert "--model" not in command - assert command[command.index("--sandbox") + 1] == ("read-only" if role in workers.READ_ONLY else "workspace-write") - assert command[-1] == "-" - settings = dict(command[index + 1].split("=", 1) for index, item in enumerate(command) if item == "-c") - assert json.loads(settings["forced_login_method"]) == "chatgpt" - assert json.loads(settings["model_provider"]) == "openai" - if source.get("model_reasoning_effort"): - assert json.loads(settings["model_reasoning_effort"]) == source["model_reasoning_effort"] - assert json.loads(settings["developer_instructions"]).startswith(source["developer_instructions"]) - assert "--enable" in command and command[command.index("--enable") + 1] == "hooks" - - -@pytest.mark.parametrize("status,stdout,stderr", [ - (1, "", "Not logged in"), - (0, "Logged in using an API key", ""), -]) -def test_missing_subscription_never_starts_any_worker(project, codex, monkeypatch, status, stdout, stderr): - monkeypatch.setattr(workers.subprocess, "run", lambda *args, **kwargs: - SimpleNamespace(returncode=status, stdout=stdout, stderr=stderr)) - with pytest.raises(ValueError, match="subscription"): - delegate(project) - assert not codex.calls - - -def test_missing_codex_does_not_fall_back_to_an_api(project, codex, monkeypatch): - monkeypatch.setattr(workers.shutil, "which", lambda _: None) - with pytest.raises(ValueError, match="Codex CLI"): - delegate(project) - assert not codex.auth_calls and not codex.calls - - -@pytest.fixture -def native(project, monkeypatch): - class Lifecycle: - def launch(self, request): - assert request["allowed_toolsets"] == [research.TOOLSET] - assert request["parent_session_id"] == "garden-owner" - bridge.research.started(parent_session_id="other-session", child_session_id="intruder", - child_subagent_id="other-child", child_goal=request["goal"]) - bridge.research.started(parent_session_id="garden-owner", child_session_id="research-session", - child_subagent_id="child", child_goal=request["goal"]) - self.launches += 1 - return {"subagent_id": "child", "provider": "fictional", "model": "orchard-model", "role": "leaf"} - - def wait(self, handle, *, timeout_seconds): - assert timeout_seconds == 10 - assert not bridge.research.owns("intruder") - assert bridge.before_tool("write_file", {}, "research-session", "child-task")["action"] == "block" - assert bridge.before_tool(research.TOOL, {}, "garden-owner", "task")["action"] == "block" - self.observe() - return {"completed": not self.timeout} - - def result(self, handle): - return {"ready": True, "terminal_state": "SUCCEEDED", "summary": "observed evidence"} - - def cancel(self, handle, *, reason): - self.cancelled = True - assert "no longer active" in read({"operation": "list"})["error"] - - lifecycle = Lifecycle() - lifecycle.launches = 0 - lifecycle.cancelled = lifecycle.timeout = False - lifecycle.observe = lambda: None - bridge = plugin.Bridge(lifecycle) - bridge.native = None # Exercise the legacy read-only host compatibility path. - monkeypatch.setattr(plugin, "native_cwd", lambda _: str(project.root)) - monkeypatch.setattr(research, "profile_config", lambda: {"delegation": {"inherit_mcp_toolsets": False}}) - monkeypatch.setattr(workers.shutil, "which", lambda _: None) - data = json.loads(project.adapter.read_text()) - data["runtimes"] = {"hermes": {"workers": {"backend": "hermes"}}} - write_json(project.adapter, data) - - def read(args): - return json.loads(bridge.research.read(args, "research-session", "child-task")) - - def run(role="chef:researcher"): - return json.loads(bridge.delegate({"role": role, "prompt": "Inspect the orchard", "timeout": 10}, - "garden-owner", "task")) - - return SimpleNamespace(bridge=bridge, lifecycle=lifecycle, run=run, read=read) - - -@pytest.mark.skipif(os.name != "posix", reason="native Hermes filesystem access uses POSIX directory descriptors") -def test_native_research_reads_only_its_owned_workspace(project, native, tmp_path): - (project.root / "notice.txt").write_text("fictional text", encoding="utf-8") - outside = tmp_path / "outside.txt" - outside.write_text("outside the slot", encoding="utf-8") - (project.root / "alias").symlink_to(outside) - (project.root / "alias-dir").symlink_to(tmp_path, target_is_directory=True) - - def observe(): - assert native.read({"operation": "read", "path": "notice.txt"})["text"] == "fictional text" - entries = native.read({"operation": "list"})["entries"] - assert "notice.txt" in entries and not {"alias", "alias-dir/", "state/"} & set(entries) - for target in ("../outside.txt", "alias", "alias-dir/outside.txt", str(outside), "state/ACTIVE", ".git/config"): - assert "error" in native.read({"operation": "read", "path": target}) - assert "error" in native.read({"operation": "write", "path": "notice.txt"}) - assert "error" in native.read({"operation": "read", "path": "notice.txt", "session_id": "garden-owner"}) - - native.lifecycle.observe = observe - assert native.run() == {"ok": True, "runtime": "hermes", "role": "chef:researcher", "result": "observed evidence", - "error": "", "model": "orchard-model", "provider": "fictional"} - assert "error" in native.read({"operation": "list"}) - - -def test_native_worker_preflight_and_unsupported_role(project, native, monkeypatch): - status = lambda: json.loads(native.bridge.worker_status({}, "garden-owner", "task")) - assert status() == {"available": True, "backend": "hermes", "roles": ["chef:researcher"]} - assert "unavailable for this role" in native.run("chef:dev-small")["error"] - monkeypatch.setattr(research, "profile_config", lambda: {"delegation": {"inherit_mcp_toolsets": True}}) - assert "inherit_mcp_toolsets" in status()["error"] - assert "inherit_mcp_toolsets" in native.run()["error"] - assert native.lifecycle.launches == 0 - - -def test_native_timeout_revokes_tool_access_before_cancelling(native): - native.lifecycle.timeout = True - assert "timed out" in native.run()["error"] - assert native.lifecycle.cancelled - assert native.bridge.before_tool("terminal", {}, "research-session", "child-task")["action"] == "block" - native.bridge.research.stopped(parent_session_id="garden-owner", child_session_id="research-session") - assert not native.bridge.research.owns("research-session") - - -def test_native_read_rechecks_active_and_project_guard(project, native, monkeypatch): - calls = [] - monkeypatch.setattr(research, "project_denial", lambda payload: (calls.append(payload) or "denied by project")) - - def observe(): - assert native.read({"operation": "list"})["error"] == "denied by project" - project.active.unlink() - assert "no longer active" in native.read({"operation": "list"})["error"] - - native.lifecycle.observe = observe - assert "mission ownership" in native.run()["error"] - assert len(calls) == 1 and calls[0]["session_id"] == "garden-owner" - - -@pytest.mark.parametrize("mutation", ["missing", "wrong-owner", "wrong-runtime", "corrupt"]) -def test_worker_refuses_missing_or_foreign_active_before_auth(project, codex, mutation): - if mutation == "missing": - project.active.unlink() - elif mutation == "corrupt": - project.active.write_text("{", encoding="utf-8") - else: - active = json.loads(project.active.read_text(encoding="utf-8")) - active["session" if mutation == "wrong-owner" else "runtime"] = "another-session" - write_json(project.active, active) - with pytest.raises(ValueError, match="ACTIVE"): - delegate(project) - assert not codex.auth_calls and not codex.calls - - -def test_disallowed_role_does_not_authenticate_or_launch(project, codex): - adapter = json.loads(project.adapter.read_text(encoding="utf-8")) - adapter["agents"]["allow"] = ["chef:researcher"] - write_json(project.adapter, adapter) - with pytest.raises(ValueError, match="permitted"): - delegate(project) - assert not codex.auth_calls and not codex.calls - - -PROJECT_HOOK = 'hooks.PreToolUse=[{matcher=".*",hooks=[{type="command",command="fictional-guard hook"}]}]' - - -def test_adapter_worker_arguments_reach_probe_and_worker_in_order(project, codex): - adapter = json.loads(project.adapter.read_text(encoding="utf-8")) - extra = ["-c", "sandbox_workspace_write.network_access=true", "-c", 'shell_environment_policy.set.ORCHARD="1"'] - adapter["runtimes"] = {"hermes": {"workers": {"codexArguments": extra}}} - write_json(project.adapter, adapter) - assert delegate(project)["ok"] - assert len(codex.calls) == 2 - for command, *_ in codex.calls: - assert command[-len(extra) - 1:] == extra + ["-"] - assert command[command.index("-C") + 1] == str(project.root) - - -def test_worker_arguments_default_to_none(project): - assert workers.extra_arguments({}) == [] - assert workers.command_for("/fictional/codex", "dev-small", str(project.root))[-1] == "-" - - -@pytest.mark.parametrize("workers_value", [ - [], - {"codexArguments": "-c a=b"}, - {"codexArguments": ["-c"]}, - {"codexArguments": ["--sandbox", "danger-full-access"]}, - {"codexArguments": ["-c", "no-assignment"]}, - {"codexArguments": ["-c", "=value"]}, - {"codexArguments": ["-c", "a=b\nc=d"]}, - {"codexArguments": ["-c", 'model="other"']}, - {"codexArguments": ["-c", 'model_providers.other.base_url="https://example.invalid"']}, - {"codexArguments": ["-c", "features.hooks=false"]}, - {"codexArguments": ["-c", 'sandbox_mode="danger-full-access"']}, - {"codexArguments": ["-c", 'approval_policy="never"']}, - {"codexArguments": ["-c", 'developer_instructions="replace"']}, - {"codexArguments": ["-c", PROJECT_HOOK]}, - {"codexArguments": ["-c", 'mcp_servers.orchard.command="fictional"']}, - {"codexArguments": ["-c", 'sandbox_workspace_write.writable_roots=["/fictional"]']}, - {"guardCommand": "fictional-guard"}, - {"guardCommand": []}, - {"guardCommand": ["fictional-guard", ""]}, - {"guardCommand": [str(Path("/fictional/missing-guard"))]}, -]) -def test_invalid_or_pinned_worker_arguments_stop_before_auth(project, codex, workers_value): - adapter = json.loads(project.adapter.read_text(encoding="utf-8")) - adapter["workers"] = {"backend": "codex", **workers_value} if isinstance(workers_value, dict) else workers_value - write_json(project.adapter, adapter) - with pytest.raises(ValueError, match="workers"): - delegate(project) - assert not codex.auth_calls and not codex.calls - - -@pytest.mark.parametrize("acknowledgement,returncode", [(None, 0), ("outdated-digest", 0), ("matching", 1)]) -def test_missing_or_failed_probe_prevents_write_worker(project, codex, monkeypatch, acknowledgement, returncode): - calls = [] - - def probe(command, prompt, env, timeout): - calls.append(command) - data = json.loads(Path(env[workers.WORKER_ENV]).read_text(encoding="utf-8")) - if acknowledgement: - Path(data["ready"]).write_text(data["digest"] if acknowledgement == "matching" else acknowledgement) - return SimpleNamespace(returncode=returncode, stdout="", stderr="") - - monkeypatch.setattr(workers, "run_codex", probe) - with pytest.raises(ValueError, match="hooks"): - delegate(project) - assert len(calls) == 1 - assert calls[0][calls[0].index("--sandbox") + 1] == "read-only" - - -def test_failed_write_worker_returns_failure_without_fallback(project, codex, monkeypatch): - def run(command, prompt, env, timeout): - result = codex.run(command, prompt, env, timeout) - if len(codex.calls) == 2: - result.returncode, result.stderr = 9, "fictional failure" - return result - - monkeypatch.setattr(workers, "run_codex", run) - result = delegate(project) - assert result["ok"] is False and result["exit_code"] == 9 - assert result["error"] == "fictional failure" - assert len(codex.calls) == 2 - - -def test_owner_change_during_read_only_probe_prevents_write_worker(project, codex, monkeypatch): - def run(command, prompt, env, timeout): - result = codex.run(command, prompt, env, timeout) - active = json.loads(project.active.read_text(encoding="utf-8")) - active["session"] = "replacement-owner" - write_json(project.active, active) - return result - - monkeypatch.setattr(workers, "run_codex", run) - with pytest.raises(ValueError, match="changed"): - delegate(project) - assert len(codex.calls) == 1 - - -def test_actual_worker_must_acknowledge_hook_after_probe(project, codex, monkeypatch): - calls = [] - - def run(command, prompt, env, timeout): - calls.append(command) - if len(calls) == 1: - return codex.run(command, prompt, env, timeout) - return SimpleNamespace(returncode=0, stdout="", stderr="") - - monkeypatch.setattr(workers, "run_codex", run) - with pytest.raises(ValueError, match="acknowledge"): - delegate(project) - assert len(calls) == 2 - - -def context(project, monkeypatch, **updates): - record = project.root.parent / "trusted-worker.json" - data = { - "schema": 1, "pid": os.getpid(), "session": "garden-owner", "role": "dev-small", - "mission": "garden-mission", - "cwd": str(project.root.resolve()), "state": str((project.root / "state").resolve()), - "ready": str(record.with_suffix(".ready")), - "guard_ready": str(record.with_suffix(".guard-ready")), "digest": workers.implementation_digest(), - "guard": None, - **updates, - } - write_json(record, data) - monkeypatch.setenv(workers.WORKER_ENV, str(record)) - return data - - -@pytest.mark.parametrize("tool,inputs", [ - ("Bash", {"command": "echo han-mission close garden-mission"}), - ("functions.spawn_agent", {"agent_type": "default"}), - ("Write", {"file_path": "state/ACTIVE", "content": "replacement"}), - ("Bash", {"command": "printf replacement > state/ACTIVE"}), - ("Bash", {"command": "python -c \"from pathlib import Path; Path('state/ACTIVE').write_text('replacement')\""}), -]) -def test_actual_guard_blocks_worker_marker_nested_agent_and_state_write(project, monkeypatch, tool, inputs): - data = context(project, monkeypatch) - payload = hooks.normalize_payload({ - "han_runtime": "codex", "hook_event_name": "PreToolUse", "session_id": "codex-child", - "cwd": str(project.root), "tool_name": tool, "tool_input": inputs, - }) - assert payload["session_id"] == data["session"] - assert payload["han_hermes_worker"]["role"] == "dev-small" - outcome = subagents.decide(payload) if tool.endswith("spawn_agent") else mission.decide(payload) - assert outcome.deny - assert mission.read_active(str(project.root / "state")).session == "garden-owner" - - -def test_worker_uses_hermes_only_adapter_for_project_command_guard(project, monkeypatch): - context(project, monkeypatch) - payload = hooks.normalize_payload({ - "han_runtime": "codex", "hook_event_name": "PreToolUse", "session_id": "codex-child", - "cwd": str(project.root), "tool_name": "Bash", "tool_input": {"command": "forbidden-action"}, - }) - assert payload["han_runtime"] == "hermes" - assert mission.decide(payload).deny.startswith("fictional command blocked") - - -def test_worker_cannot_escape_assigned_workspace_through_cwd(project, monkeypatch): - context(project, monkeypatch) - with pytest.raises(ValueError, match="escaped"): - hooks.normalize_payload({"han_runtime": "codex", "hook_event_name": "PreToolUse", - "cwd": str(project.root.parent)}) - - -def test_worker_filesystem_case_alias_keeps_ownership_and_state_protection(project, monkeypatch): - alias = project.root.with_name(project.root.name.upper()) - if not alias.exists() or not os.path.samefile(alias, project.root): - pytest.skip("requires a case-insensitive filesystem") - context(project, monkeypatch) - normalized = hooks.normalize_payload({"han_runtime": "codex", "hook_event_name": "PreToolUse", - "cwd": str(alias), "tool_name": "Write", "tool_input": {"file_path": "STATE/ACTIVE"}}) - assert workers.worker_denial(normalized) - assert normalized["session_id"] == "garden-owner" - - -def test_worker_lock_identity_is_shared_by_filesystem_aliases(project, codex, monkeypatch): - alias = project.root.with_name(project.root.name.upper()) - if not alias.exists() or not os.path.samefile(alias, project.root): - pytest.skip("requires a case-insensitive filesystem") - locks = [] - def lock(path, name): - locks.append(path) - return contextlib.nullcontext() - monkeypatch.setattr(workers, "FileLock", lock) - delegate(project) - workers.delegate({"role": "chef:dev-small", "prompt": "Inspect the fictional garden."}, - session_id="garden-owner", cwd=str(alias)) - assert len(locks) == 2 and locks[0] == locks[1] - - -def test_each_worker_hook_revalidates_active_ownership(project, monkeypatch): - context(project, monkeypatch) - active = json.loads(project.active.read_text(encoding="utf-8")) - active["session"] = "replacement-owner" - write_json(project.active, active) - with pytest.raises(ValueError, match="ownership"): - hooks.normalize_payload({"han_runtime": "codex", "hook_event_name": "PreToolUse", - "cwd": str(project.root)}) - - -@pytest.mark.parametrize("change", ["expired", "mismatched-digest"]) -def test_hook_context_must_have_live_owner_and_matching_deployment(project, monkeypatch, change): - context(project, monkeypatch, **({"digest": "outdated"} if change == "mismatched-digest" else {})) - if change == "expired": - monkeypatch.setattr(workers, "process_alive", lambda _: False) - with pytest.raises(ValueError, match="expired|differs"): - hooks.normalize_payload({"han_runtime": "codex", "hook_event_name": "PreToolUse"}) - - -def test_actual_worker_hook_fails_closed_for_broken_context(project, monkeypatch): - record = project.root.parent / "broken-context.json" - record.write_text("{", encoding="utf-8") - monkeypatch.setenv(workers.WORKER_ENV, str(record)) - payload = {"hook_event_name": "PreToolUse", "tool_name": "Bash", - "tool_input": {"command": "echo harmless"}, "cwd": str(project.root)} - output = io.StringIO() - monkeypatch.setattr(mission.sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(payload).encode()))) - monkeypatch.setattr(mission.sys, "stdout", output) - assert mission.main("codex") == 0 - assert json.loads(output.getvalue())["hookSpecificOutput"]["permissionDecision"] == "deny" - - -def test_run_codex_passes_prompt_on_stdin_and_explicit_cwd(project, monkeypatch): - seen = [] - - class Process: - returncode = 0 - - def communicate(self, **kwargs): - seen.append(("communicate", kwargs)) - return "fictional output", "" - - def popen(*args, **kwargs): - seen.append((args, kwargs)) - return Process() - - monkeypatch.setattr(workers.subprocess, "Popen", popen) - command = workers.command_for("/fictional/codex", "dev-small", str(project.root)) - result = workers.run_codex(command, "prompt; $DATA\ntext", {"PWD": str(project.root)}, 60) - assert result.returncode == 0 and result.stdout == "fictional output" - positional, keywords = seen[0] - assert positional == (command,) - assert keywords["cwd"] == str(project.root) - assert not keywords.get("shell", False) - assert keywords["start_new_session"] == (os.name != "nt") - assert seen[1] == ("communicate", {"input": "prompt; $DATA\ntext", "timeout": 60}) - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX Hermes process group cleanup") -@pytest.mark.parametrize("cancel", [False, True]) -def test_timed_out_or_cancelled_worker_stops_its_term_ignoring_descendant(tmp_path, monkeypatch, cancel): - child = tmp_path / "child.py" - child.write_text( - "import os, signal, time\n" - "from pathlib import Path\n" - "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" - "Path('child.pid').write_text(str(os.getpid()))\n" - "while True: time.sleep(1)\n", - encoding="utf-8", - ) - parent = tmp_path / "parent.py" - parent.write_text( - "import subprocess, sys, time\n" - "subprocess.Popen([sys.executable, 'child.py'])\n" - "while True: time.sleep(1)\n", - encoding="utf-8", - ) - original_popen = subprocess.Popen - created = [] - - class CancelledProcess: - def __init__(self, process): - self.process = process - self.cancelled = False - - def __getattr__(self, name): - return getattr(self.process, name) - - def communicate(self, **kwargs): - if not self.cancelled: - self.cancelled = True - deadline = time.monotonic() + 5 - while not (tmp_path / "child.pid").exists() and time.monotonic() < deadline: - time.sleep(.01) - raise KeyboardInterrupt("fictional cancellation") - return self.process.communicate(**kwargs) - - def popen(*args, **kwargs): - process = original_popen(*args, **kwargs) - created.append(process) - return CancelledProcess(process) if cancel else process - - command = [sys.executable, str(parent), "-C", str(tmp_path)] - with monkeypatch.context() as context: - context.setattr(workers.subprocess, "Popen", popen) - with pytest.raises(KeyboardInterrupt if cancel else subprocess.TimeoutExpired): - workers.run_codex(command, "", os.environ.copy(), 1) - assert len(created) == 1 and created[0].returncode is not None - child_pid = int((tmp_path / "child.pid").read_text()) - # A killed orphan may briefly remain a zombie before init reaps it; it must - # not remain a running descendant after run_codex has returned. - status = subprocess.run(["ps", "-o", "stat=", "-p", str(child_pid)], capture_output=True, - text=True, timeout=5).stdout.strip() - assert not status or status.startswith("Z"), status - - -GUARD_SCRIPT = """ -import json, pathlib, sys, time -payload = json.load(sys.stdin) -pathlib.Path(sys.argv[1]).write_text(json.dumps(payload), encoding="utf-8") -command = (payload.get("tool_input") or {}).get("command", "") -if "sleep" in command: - time.sleep(5) -if "crash" in command: - sys.exit(3) -if "noise" in command: - print("not json") -if "deny" in command: - print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", - "permissionDecisionReason": "fictional project rule"}})) -""" - - -def guarded_project(project, tmp_path): - script = tmp_path / "project_guard.py" - script.write_text(GUARD_SCRIPT, encoding="utf-8") - seen = tmp_path / "seen.json" - argv = [sys.executable, str(script), str(seen)] - adapter = json.loads(project.adapter.read_text(encoding="utf-8")) - adapter["runtimes"] = {"hermes": {"workers": {"guardCommand": argv}}} - write_json(project.adapter, adapter) - return seen, argv - - -def worker_call(project, command): - return mission.decide({ - "han_runtime": "codex", "hook_event_name": "PreToolUse", "session_id": "codex-child", - "cwd": str(project.root), "tool_name": "Bash", "tool_input": {"command": command}, - }) - - -def test_project_guard_command_sees_owner_identity_and_can_deny(project, monkeypatch, tmp_path): - seen, argv = guarded_project(project, tmp_path) - context(project, monkeypatch, guard=argv) - assert not worker_call(project, "echo allowed").deny - payload = json.loads(seen.read_text(encoding="utf-8")) - assert (payload["session_id"], payload["agent_id"], payload["han_runtime"]) == ("garden-owner", "chef-codex-worker", "hermes") - assert payload["tool_input"] == {"command": "echo allowed"} - assert "han_hermes_worker" not in payload - assert worker_call(project, "echo deny").deny == "프로젝트 워커 가드: fictional project rule" - - -@pytest.mark.parametrize("command,reason", [("echo crash", "실패"), ("echo noise", "JSON"), ("echo sleep", "실행하지 못함")]) -def test_project_guard_failures_deny_the_worker_call(project, monkeypatch, tmp_path, command, reason): - _, argv = guarded_project(project, tmp_path) - context(project, monkeypatch, guard=argv) - monkeypatch.setattr(workers, "GUARD_TIMEOUT", 1) - assert reason in worker_call(project, command).deny - - -def test_project_guard_is_not_run_outside_hermes_workers(project, monkeypatch, tmp_path): - seen, _ = guarded_project(project, tmp_path) - assert not worker_call(project, "echo deny").deny - assert not seen.exists() - - -def test_worker_with_project_guard_still_reaches_the_role_worker(project, codex, tmp_path): - _, argv = guarded_project(project, tmp_path) - assert delegate(project)["ok"] - assert len(codex.calls) == 2 - assert all(call[4]["guard"] == argv for call in codex.calls) - - -def test_planted_adapter_cannot_drop_the_fixed_project_guard(project, monkeypatch, tmp_path): - seen, argv = guarded_project(project, tmp_path) - context(project, monkeypatch, guard=argv) - # A worker writes a nearer adapter without workers.guardCommand; the hook keeps the fixed guard. - write_json(project.root / ".hermes/orchestrator/adapter.json", {"schema": 1, "project": "planted", "paths": {"stateDir": "state"}}) - assert worker_call(project, "echo deny").deny == "프로젝트 워커 가드: fictional project rule" - assert seen.exists() - - -def test_context_without_a_fixed_guard_entry_fails_closed(project, monkeypatch): - data = context(project, monkeypatch) - data.pop("guard") - write_json(Path(os.environ[workers.WORKER_ENV]), data) - with pytest.raises(ValueError, match="update Chef"): - worker_call(project, "echo allowed") - # The hook entry turns any worker-context error into a denial. - output = io.StringIO() - payload = {"session_id": "codex-child", "cwd": str(project.root), "hook_event_name": "PreToolUse", - "tool_name": "Bash", "tool_input": {"command": "echo allowed"}} - monkeypatch.setattr(mission.sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(payload).encode()))) - monkeypatch.setattr(mission.sys, "stdout", output) - assert mission.main("codex") == 0 - assert json.loads(output.getvalue())["hookSpecificOutput"]["permissionDecision"] == "deny" diff --git a/tests/integration/hooks/test_grok_hooks.py b/tests/integration/hooks/test_grok_hooks.py deleted file mode 100644 index 3f55d2d..0000000 --- a/tests/integration/hooks/test_grok_hooks.py +++ /dev/null @@ -1,201 +0,0 @@ -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest -from chef.guards import integrity as question_integrity -from chef.guards import mission as mission_guard -from chef.runtimes import hooks as hook_runtime -from chef.runtimes import session as session_rules - -from tests.paths import PLUGIN_ROOT -from tests.transition_support import run_lifecycle_hook - - -@pytest.fixture -def project(tmp_path, monkeypatch): - for key in ("GROK_HOOK_EVENT", "GROK_SESSION_ID", "CLAUDE_PROJECT_DIR", "HAN_REPO", "HAN_GROK_INJECT_RULES"): - monkeypatch.delenv(key, raising=False) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "no-registry")) - root = tmp_path / "sample-project" - adapter = root / ".grok/orchestrator/adapter.json" - adapter.parent.mkdir(parents=True) - adapter.write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}, - "guard": {"deny": [{"pattern": "^release-tool publish$", "reason": "release blocked"}], - "coordinatorWrite": ["state/**"]}}), encoding="utf-8") - return root - - -def payload(project, command="echo ready", tool="run_terminal_command", session="owner", **fields): - return {"hookEventName": "pre_tool_use", "sessionId": session, "cwd": str(project), - "toolName": tool, "toolInput": {"command": command}, **fields} - - -def run_hook(script, value, **environment): - env = {key: value for key, value in os.environ.items() if key not in ("GROK_HOOK_EVENT", "GROK_SESSION_ID", "CLAUDE_PROJECT_DIR")} - result = run_lifecycle_hook((PLUGIN_ROOT / 'hooks') / script, value, env={**env, **environment}) - assert result.returncode == 0, result.stderr - return json.loads(result.stdout) if result.stdout else {} - - -@pytest.mark.parametrize("tool,shell,marker", [("run_terminal_command", "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", "Write-Output"), - ("Shell", "C:/Program Files/PowerShell/7/pwsh.exe", "Write-Host"), - ("run_terminal_command", "C:/Program Files/Git/bin/bash.exe", "echo")]) -def test_native_marker_lifecycle_and_init_boundary(project, tool, shell, marker): - script = PLUGIN_ROOT / "skills/mission/scripts/mission_state.py" - init = [sys.executable, "-B", str(script), "--runtime", "grok", "--project", str(project), "--mission", "garden", "init", "--tier", "M", "--goal", "Build a fictional garden"] - before = subprocess.run(init, capture_output=True, timeout=30) - assert before.returncode != 0 - def call(action, session="owner"): - value = payload(project, tool=tool, session=session, - toolInput={"command": f"{marker} han-mission {action} garden", "shell": shell}) - return run_hook("mission_guard.py", value) - assert "permissionDecision" not in call("open").get("hookSpecificOutput", {}) - active_path = project / "state/ACTIVE" - assert json.loads(active_path.read_text())["session"] == "owner" - initialized = subprocess.run(init, capture_output=True, timeout=30) - assert initialized.returncode == 0, initialized.stderr - assert (project / "state/garden/mission.md").is_file() - assert call("close", "stranger")["hookSpecificOutput"]["permissionDecision"] == "deny" - call("resume", "next-owner") - assert json.loads(active_path.read_text())["session"] == "next-owner" - call("close", "next-owner") - assert not active_path.exists() - - -def open_mission(project): - assert not mission_guard.decide(payload(project, "echo han-mission open garden"), marker_mode="execute").deny - - -def test_native_deny_command_and_unrelated_session(project): - open_mission(project) - assert mission_guard.decide(payload(project, "release-tool publish")).deny - assert not mission_guard.decide(payload(project, "release-tool publish", session="unrelated")).deny - assert mission_guard.decide(payload(project, "release-tool publish", session="child", subagentType="developer")).deny - assert mission_guard.decide(payload(project, "echo ready", toolInputTruncated=True)).deny - assert not mission_guard.decide(payload(project, "echo ready", session="unrelated", toolInputTruncated=True)).deny - - -def test_native_marker_requires_owner_and_records_transcript(project): - missing = payload(project, "echo han-mission open garden", session="") - assert "session_id" in mission_guard.decide(missing).deny - transcript = str(project / "session.json") - assert not mission_guard.decide(payload(project, "echo han-mission open garden", transcriptPath=transcript), marker_mode="execute").deny - sessions = (project / "state/garden/sessions.tsv").read_text(encoding="utf-8") - assert f"open\towner\t{transcript}" in sessions - - -@pytest.mark.parametrize("action", ["open", "resume", "close"]) -def test_subagent_cannot_change_mission_owner(project, action): - open_mission(project) - before = (project / "state/ACTIVE").read_bytes() - assert mission_guard.decide(payload(project, f"echo han-mission {action} garden", session="child", subagentType="developer")).deny - assert (project / "state/ACTIVE").read_bytes() == before - - -@pytest.mark.parametrize("tool,key", [("write", "path"), ("Write", "path"), ("search_replace", "file_path"), - ("hashline_edit", "path"), ("StrReplace", "path"), ("EditNotebook", "target_notebook")]) -def test_native_guarded_writes_and_subagent_identity(project, tool, key): - open_mission(project) - value = payload(project, tool=tool, toolInput={key: "src/garden.py", "contents": "garden = []"}) - assert mission_guard.decide(value).deny - assert mission_guard.decide({**value, "agent_id": "forged-child"}).deny - assert not mission_guard.decide({**value, "subagentType": "developer", "sessionId": "child"}).deny - question = {**value, "toolInput": {key: "state/garden/questions/ask-colors.json", "contents": "{}"}, "subagentType": "developer"} - assert "직접 쓰지 않음" in mission_guard.decide(question).deny - - -def test_grok_event_cwd_already_includes_tool_cwd(project): - open_mission(project) - value = payload(project, tool="write", toolInput={"path": "src/garden.py", "cwd": "elsewhere"}) - assert mission_guard.decide(value).deny - - -def test_native_integrity_checks_current_and_child_session_at_stop(project): - open_mission(project) - question = project / "state/garden/ask-colors.md" - question.write_text("Untracked answer", encoding="utf-8") - value = payload(project, tool="write", hookEventName="stop") - assert question_integrity.decide(value)["systemMessage"] - assert question_integrity.decide({**value, "sessionId": "child", "subagentType": "developer"})["systemMessage"] - assert question_integrity.decide({**value, "sessionId": "unrelated"}) == {} - - -def test_native_post_tool_integrity_is_ignored(project): - open_mission(project) - (project / "state/garden/ask-colors.md").write_text("Untracked fictional answer", encoding="utf-8") - value = payload(project, tool="write", hookEventName="post_tool_use") - assert question_integrity.decide(value) == {} - assert question_integrity.decide({**value, "sessionId": "child", "subagentType": "developer"}) == {} - - -def test_native_session_context_does_not_inherit_claude_rule_opt_in(project, monkeypatch): - monkeypatch.setenv("CLAUDE_PLUGIN_OPTION_INJECT_RULES", "on") - monkeypatch.setenv("GROK_HOOK_EVENT", "session_start") - value = {"hookEventName": "session_start", "sessionId": "owner", "source": "load", "transcriptPath": "C:/sessions/garden.json"} - output = session_rules.decide(value) - context = output["hookSpecificOutput"]["additionalContext"] - assert "C:/sessions/garden.json" in context - assert context == 'chef-distill 대화 기록 경로 (--transcript): "C:/sessions/garden.json"' - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_explicit_other_runtime_is_preserved(project, runtime, monkeypatch): - monkeypatch.setenv("GROK_HOOK_EVENT", "pre_tool_use") - value = hook_runtime.normalize_payload({"tool_name": "Bash", "tool_input": {"command": "echo ready", "shell": "bash"}}, runtime) - assert value["han_runtime"] == runtime - assert value["tool_name"] == "Bash" - assert hook_runtime.normalize_payload(value)["han_runtime"] == runtime - - -def test_native_matchers_cover_current_grok_contract(): - hooks = json.loads(((PLUGIN_ROOT / 'hooks') / "hooks.json").read_text(encoding="utf-8"))["hooks"] - assert set(("new", "load")).issubset(hooks["SessionStart"][0]["matcher"].split("|")) - assert "PostToolUse" not in hooks - for event in ("PreToolUse",): - assert set(("run_terminal_command", "Shell", "search_replace", "write")).issubset(hooks[event][0]["matcher"].split("|")) - - -def test_native_manifest_exposes_only_grok_skills_and_agents(): - root = PLUGIN_ROOT - manifest = json.loads((root / ".grok-plugin/plugin.json").read_text(encoding="utf-8")) - assert manifest["name"] == "chef" - assert manifest["agents"] - native_agent_root = (root / "grok/agents").resolve() - claude_agent_root = (root / "agents").resolve() - discovered = [] - for path in manifest["agents"]: - agent_dir = (root / path).resolve() - assert agent_dir == native_agent_root - assert not agent_dir.is_relative_to(claude_agent_root) - assert agent_dir.is_dir() - for agent in agent_dir.glob("*.md"): - text = agent.read_text(encoding="utf-8") - assert text.startswith("---\n") - fields = dict(line.split(": ", 1) for line in text.split("---", 2)[1].strip().splitlines()) - discovered.append(f"{manifest['name']}:{fields['name']}") - assert fields["model"] == "inherit" - assert len(discovered) == 6 - assert set(discovered) == {"chef:researcher", "chef:dev-small", "chef:dev-medium", "chef:verifier", "chef:code-reviewer", "chef:reviewer-small"} - assert len(manifest["skills"]) == 8 - assert len(set(manifest["skills"])) == 8 - for skill in manifest["skills"]: - assert skill.startswith("./grok/skills/") - assert (root / skill / "SKILL.md").is_file() - - -@pytest.mark.parametrize("source", ["new", "load"]) -@pytest.mark.parametrize("mode", ["on", "shared"]) -def test_grok_session_start_only_delivers_transcript(project, monkeypatch, source, mode): - monkeypatch.setenv("HAN_GROK_INJECT_RULES", mode) - monkeypatch.setenv("HAN_RULES_DISABLE", "1") - value = {"hookEventName": "session_start", "source": source, "transcriptPath": "C:/sessions/garden.json"} - output = session_rules.decide(value) - assert output["hookSpecificOutput"] == { - "hookEventName": "SessionStart", - "additionalContext": 'chef-distill 대화 기록 경로 (--transcript): "C:/sessions/garden.json"', - } - assert session_rules.decide({"hookEventName": "session_start", "source": source}) == {} - assert session_rules.decide({**value, "hookEventName": "subagent_start", "subagentType": "developer"}) == {} diff --git a/tests/integration/hooks/test_guard_allow_write.py b/tests/integration/hooks/test_guard_allow_write.py deleted file mode 100644 index fa4ab64..0000000 --- a/tests/integration/hooks/test_guard_allow_write.py +++ /dev/null @@ -1,132 +0,0 @@ -import json -import os -import re -import sys -from pathlib import Path - -import pytest -from chef.guards import mission as mission_guard - -from tests.paths import PLUGIN_ROOT - -CL = r"(?:^|\s)-c\s*(?:\d+|\$\{?\w+\}?)(?=\s|$)" -ADAPTER = { - "guard": { - "allow": [r"tool\.bat submit \d+ --check-only"], - "deny": [{"pattern": r"(?:^|\s)submit(?:\s|$)", "reason": "submit 금지"}], - "p4Deny": [ - {"commands": ["obliterate"], "reason": "obliterate 금지"}, - {"commands": ["shelve"], "when": r"(?:^|\s)-d\b", "reason": "shelve 삭제 금지"}, - {"commands": ["revert"], "unless": r"^(?=.*(?:^|\s)-a\b)(?=.*" + CL + ")", "reason": "revert 제한"}, - {"commands": ["edit", "add"], "unless": CL, "reason": "번호 CL 만"}, - ], - } -} - - -def reason(command, adapter=ADAPTER, problems=None): - return mission_guard.judge_command(adapter, command, "Bash", [] if problems is None else problems, "D:/p").reason - - -@pytest.mark.parametrize( - "command, expected", - [ - ("tool.bat submit 12 --check-only", ""), - ("tool.bat submit 12", "submit 금지"), - ("tool.bat submit 12 --check-only && p4 submit", "submit 금지"), - ("p4 obliterate -y //x/...", "obliterate 금지"), - ("& p4 -u me -p ssl:h:1666 obliterate //x", "obliterate 금지"), - ('"C:/Program Files/Perforce/p4.exe" obliterate //x', "obliterate 금지"), - ("p4 shelve -c 1", ""), - ("p4 shelve -d -c 1", "shelve 삭제 금지"), - ("p4 revert -a -c 12 //x/...", ""), - ("p4 revert -c 12 a.cs", "revert 제한"), - ("p4 -c ws edit -c $CL a.cs", ""), - ('p4 -c ws edit -c "$CL" a.cs', ""), - ("p4 -c ws edit a.cs", "번호 CL 만"), - ("p4 opened", ""), - ("echo obliterate", ""), - ], -) -def test_allow_list_and_p4_deny(command, expected): - assert reason(command) == expected, command - - -def test_allow_does_not_skip_p4_client_check(): - adapter = {"guard": {"allow": [r"p4 sync"], "p4Client": {"require": True}}} - assert reason("p4 sync", adapter) != "" - - -def test_bad_p4_deny_and_allow_are_reported_not_allowed(): - problems = [] - adapter = {"guard": {"allow": ["("], "p4Deny": [{"commands": []}, {"commands": "submit", "reason": "x"}]}} - assert reason("p4 submit", adapter, problems) == "x" - assert any("guard.allow" in p for p in problems) and any("commands" in p for p in problems) - - -@pytest.mark.parametrize( - "pattern, path, ok", - [ - ("_My/missions/**", "_My/missions/m1/mission.md", True), - ("_My/missions/**", "_my/MISSIONS/m1/x.md", True), - ("_My/missions/**", "Assets/a.cs", False), - ("docs/*.md", "docs/a.md", True), - ("docs/*.md", "docs/sub/a.md", False), - ("**/*.tmp", "a/b/c.tmp", True), - ("**/*.tmp", "c.tmp", True), - ], -) -def test_glob_regex(pattern, path, ok): - assert bool(mission_guard.glob_regex(pattern).fullmatch(path)) is ok - - -@pytest.fixture -def write_project(tmp_path, monkeypatch): - project = tmp_path / "proj" - state = project / "_My" / "missions" - state.mkdir(parents=True) - adapter_dir = project / ".claude" / "orchestrator" - adapter_dir.mkdir(parents=True) - adapter = {"schema": 1, "project": "T", "paths": {"vcsRoot": ".", "stateDir": "_My/missions"}, - "guard": {"coordinatorWrite": ["_My/missions/**"]}} - (adapter_dir / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - (state / "ACTIVE").write_text(json.dumps({"id": "m1", "session": "s1", "openedAt": "2026-10-26T00:00:00"}), encoding="utf-8") - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project)) - return project - - -def write(project, target, session="s1", **extra): - payload = {"tool_name": "Write", "session_id": session, "cwd": str(project), - "tool_input": {"file_path": str(target)}, "han_runtime": "claude", **extra} - return mission_guard.decide(payload) - - -def test_coordinator_write_whitelist(write_project): - p = write_project - assert write(p, p / "_My" / "missions" / "m1" / "mission.md").deny == "" - denied = write(p, p / "Assets" / "a.cs").deny - assert "Assets/a.cs" in denied and "roles.implement" in denied - assert write(p, "Assets/b.cs").deny # 상대 경로도 프로젝트 기준 - assert write(p, p.parent / "memory" / "x.md").deny == "" # 프로젝트 밖 - assert write(p, p / "Assets" / "a.cs", agent_id="a1").deny == "" # 서브에이전트 - assert write(p, p / "Assets" / "a.cs", session="s2").deny == "" # 다른 세션 - - -def test_coordinator_write_off_without_active_or_setting(write_project): - p = write_project - (p / "_My" / "missions" / "ACTIVE").unlink() - assert write(p, p / "Assets" / "a.cs").deny == "" - adapter_path = p / ".claude" / "orchestrator" / "adapter.json" - adapter = json.loads(adapter_path.read_text(encoding="utf-8")) - del adapter["guard"] - adapter_path.write_text(json.dumps(adapter), encoding="utf-8") - (p / "_My" / "missions" / "ACTIVE").write_text(json.dumps({"id": "m1", "session": "s1"}), encoding="utf-8") - assert write(p, p / "Assets" / "a.cs").deny == "" - - -def test_hooks_json_routes_write_tools_to_guard(): - hooks = json.loads(((PLUGIN_ROOT / 'hooks') / "hooks.json").read_text(encoding="utf-8"))["hooks"]["PreToolUse"] - matchers = [group["matcher"] for group in hooks for hook in group["hooks"] - if hook.get("type") == "command" and "hooks/mission_guard.py" in hook["command"]] - for tool in ("Bash", "PowerShell", "Write", "Edit", "MultiEdit", "NotebookEdit", "apply_patch", "ApplyPatch"): - assert any(re.fullmatch(matcher, tool) for matcher in matchers), tool diff --git a/tests/integration/hooks/test_guard_command_exceptions.py b/tests/integration/hooks/test_guard_command_exceptions.py deleted file mode 100644 index ebb9dc5..0000000 --- a/tests/integration/hooks/test_guard_command_exceptions.py +++ /dev/null @@ -1,83 +0,0 @@ -import unittest -from pathlib import Path - -from chef.guards import mission as mission_guard - -from tests.paths import PLUGIN_ROOT - - -class CommandExceptionTests(unittest.TestCase): - def adapter(self, exception=".*"): - return {"guard": {"deny": [{"pattern": r"\bdeliver\b", "reason": "approval required", "exceptCommand": [exception]}]}} - - def test_literal_queries_and_output(self): - commands = [ - 'grep -n "publish-tool deliver" policy.md', - "rg -n -F 'publish-tool deliver' notes.txt", - 'echo "publish-tool deliver 17"', - "Write-Output 'publish-tool deliver 17'", - r'rg -n "publish-tool deliver" C:\notes\policy.md', - ] - for tool in ("Bash", "PowerShell"): - for command in commands: - with self.subTest(tool=tool, command=command): - self.assertFalse(mission_guard.judge_command(self.adapter(), command, tool).denied) - - def test_dynamic_and_embedded_execution_stays_denied(self): - commands = [ - "publish-tool deliver 17", - "$CLI deliver 17", - "CLI=publish-tool; $CLI deliver 17", - "$CLI = 'publish-tool'; & $CLI deliver 17", - 'echo "$(publish-tool deliver 17)"', - 'echo `publish-tool deliver 17`', - "echo publish-tool deliver 17 | sh", - "echo publish-tool deliver 17 | Invoke-Expression", - "echo publish-tool deliver 17 && sh", - "echo publish-tool deliver 17; sh", - "echo publish-tool deliver 17\nsh", - "echo publish-tool deliver 17 > run.sh", - "rg --pre publish-tool deliver notes.txt", - "rg --pre=publish-tool deliver notes.txt", - r"rg deliver \--pre publish-tool", - r"rg deliver \-\-pre publish-tool", - 'python -c "import os; os.system(\\\"publish-tool deliver 17\\\")"', - "sh -c 'publish-tool deliver 17'", - "& echo publish-tool deliver 17", - r'echo %PROGRAM% deliver 17', - "echo publish-tool deliver 17 <(sh)", - "echo (publish-tool deliver 17)", - "echo 'publish-tool deliver 17'|sh", - ] - for tool in ("Bash", "PowerShell"): - for command in commands: - with self.subTest(tool=tool, command=command): - self.assertTrue(mission_guard.judge_command(self.adapter(), command, tool).denied) - - def test_full_match_is_required(self): - self.assertTrue(mission_guard.judge_command(self.adapter("deliver"), 'echo "publish-tool deliver"').denied) - - def test_rule_exception_does_not_disable_other_rules(self): - adapter = self.adapter() - adapter["guard"]["deny"].append({"pattern": "publish-tool", "reason": "separate policy"}) - self.assertEqual("separate policy", mission_guard.judge_command(adapter, 'echo "publish-tool deliver"').reason) - - def test_existing_fragment_exceptions_remain_compatible(self): - adapter = self.adapter() - rule = adapter["guard"]["deny"][0] - rule.pop("exceptCommand") - rule["except"] = [r'echo "publish-tool deliver"'] - self.assertFalse(mission_guard.judge_command(adapter, 'echo "publish-tool deliver"').denied) - - def test_invalid_command_exception_is_not_applied(self): - for value in (".*", ["["], [1]): - with self.subTest(value=value): - adapter = self.adapter() - adapter["guard"]["deny"][0]["exceptCommand"] = value - problems = [] - self.assertTrue(mission_guard.judge_command(adapter, 'echo "publish-tool deliver"', problems=problems).denied) - self.assertTrue(any("exceptCommand" in problem for problem in problems)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/integration/hooks/test_guard_corpus.py b/tests/integration/hooks/test_guard_corpus.py new file mode 100644 index 0000000..ca871a2 --- /dev/null +++ b/tests/integration/hooks/test_guard_corpus.py @@ -0,0 +1,18 @@ +"""Every listed guard command is judged. The list lives in the fixture file.""" +import json + +from tests.support import SAMPLE_ADAPTER, command_reason, each_guard_command, load_guard_commands + + +def test_guard_corpus_runs_every_listed_command(): + adapter = json.loads(SAMPLE_ADAPTER.read_text(encoding="utf-8")) + missed = [] + seen = 0 + for name, tool, expect_deny, command in each_guard_command(): + seen += 1 + denied = command_reason(adapter, command, tool) != "" + if denied != expect_deny: + missed.append(f"{name}: {command!r}") + expected = sum(len(commands) for commands in load_guard_commands().values()) + assert seen == expected + assert missed == [] diff --git a/tests/integration/hooks/test_mission_entry.py b/tests/integration/hooks/test_mission_entry.py deleted file mode 100644 index e04625e..0000000 --- a/tests/integration/hooks/test_mission_entry.py +++ /dev/null @@ -1,787 +0,0 @@ -import json -import os -import socket -import sys -from pathlib import Path -from types import SimpleNamespace - -import pytest -from chef.cli import mission_entry as mission_entry -from chef.guards import mission as mission_guard -from chef.guards.slot_binding import write_slot_binding - -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture -def project(tmp_path, monkeypatch): - root = tmp_path / "workspace" - root.mkdir() - registry = tmp_path / "registry" - registry.mkdir() - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - script = tmp_path / "extension.py" - script.write_text("import json,sys\nrequest=json.load(sys.stdin)\nprint(json.dumps({'schema':1,'action':'continue'}))\n", encoding="utf-8") - adapter = root / ".claude/orchestrator/adapter.json" - adapter.parent.mkdir(parents=True) - adapter.write_text(json.dumps({"schema": 1, "paths": {"stateDir": ".missions"}})) - return {"root": root, "registry": registry, "script": script, "adapter": adapter} - - -def register(project, **extra): - event = {"id": "sample", "roots": [str(project["root"])], "trusted": True, - "command": [sys.executable, str(project["script"])], "watchFiles": [str(project["script"])], **extra} - path = project["registry"] / "mission-entry.json" - path.write_text(json.dumps({"schema": 1, "events": [event]}), encoding="utf-8") - return path - - -def enter(project, mode="new", session="session-a", mission="sample-mission", runtime="claude"): - return mission_entry.enter(str(project["root"]), runtime, mode, session, mission, "Create a sample tool") - - -def marker(project, action="open", mission="sample-mission", session="session-a", runtime="claude", cwd=""): - return mission_guard.decide({"tool_name": "Bash", "tool_input": {"command": f"echo han-mission {action} {mission}"}, - "cwd": cwd or str(project["root"]), "session_id": session, "han_runtime": runtime}, marker_mode="execute") - - -def test_unregistered_existing_marker_compatibility(project): - result = enter(project) - assert result["action"] == "continue" and "receipt" not in result - assert not marker(project).deny - - -def test_registered_missing_adapter_rejects_direct_marker(project): - project["adapter"].unlink() - register(project) - assert marker(project).deny - assert not (project["root"] / ".missions/ACTIVE").exists() - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_entry_receipt_all_runtime_markers(project, runtime): - register(project) - result = enter(project, runtime=runtime) - assert Path(result["receipt"]).is_file() - assert not marker(project, runtime=runtime).deny - active = mission_guard.read_active(str(project["root"] / ".missions")) - assert active.session == "session-a" and active.runtime == runtime - - -def test_profile_receipt(project, tmp_path, monkeypatch): - gateway_home = tmp_path / "home" - profile_home = gateway_home / "profiles" / "elm" - profile_registry = profile_home / "chef" / "adapters" - profile_registry.mkdir(parents=True) - monkeypatch.delenv("HAN_ADAPTERS_DIR") - monkeypatch.setenv("HERMES_HOME", str(gateway_home)) - monkeypatch.setitem(sys.modules, "hermes_constants", SimpleNamespace(get_hermes_home=lambda: profile_home)) - write_slot_binding(str(project["root"]), {"registry": str(project["registry"])}) - registration = register({**project, "registry": profile_registry}) - - assert marker(project, runtime="hermes").deny - assert not (project["root"] / ".missions/ACTIVE").exists() - result = enter(project, runtime="hermes") - assert Path(result["receipt"]).is_relative_to(registration.parent) - assert not marker(project, runtime="hermes").deny - - -def test_bootstrap_adapter_before_discovery(project): - project["adapter"].unlink() - project["script"].write_text( - "import json,pathlib,sys\nrequest=json.load(sys.stdin)\n" - "path=pathlib.Path(request['cwd'])/'.claude/orchestrator/adapter.json'\n" - "path.write_text(json.dumps({'schema':1,'paths':{'stateDir':'.missions'}}))\n" - "print(json.dumps({'schema':1,'action':'continue','project':request['cwd'],'adapter':str(path)}))\n") - register(project) - assert enter(project)["action"] == "continue" - assert not marker(project).deny - - -@pytest.mark.parametrize("change", ["session", "mission", "runtime", "cwd", "stale", "source", "config", "adapter", "local", "route"]) -def test_receipt_binds_invocation_and_inputs(project, change): - registration = register(project) - result = enter(project) - kwargs = {} - if change == "session": - kwargs["session"] = "different-session" - elif change == "mission": - kwargs["mission"] = "different-mission" - elif change == "runtime": - kwargs["runtime"] = "codex" - elif change == "cwd": - child = project["root"] / "child" - child.mkdir() - kwargs["cwd"] = str(child) - elif change == "stale": - receipt = json.loads(Path(result["receipt"]).read_text()) - receipt["createdAt"] -= 601 - Path(result["receipt"]).write_text(json.dumps(receipt)) - elif change == "source": - with project["script"].open("a") as stream: - stream.write("\nprint('changed')\n") - elif change == "config": - data = json.loads(registration.read_text()) - data["events"][0]["timeoutSeconds"] = 30 - registration.write_text(json.dumps(data)) - elif change == "adapter": - data = json.loads(project["adapter"].read_text()) - data["project"] = "fictional-workspace" - project["adapter"].write_text(json.dumps(data)) - elif change == "local": - project["adapter"].with_name("local.json").write_text(json.dumps({"project": "fictional-workspace"})) - elif change == "route": - project["adapter"].unlink() - outcome = marker(project, **kwargs) - assert outcome.deny - assert not (project["root"] / ".missions/ACTIVE").exists() - - -def test_resume_requires_separate_receipt_and_preserves_active_until_marker(project): - register(project) - enter(project) - assert not marker(project).deny - active = (project["root"] / ".missions/ACTIVE").read_bytes() - assert marker(project, action="resume").deny - enter(project, mode="resume") - assert (project["root"] / ".missions/ACTIVE").read_bytes() == active - assert not marker(project, action="resume").deny - - -def test_registered_resume_rejects_another_session_before_callback(project, monkeypatch): - register(project) - enter(project) - assert not marker(project).deny - original = (project["root"] / ".missions/ACTIVE").read_bytes() - monkeypatch.setattr(mission_entry, "execute_event", lambda *_: pytest.fail("callback ran for another session")) - with pytest.raises(mission_entry.EntryError, match="preserve the ACTIVE session"): - enter(project, mode="resume", session="session-b") - assert (project["root"] / ".missions/ACTIVE").read_bytes() == original - - -def test_registered_resume_guard_rejects_another_session_with_matching_receipt_snapshot(project): - register(project) - enter(project) - assert not marker(project).deny - result = enter(project, mode="resume") - data = json.loads(Path(result["receipt"]).read_text()) - data["binding"]["sessionId"] = "session-b" - selected = mission_entry.registration(str(project["root"]), "claude") - other_receipt = mission_entry.receipt_path(selected, data["binding"]) - Path(other_receipt).write_text(json.dumps(data)) - outcome = marker(project, action="resume", session="session-b") - assert "preserve the ACTIVE session" in outcome.deny - assert mission_guard.read_active(str(project["root"] / ".missions")).session == "session-a" - - -def test_unregistered_resume_retains_legacy_session_handoff(project): - assert not marker(project).deny - result = enter(project, mode="resume", session="session-b") - assert result["action"] == "continue" and "receipt" not in result - assert not marker(project, action="resume", session="session-b").deny - assert mission_guard.read_active(str(project["root"] / ".missions")).session == "session-b" - - -def test_registration_only_applies_to_matching_root(project, tmp_path): - register(project, roots=[str(tmp_path / "somewhere-else")]) - assert not marker(project).deny - - -@pytest.mark.parametrize("extra", [{"trusted": False}, {"command": "python extension.py"}, {"timeoutSeconds": 0}, {"watchFiles": []}]) -def test_invalid_or_untrusted_registration_fails_closed(project, extra): - register(project, **extra) - with pytest.raises(mission_entry.EntryError): - enter(project) - assert marker(project).deny - - -@pytest.mark.parametrize("body", ["raise SystemExit(7)", "print('not-json')", "print('{}')", "print('{\"schema\":1,\"action\":\"unknown\"}')"]) -def test_callback_failure_never_opens_active(project, body): - project["script"].write_text(body) - register(project) - with pytest.raises(mission_entry.EntryError): - enter(project) - assert not (project["root"] / ".missions/ACTIVE").exists() - assert not list(project["registry"].rglob("mission-entry-receipts/*.json")) - - -def test_callback_timeout(project): - project["script"].write_text("import time\ntime.sleep(5)\n") - register(project, timeoutSeconds=1) - with pytest.raises(mission_entry.EntryError, match="timed out"): - enter(project) - - -def test_failed_callback_removes_previous_receipt(project, monkeypatch): - register(project) - result = enter(project) - monkeypatch.setattr(mission_entry, "execute_event", lambda *_: (_ for _ in ()).throw(mission_entry.EntryError("failed"))) - with pytest.raises(mission_entry.EntryError): - enter(project) - assert not Path(result["receipt"]).exists() - - -def test_needs_input_returns_without_receipt(project): - project["script"].write_text("print('{\"schema\":1,\"action\":\"needs-input\",\"message\":\"Choose an option\"}')") - register(project) - assert enter(project) == {"schema": 1, "action": "needs-input", "message": "Choose an option"} - assert marker(project).deny - - -def test_continue_cannot_override_discovered_adapter(project, tmp_path): - other = tmp_path / "unregistered.json" - other.write_text(project["adapter"].read_text()) - project["script"].write_text(f"import json\nprint(json.dumps({{'schema':1,'action':'continue','adapter':{str(other)!r}}}))") - register(project) - with pytest.raises(mission_entry.EntryError, match="disagrees"): - enter(project) - - -def test_continue_must_remain_in_allowed_roots(project, tmp_path): - register(project, allowedRoots=[str(tmp_path / "different")]) - with pytest.raises(mission_entry.EntryError, match="allowedRoots"): - enter(project) - - -def test_guard_never_executes_callback(project, monkeypatch): - register(project) - enter(project) - monkeypatch.setattr(mission_entry.subprocess, "run", lambda *_args, **_kwargs: pytest.fail("hook ran an external command")) - assert not marker(project).deny - - -def slot_setup(project, tmp_path): - from chef.slots import commands as slots - - slot_root = tmp_path / "slots" - slot = slot_root / "a" - slot.mkdir(parents=True) - data = json.loads(project["adapter"].read_text()) - data["slots"] = {"enabled": True, "root": str(slot_root), "client": "sample_{name}", "names": ["a"], "prepare": []} - project["adapter"].write_text(json.dumps(data)) - registry = [{"adapter": "sample", "roots": [str(slot)]}] - (project["registry"] / "projects.json").write_text(json.dumps(registry)) - target = project["registry"] / "sample/adapter.json" - target.parent.mkdir() - target.write_text(json.dumps({**data, "vars": {"main": str(project["root"])}})) - located = mission_guard.Located(str(project["root"]), str(project["adapter"])) - config = slots.Config(located, data) - slots.Rows(config.rows_path).upsert("a", path=str(slot), client="sample_a", created="", synced="", state="ready") - return slots, config, slot - - -def delegate_script(project): - project["script"].write_text("import json\nprint(json.dumps(" + repr({"schema": 1, "action": "delegate", "project": str(project["root"]), "slot": "a"}) + "))") - - -def test_delegate_runs_canonical_before_run_under_lock_without_parent_active(project, tmp_path, monkeypatch): - slots, config, slot = slot_setup(project, tmp_path) - monkeypatch.setattr(slots, "ensure_launcher", lambda config: None) - helper = tmp_path / "prepare.py" - proof = tmp_path / "proof.json" - helper.write_text("import json,pathlib,sys\nlock=pathlib.Path(sys.argv[2])\n" - "pathlib.Path(sys.argv[1]).write_text(json.dumps({'locked':lock.is_file(),'owner':lock.read_text().split('\\t')[0]==sys.argv[3]}))\n") - data = json.loads(project["adapter"].read_text()) - data["slots"]["beforeRun"] = [{"id": "prepare", "run": f'"{sys.executable}" "{helper}" "{proof}" "{{slotLockPath}}" "{{slotLockOwnerPid}}"'}] - project["adapter"].write_text(json.dumps(data)) - delegate_script(project) - register(project, allowedRoots=[str(project["root"]), str(slot)]) - calls = [] - monkeypatch.setattr(slots, "launch_mission", lambda config, name, command: calls.append((config.runtime, name, command, Path(config.slot_lock_path(name)).is_file()))) - result = enter(project) - assert result["action"] == "delegate" and result["launched"] - assert len(calls) == 1 and calls[0][3] - assert json.loads(proof.read_text()) == {"locked": True, "owner": True} - assert not (project["root"] / ".missions/ACTIVE").exists() - assert marker(project).deny - - -def test_delegate_failure_never_launches_cli(project, tmp_path, monkeypatch): - slots, config, slot = slot_setup(project, tmp_path) - monkeypatch.setattr(slots, "ensure_launcher", lambda config: None) - data = json.loads(project["adapter"].read_text()) - data["slots"]["beforeRun"] = [{"id": "prepare", "run": f'"{sys.executable}" -c "raise SystemExit(7)"'}] - project["adapter"].write_text(json.dumps(data)) - delegate_script(project) - register(project, allowedRoots=[str(project["root"]), str(slot)]) - monkeypatch.setattr(slots, "launch_mission", lambda *_: pytest.fail("launched after failing beforeRun")) - with pytest.raises(mission_entry.EntryError, match="delegation failed"): - enter(project) - assert not (project["root"] / ".missions/ACTIVE").exists() - - -def test_delegate_target_outside_allowed_roots_is_rejected(project, tmp_path, monkeypatch): - slots, config, slot = slot_setup(project, tmp_path) - delegate_script(project) - register(project) - monkeypatch.setattr(slots, "launch_mission", lambda *_: pytest.fail("launched outside allowedRoots")) - with pytest.raises(mission_entry.EntryError, match="allowedRoots"): - enter(project) - - -def test_slot_reentry_cannot_delegate_again(project, tmp_path, monkeypatch): - slots, config, slot = slot_setup(project, tmp_path) - delegate_script(project) - register(project, roots=[str(project["root"]), str(slot)], allowedRoots=[str(project["root"]), str(slot)]) - monkeypatch.setattr(slots, "launch_mission", lambda *_: pytest.fail("reentry delegated")) - with pytest.raises(mission_entry.EntryError, match="cannot delegate"): - mission_entry.enter(str(slot), "claude", "new", "slot-session", "sample-mission", "Create a sample tool") - - -def test_slot_reentry_continues_with_separate_receipt(project, tmp_path): - slots, config, slot = slot_setup(project, tmp_path) - register(project, roots=[str(slot)], allowedRoots=[str(slot)]) - result = mission_entry.enter(str(slot), "claude", "new", "slot-session", "sample-mission") - assert result["action"] == "continue" - assert not marker(project, session="slot-session", cwd=str(slot)).deny - - -def test_unwatched_command_script_is_rejected(project, tmp_path): - unrelated = tmp_path / "unrelated.txt" - unrelated.write_text("sample") - register(project, watchFiles=[str(unrelated)]) - with pytest.raises(mission_entry.EntryError, match="watchFiles"): - enter(project) - - -def test_mixed_marker_cannot_bypass_missing_adapter_receipt(project): - project["adapter"].unlink() - register(project) - outcome = mission_guard.decide({"tool_name": "Bash", "tool_input": {"command": "echo han-mission open sample-mission; echo other"}, - "cwd": str(project["root"]), "session_id": "session-a"}) - assert outcome.deny - - -@pytest.mark.parametrize("saved_runtime", ["codex", "claude"]) -def test_delegate_resume_preserves_recorded_session_and_runtime(project, tmp_path, monkeypatch, saved_runtime): - slots, config, slot = slot_setup(project, tmp_path) - monkeypatch.setattr(slots, "ensure_launcher", lambda config: None) - session = "51c1973e-0a29-47b2-9733-660cf63fb9bc" - mission_guard.write_active(config.slot_state_dir("a"), mission_guard.Active("sample-mission", session, mission_guard.now_iso())) - original = Path(config.slot_state_dir("a"), "ACTIVE").read_bytes() - delegate_script(project) - register(project, allowedRoots=[str(project["root"]), str(slot)]) - monkeypatch.setattr(slots, "session_runtime", lambda *_args, **_kwargs: saved_runtime) - commands = [] - monkeypatch.setattr(slots, "launch_mission", lambda config, name, command: commands.append(command)) - if saved_runtime == "codex": - result = enter(project, mode="resume", runtime="codex") - assert result["action"] == "delegate" - assert len(commands) == 1 - position = commands[0].index("resume") - assert commands[0][position + 1] == session - else: - with pytest.raises(mission_entry.EntryError, match="preserve the existing runtime"): - enter(project, mode="resume", runtime="codex") - assert not commands - assert Path(config.slot_state_dir("a"), "ACTIVE").read_bytes() == original - - -def test_resume_event_cannot_rebind_adapter(project): - register(project) - enter(project) - assert not marker(project).deny - project["script"].write_text( - "import json,pathlib,sys\nrequest=json.load(sys.stdin)\n" - "path=pathlib.Path(request['cwd'])/'.claude/orchestrator/adapter.json'\n" - "data=json.loads(path.read_text())\ndata['project']='changed'\npath.write_text(json.dumps(data))\n" - "print(json.dumps({'schema':1,'action':'continue'}))\n") - register(project) - with pytest.raises(mission_entry.EntryError, match="preserve the existing adapter"): - enter(project, mode="resume") - - -def test_callback_cannot_change_registration_during_execution(project): - config = register(project) - project["script"].write_text( - f"import pathlib\npath=pathlib.Path({str(config)!r})\npath.write_text(path.read_text()+' ')\n" - "print('{\"schema\":1,\"action\":\"continue\"}')") - with pytest.raises(mission_entry.EntryError, match="changed while running"): - enter(project) - - -@pytest.mark.parametrize("relative", ["skills/mission/scripts/mission_entry.py", "codex/skills/chef-mission/scripts/mission_entry.py", "grok/scripts/mission_entry.py"]) -def test_runtime_wrapper_executes_shared_entry(project, relative): - register(project) - wrapper = Path(mission_entry.DEPLOY_ROOT) / relative - done = mission_entry.subprocess.run([sys.executable, str(wrapper), "--project", str(project["root"]), "--mode", "new", - "--session", "wrapper-session", "--mission", "sample-mission"], capture_output=True, text=True, encoding="utf-8") - assert done.returncode == 0, done.stderr - response = json.loads(done.stdout) - assert response["action"] == "continue" and Path(response["receipt"]).exists() - - -def test_damaged_existing_adapter_rejects_before_callback(project): - project["adapter"].write_text("not-json") - proof = project["root"] / "callback-ran" - project["script"].write_text(f"from pathlib import Path\nPath({str(proof)!r}).touch()\n") - register(project) - with pytest.raises(mission_guard.GuardOff, match="adapter.json"): - enter(project) - assert not proof.exists() - - -def test_receipt_rejects_changed_active_ownership(project): - register(project) - enter(project) - mission_guard.write_active(str(project["root"] / ".missions"), mission_guard.Active("sample-mission", "someone-else", mission_guard.now_iso())) - assert "ACTIVE changed" in marker(project).deny - - -@pytest.mark.parametrize("action", ["needs-input", "continue"]) -def test_wrapper_json_preserves_unicode_with_legacy_stdout_encoding(project, action): - if action == "needs-input": - result = {"schema": 1, "action": "needs-input", "message": "선택해 주세요 🔧"} - project["script"].write_text("import json\nprint(json.dumps(" + repr(result) + "))\n", encoding="utf-8") - else: - previous_root = project["root"] - project["root"] = previous_root.with_name("workspace-도구-🚀") - previous_root.rename(project["root"]) - project["adapter"] = project["root"] / ".claude/orchestrator/adapter.json" - register(project) - wrapper = Path(mission_entry.DEPLOY_ROOT) / "codex/skills/chef-mission/scripts/mission_entry.py" - done = mission_entry.subprocess.run([sys.executable, str(wrapper), "--project", str(project["root"]), "--mode", "new", - "--session", "wrapper-session", "--mission", "sample-mission"], capture_output=True, - text=True, encoding="utf-8", env={**os.environ, "PYTHONIOENCODING": "cp1252"}) - if action == "needs-input": - assert done.returncode == 3, done.stderr - assert json.loads(done.stdout) == result - else: - assert done.returncode == 0, done.stderr - response = json.loads(done.stdout) - assert Path(response["project"]) == project["root"] - assert Path(response["receipt"]).exists() - - -@pytest.mark.parametrize("mode", ["new", "resume"]) -def test_registered_existing_active_pins_runtime_for_same_session(project, mode): - register(project) - enter(project) - assert not marker(project).deny - active = mission_guard.read_active(str(project["root"] / ".missions")) - assert active.runtime == "claude" - with pytest.raises(mission_entry.EntryError, match="preserve the existing runtime: claude"): - enter(project, mode=mode, runtime="codex") - - -@pytest.mark.parametrize("mode,action", [("new", "open"), ("resume", "resume")]) -def test_registered_existing_active_guard_rejects_foreign_runtime_with_matching_receipt(project, mode, action): - register(project) - enter(project) - assert not marker(project).deny - result = enter(project, mode=mode) - receipt = json.loads(Path(result["receipt"]).read_text()) - receipt["binding"]["runtime"] = "codex" - selected = mission_entry.registration(str(project["root"]), "codex") - other = Path(mission_entry.receipt_path(selected, receipt["binding"])) - other.parent.mkdir(parents=True, exist_ok=True) - other.write_text(json.dumps(receipt)) - assert "preserve the existing runtime: claude" in marker(project, action=action, runtime="codex").deny - - -@pytest.mark.parametrize("evidence", ["codex", "unknown"]) -def test_registered_legacy_resume_uses_session_transcript_evidence(project, evidence): - session = "b47c2c20-609b-4309-8458-7463e7de1d2f" - state = project["root"] / ".missions" - mission_guard.write_active(str(state), mission_guard.Active("sample-mission", session, mission_guard.now_iso())) - register(project) - if evidence == "codex": - transcript = project["root"] / "sample-transcript.jsonl" - transcript.write_text(json.dumps({"type": "session_meta"}) + "\n") - folder = state / "sample-mission" - folder.mkdir() - (folder / "sessions.tsv").write_text("at\taction\tsession\ttranscript\nnow\topen\t" + session + "\t" + str(transcript) + "\n") - result = enter(project, mode="resume", runtime="codex", session=session) - assert result["action"] == "continue" - assert not marker(project, action="resume", runtime="codex", session=session).deny - assert mission_guard.read_active(str(state)).runtime == "codex" - else: - with pytest.raises(mission_entry.EntryError, match="cannot establish the existing runtime"): - enter(project, mode="resume", runtime="codex", session=session) - - -@pytest.fixture -def ambiguous_legacy_session(project, tmp_path, monkeypatch): - session = "44860a6b-117d-47d8-8011-2a31b9c7c6d5" - state = project["root"] / ".missions" - mission_guard.write_active(str(state), mission_guard.Active("sample-mission", session, mission_guard.now_iso())) - homes = {"codex": tmp_path / "codex", "claude": tmp_path / "claude", "grok": tmp_path / "grok"} - monkeypatch.setenv("CODEX_HOME", str(homes["codex"])) - monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(homes["claude"])) - monkeypatch.setenv("GROK_HOME", str(homes["grok"])) - register(project) - return session, state / "sample-mission", homes - - -def write_fallback(homes, runtime, session, index): - if runtime == "codex": - path = homes[runtime] / "sessions" / str(index) / f"rollout-example-{session}.jsonl" - content = {"type": "session_meta"} - elif runtime == "claude": - path = homes[runtime] / "projects" / str(index) / f"{session}.jsonl" - content = {"type": "user"} - else: - path = homes[runtime] / "sessions" / str(index) / session / "updates.jsonl" - content = {"params": {"sessionId": session, "update": {"sessionUpdate": "turn_completed"}}} - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(content) + "\n", encoding="utf-8") - return path - - -@pytest.mark.parametrize("first,second", [("codex", "claude"), ("codex", "codex"), ("claude", "claude"), ("grok", "grok")]) -def test_registered_legacy_resume_rejects_ambiguous_fallbacks_and_keeps_default_reader(project, ambiguous_legacy_session, first, second): - session, folder, homes = ambiguous_legacy_session - write_fallback(homes, first, session, 1) - write_fallback(homes, second, session, 2) - slots = mission_entry.slot_tools() - assert slots.session_runtime(str(folder), session) == first - with pytest.raises(mission_entry.EntryError, match="ambiguous"): - enter(project, mode="resume", runtime=first, session=session) - - -def test_registered_legacy_resume_keeps_explicit_session_path_priority(project, ambiguous_legacy_session): - session, folder, homes = ambiguous_legacy_session - write_fallback(homes, "codex", session, 1) - selected = write_fallback(homes, "claude", session, 2) - folder.mkdir() - (folder / "sessions.tsv").write_text("at\taction\tsession\ttranscript\nnow\topen\t" + session + "\t" + str(selected) + "\n") - result = enter(project, mode="resume", runtime="claude", session=session) - assert result["action"] == "continue" - assert not marker(project, action="resume", runtime="claude", session=session).deny - - -@pytest.fixture -def deployment_root(tmp_path, monkeypatch): - tools = mission_entry.slot_tools() - root = tmp_path / "installed-plugin" - root.mkdir() - monkeypatch.setattr(mission_entry, "slot_tools", lambda: tools) - monkeypatch.setattr(mission_entry, "DEPLOY_ROOT", str(root)) - return root - - -def test_read_only_public_watch_input_is_allowed_and_update_invalidates_receipt(project, deployment_root): - public_input = deployment_root / "roles/example.toml" - public_input.parent.mkdir() - public_input.write_text('name = "example"\n') - register(project, watchFiles=[str(project["script"]), str(public_input)]) - result = enter(project) - assert Path(result["receipt"]).exists() - public_input.write_text('name = "updated-example"\n') - assert "external source changed" in marker(project).deny - - -@pytest.mark.parametrize("input_kind", ["executable", "script", "configuration"]) -def test_command_executable_script_and_configuration_stay_outside_deployment(project, deployment_root, input_kind): - deployed = deployment_root / "external-input" - deployed.write_text("sample input") - command = [sys.executable, str(project["script"])] - if input_kind == "executable": - command[0] = str(deployed) - elif input_kind == "script": - command[1] = str(deployed) - else: - command.extend(["--config", str(deployed)]) - register(project, command=command, watchFiles=[str(project["script"]), str(deployed)]) - with pytest.raises(mission_entry.EntryError, match="outside the installed plugin"): - enter(project) - - -def test_registration_stays_outside_deployment(project, deployment_root, monkeypatch): - register(project) - monkeypatch.setattr(mission_entry, "DEPLOY_ROOT", str(project["registry"])) - with pytest.raises(mission_entry.EntryError, match="registration must be outside"): - enter(project) - - -def test_receipt_state_stays_outside_deployment(project, deployment_root, monkeypatch): - register(project) - monkeypatch.setattr(mission_entry, "DEPLOY_ROOT", str(project["registry"] / mission_entry.RECEIPTS_DIR)) - with pytest.raises(mission_entry.EntryError, match="receipts must be outside"): - enter(project) - - -def test_existing_active_new_entry_cannot_change_state_binding(project): - register(project) - enter(project) - assert not marker(project).deny - original = (project["root"] / ".missions/ACTIVE").read_bytes() - project["script"].write_text( - "import json,pathlib,sys\nrequest=json.load(sys.stdin)\n" - "path=pathlib.Path(request['cwd'])/'.claude/orchestrator/adapter.json'\n" - "data=json.loads(path.read_text())\ndata['paths']['stateDir']='.other-missions'\npath.write_text(json.dumps(data))\n" - "print(json.dumps({'schema':1,'action':'continue'}))\n") - with pytest.raises(mission_entry.EntryError, match="preserve the existing adapter"): - enter(project) - assert (project["root"] / ".missions/ACTIVE").read_bytes() == original - assert not (project["root"] / ".other-missions/ACTIVE").exists() - - -def test_guard_rechecks_adapter_state_binding_before_transition(project, monkeypatch): - register(project) - enter(project) - original = mission_entry.guard_location - calls = [] - - def checked(*args): - context = original(*args) - if not calls: - data = json.loads(project["adapter"].read_text()) - data["paths"]["stateDir"] = ".other-missions" - project["adapter"].write_text(json.dumps(data)) - calls.append(context) - return context - - monkeypatch.setattr(mission_entry, "guard_location", checked) - assert marker(project).deny - assert not (project["root"] / ".missions/ACTIVE").exists() - assert not (project["root"] / ".other-missions/ACTIVE").exists() - - -def test_registered_junction_or_symlink_cwd_cannot_bypass_receipt(project, tmp_path): - alias = tmp_path / "workspace-alias" - if os.name == "nt": - created = mission_entry.subprocess.run( - ["powershell", "-NoProfile", "-Command", "New-Item -ItemType Junction -Path $env:ENTRY_TEST_LINK -Target $env:ENTRY_TEST_TARGET | Out-Null"], - env={**os.environ, "ENTRY_TEST_LINK": str(alias), "ENTRY_TEST_TARGET": str(project["root"])}, capture_output=True) - assert created.returncode == 0, created.stderr - else: - alias.symlink_to(project["root"], target_is_directory=True) - register(project) - assert marker(project, cwd=str(alias)).deny - result = mission_entry.enter(str(alias), "claude", "new", "session-a", "sample-mission") - assert result["action"] == "continue" - assert not marker(project, cwd=str(alias)).deny - - -def listen(): - listener = socket.socket() - listener.bind(("127.0.0.1", 0)) - listener.listen(8) - listener.settimeout(10) - return listener - - -def finish_processes(processes): - for process in processes: - if process.poll() is None: - process.kill() - process.communicate(timeout=10) - - -def test_registered_new_markers_serialize_same_active_across_runtimes(project, tmp_path): - register(project) - enter(project, runtime="claude", session="session-a") - enter(project, runtime="codex", session="session-b") - harness = tmp_path / "marker_harness.py" - harness.write_text( - "import json,socket,sys\nsys.path.insert(0,sys.argv[1])\nimport mission_entry,mission_guard\n" - "payload=json.loads(sys.argv[2])\noriginal_check=mission_entry.guard_location\ncalls=0\n" - "def checked(*args):\n global calls\n result=original_check(*args)\n calls+=1\n" - " if calls==1:\n with socket.create_connection(('127.0.0.1',int(sys.argv[3]))) as gate:\n" - " gate.sendall(payload['session_id'].encode())\n gate.recv(1)\n return result\n" - "mission_entry.guard_location=checked\noriginal_marker=mission_guard.handle_marker\n" - "def transition(*args,**kwargs):\n with socket.create_connection(('127.0.0.1',int(sys.argv[4]))) as gate:\n" - " gate.sendall(payload['session_id'].encode())\n gate.recv(1)\n return original_marker(*args,**kwargs)\n" - "mission_guard.handle_marker=transition\nresult=mission_guard.decide(payload,marker_mode='execute')\nprint(json.dumps({'deny':result.deny}))\n") - processes = [] - gates = [] - with listen() as snapshot, listen() as transition: - try: - for runtime, session in [("claude", "session-a"), ("codex", "session-b")]: - payload = {"tool_name": "Bash", "tool_input": {"command": "echo han-mission open sample-mission"}, - "cwd": str(project["root"]), "session_id": session, "han_runtime": runtime} - process = mission_entry.subprocess.Popen([sys.executable, str(harness), str((PLUGIN_ROOT / "hooks")), json.dumps(payload), - str(snapshot.getsockname()[1]), str(transition.getsockname()[1])], - stdout=mission_entry.subprocess.PIPE, stderr=mission_entry.subprocess.PIPE) - processes.append(process) - gate, _ = snapshot.accept() - gate.settimeout(10) - assert gate.recv(100).decode() == session - gates.append(gate) - for gate in gates: - gate.sendall(b"x") - holder, _ = transition.accept() - holder.settimeout(10) - gates.append(holder) - winning_session = holder.recv(100).decode() - transition.settimeout(1) - with pytest.raises(TimeoutError): - extra, _ = transition.accept() - gates.append(extra) - holder.sendall(b"x") - outcomes = [] - for process in processes: - out, err = process.communicate(timeout=10) - assert process.returncode == 0, err - outcomes.append(json.loads(out)) - assert sum(bool(outcome["deny"]) for outcome in outcomes) == 1 - assert mission_guard.read_active(str(project["root"] / ".missions")).session == winning_session - finally: - for gate in gates: - gate.close() - finish_processes(processes) - - -@pytest.mark.parametrize("later", ["fail", "needs-input"]) -def test_overlapping_binding_entry_serializes_callback_and_failed_receipt_invalidation(project, tmp_path, later): - harness = tmp_path / "entry_harness.py" - harness.write_text( - "import socket,sys\nsys.path.insert(0,sys.argv[1])\nimport mission_entry\nslots=mission_entry.slot_tools()\n" - "original=slots.FileLock\nclass ObservedLock(original):\n def __enter__(self):\n" - " with socket.create_connection(('127.0.0.1',int(sys.argv[2]))) as notice:\n notice.sendall(b'attempt')\n" - " return super().__enter__()\nslots.FileLock=ObservedLock\nsys.exit(mission_entry.main(sys.argv[3:]))\n") - processes = [] - gates = [] - with listen() as notices, listen() as callbacks: - project["script"].write_text( - "import json,socket,sys\njson.load(sys.stdin)\n" - f"with socket.create_connection(('127.0.0.1',{callbacks.getsockname()[1]})) as gate:\n" - " gate.sendall(b'callback')\n decision=gate.recv(100).decode()\n" - "if decision=='fail':\n raise SystemExit(7)\n" - "result={'schema':1,'action':'continue'}\n" - "if decision=='needs-input':\n result={'schema':1,'action':'needs-input','message':'Choose an option'}\n" - "print(json.dumps(result))\n") - register(project) - args = [sys.executable, str(harness), str((PLUGIN_ROOT / "hooks")), str(notices.getsockname()[1]), - "--project", str(project["root"]), "--mode", "new", "--session", "session-a", "--mission", "sample-mission"] - try: - first = mission_entry.subprocess.Popen(args, stdout=mission_entry.subprocess.PIPE, stderr=mission_entry.subprocess.PIPE) - processes.append(first) - notice, _ = notices.accept() - assert notice.recv(100) == b"attempt" - notice.close() - initial, _ = callbacks.accept() - initial.settimeout(10) - assert initial.recv(100) == b"callback" - gates.append(initial) - second = mission_entry.subprocess.Popen(args, stdout=mission_entry.subprocess.PIPE, stderr=mission_entry.subprocess.PIPE) - processes.append(second) - notice, _ = notices.accept() - assert notice.recv(100) == b"attempt" - notice.close() - callbacks.settimeout(1) - with pytest.raises(TimeoutError): - extra, _ = callbacks.accept() - gates.append(extra) - initial.sendall(b"continue") - out, err = first.communicate(timeout=10) - assert first.returncode == 0, err - receipt = Path(json.loads(out)["receipt"]) - callbacks.settimeout(10) - following, _ = callbacks.accept() - following.settimeout(10) - gates.append(following) - assert following.recv(100) == b"callback" - following.sendall(later.encode()) - _, err = second.communicate(timeout=10) - if later == "fail": - assert second.returncode == 1, err - else: - assert second.returncode == 3, err - assert not receipt.exists() - finally: - for gate in gates: - gate.close() - finish_processes(processes) diff --git a/tests/integration/hooks/test_mission_guard.py b/tests/integration/hooks/test_mission_guard.py deleted file mode 100644 index 53983d5..0000000 --- a/tests/integration/hooks/test_mission_guard.py +++ /dev/null @@ -1,1687 +0,0 @@ -import importlib.util -import json -import os -import subprocess -import sys -import tempfile -from pathlib import Path - -import pytest -from chef.guards import adapters as guard_adapters - -from tests.paths import PLUGIN_ROOT, REPO_ROOT -from tests.transition_support import run_lifecycle_hook - -HOOKS_DIR = (PLUGIN_ROOT / 'hooks') - -from chef.guards import mission as mission_guard - -SCRIPT = HOOKS_DIR / "mission_guard.py" -CHECK_GUARD = HOOKS_DIR.parent / "skills" / "adapter-init" / "scripts" / "check_guard.py" -SAMPLE_ADAPTER = PLUGIN_ROOT.parent.parent / "tests/fixtures/sample-adapter.json" -REPO_ROOT = HOOKS_DIR.parent.parent.parent -EXAMPLE_ADAPTER = REPO_ROOT / "adapters" / "example" / "adapter.json" -EXAMPLE_CASES = REPO_ROOT / "adapters" / "example" / "guard-cases.json" -NO_REGISTRY = Path(tempfile.gettempdir()) / "han-guard-test-no-registry" -SUBMIT_RULE = {"pattern": r"^p4\s+submit\b", "reason": "submit 금지"} -SYNC_RULE = {"pattern": r"^p4\s+sync\b", "reason": "sync 금지"} -STATE = Path("_My") / "missions" -POWERSHELL = "PowerShell" -CLEARED_ENV = ("CLAUDE_PROJECT_DIR", "HAN_ADAPTERS_DIR", "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "HAN_GUARD_LOG") - -MUST_DENY = [ - "p4 submit -c 123", - "P4.EXE SUBMIT -c 1", - "CLI=Tool/VcsWrapper/vcs-wrapper.exe\n$CLI pending submit 123", - "p4 \\\n submit -c 123", - "p4 \\\r\n submit -c 123", - "p4 -c otherclient submit", - '& "p4.exe" submit -c 1', - "$P = 'p4'\n& $P submit", - '$CLI = "Tool/VcsWrapper/vcs-wrapper.exe"; $CLI pending submit 1', - "x=$(p4 submit -c 1)", - "$out = p4 submit -c 1", - "FOO=1 p4 edit a.cs", - "echo it's here; p4 submit -c 1", - "Tool/VcsWrapper/vcs-wrapper.exe pending submit 123", - "Tool/QualityGate/qualitygate.bat submit 123 --check-only", - "python Tool/cli.py submit 1", - "p4 -x list.txt edit", - "p4 -x list.txt add", - "p4 edit Foo.cs && p4 edit -c 123 Bar.cs", - "p4 revert -c 123 Foo.cs; p4 opened -a Foo.cs", - "p4 revert -a //...", - "Tool/VcsWrapper/vcs-wrapper.exe pending move-files 123 Foo.cs", - "Tool/VcsWrapper/vcs-wrapper.exe workspace delete x", - "vcs-wrapper git pull", - "p4 unshelve -s 9 -f", - "p4 unshelve -s 999 -f -c 123", - "p4 edit -c default Foo.cs", - "p4 obliterate -y //x/...", - "p4 shelve -d -c 1", - "p4 change -d 5", - "p4 changelist -f 5", - "p4 reopen -c 1 a.cs", - "p4 sync", - "p4 flush", - "p4 clean", - "p4 integrate a b", - "p4 protect", - "p4 lock a.cs", - "p4 client -d ws", - "p4 workspace -d ws", - "p4 reconcile Unity/Game/Assets/...", - "p4 rec", - "p4 open Foo.cs", - "p4 rename a b", - "p4 integ a b", - "p4 undo //x/...@1", - "p4 resolve -at", - "p4 resolve -ay", - "p4 populate //a/... //b/...", - "p4 client -i < spec.txt", - "p4 edit -c a.cs", - "p4 opened & p4 sync", - "echo $(p4 sync)", - "x=`p4 sync`", - "echo `p4 sync`", - 'echo "$(p4 sync)"', - "cat <(p4 sync)", - "p4 opened -c 1 | xargs p4 revert", - "p4 opened -c 1 | xargs -I {} p4 revert {}", - "cmd /c p4 sync", - 'cmd.exe /c "p4 sync"', - "env P4CLIENT=x p4 sync", - "nohup p4 sync", - "sudo p4 sync", - "start /b p4 sync", - 'powershell -NoProfile -Command "p4 sync"', - 'powershell.exe -NoProfile -ExecutionPolicy Bypass -c "p4 sync; echo done"', - 'pwsh -c "p4 sync"', - 'bash -c "p4 sync"', - 'echo "a\\"b"; p4 sync; echo "x\\"y"', - 'p4 -x "C:/my list.txt" edit', - "p4 -zprog=x sync", - "C:\\Perforce\\p4.exe sync", - '"C:\\Program Files\\Perforce\\p4.exe" sync', - "vcs-wrapper.exe pending submit 123", - "vcs-wrapper-tui pending submit 1", - "vcs-wrapper.exe p4 submit -c 1", - "vcs-wrapper.exe p4 -c 12 submit", - 'vcs-wrapper.exe pending new "fix submit gate"', -] - -MUST_ALLOW = [ - "p4 edit -c 123 a.cs", - "p4 edit -c $CL a.cs", - 'p4 edit -c "$CL" A.cs', - "CL=123\np4 edit -c $CL a.cs", - 'CL=123; p4 edit -c "$CL" a.cs', - "CL=5; p4 edit -c ${CL} a.cs", - "p4 -x list.txt edit -c 12", - "p4 -x C:/tmp/list.txt edit -c 123", - 'p4 -x "C:/my list.txt" edit -c 123', - "p4 add -c 99 b.cs b.cs.meta", - "p4 shelve -f -c 123", - "p4 opened -a x", - "p4 opened -c 123", - "p4 opened", - "p4 describe -s 1", - "p4 changes -s submitted -m5", - "p4 changes -s pending -c ws-yourname_Main", - "p4 revert -a -c 123", - "p4 diff -du Wiki/common/perforce-workflow.md", - 'p4 -F "%depotFile%" opened -c 123 | p4 -x - diff -du', - r"Build\project-build.bat code test GameServer", - r"Tool\QualityGate\qualitygate.bat change-description 1 --description-file x", - "p4 edit -c 123 Unity/Game/Packages/packages-lock.json", - "p4 opened -a Unity/Game/Packages/packages-lock.json", - "p4 fstat //Depot/Main/Code/Admin/x.cs", - "p4 edit -c 123 Code/GameServer/admin/Ops.cs", - "p4 add -c 123 Tool/foo-sync.md", - "p4 edit -c 1 Unity/Game/Assets/HeroArrangeSystem.Sync.cs", - "p4 add -c 123 Wiki/reports/20261015_sync_audit.md", - 'Tool/VcsWrapper/vcs-wrapper.exe pending new "Game mission m1 M1"', - 'Tool/VcsWrapper/vcs-wrapper.exe pending new "Game mission 20261015-safe-submit-fix M1"', - "Tool/VcsWrapper/vcs-wrapper.exe desc show 123", - "dotnet run --project Tool/DataTool -- D:/Work/Game_Main", - "p4 reconcile -c 123 Unity/Game/Assets/...", - "p4 rec -c 123 a.cs", - "p4 open -c 12 a.cs", - "p4 resolve -c 123 -am a.cs", - "p4 edit -c123 a.cs", - "p4 add -c99 b.cs", - "p4 revert -a -c123", - "p4 opened 2>&1", - "p4 opened &> out.txt", - "p4 opened >& out.txt", - "p4 changes -m5 &", - "p4 edit -c 1 a.{cs,meta}", - "echo ${CL}", - "cmd /c p4 opened", - "xargs echo", - "echo $(date)", -] - -POWERSHELL_DENY = [ - "p4 `\n submit -c 123", - "p4 `\r\n sync", - "dir *.cs | ForEach-Object { p4 edit $_ }", - "Get-ChildItem | % { p4 edit $_.FullName }", - "try { p4 sync } catch {}", - "try{p4 sync}catch{}", - "if ($true) { p4 submit -c 1 }", - "Write-Host (p4 sync)", - 'Write-Host "$(p4 sync)"', - "echo $(p4 sync)", - "$x = $(p4 sync)", - "$p = 'p4'; & $P sync", - "$p = 'p4'\n& $P sync", - "cd D:\\Work\\x\\\np4 sync", - '& "C:\\Program Files\\Perforce\\p4.exe" sync', - 'powershell -Command "& { p4 sync }"', - 'echo "a`"b"; p4 sync; echo "x`"y"', -] - -POWERSHELL_ALLOW = [ - "Get-ChildItem | % { p4 edit -c 123 $_.FullName }", - 'Write-Host "a (p4 sync) b"', -] - - -def make_adapter(project, deny=None, schema=1, state_dir="_My/missions"): - adapter_dir = project / ".claude" / "orchestrator" - adapter_dir.mkdir(parents=True, exist_ok=True) - adapter = { - "schema": schema, - "paths": {"stateDir": state_dir}, - "guard": {"deny": [SUBMIT_RULE] if deny is None else deny}, - } - (adapter_dir / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - - -def make_active(project, mission_id="m-001", session="s1"): - state_dir = project / STATE - state_dir.mkdir(parents=True, exist_ok=True) - if session is None: - (state_dir / "ACTIVE").write_text(mission_id + "\n", encoding="utf-8") - return - data = {"id": mission_id, "session": session, "openedAt": "2026-10-15T09:00:00+09:00"} - (state_dir / "ACTIVE").write_text(json.dumps(data), encoding="utf-8") - - -def make_corrupt_active(project): - state_dir = project / STATE - state_dir.mkdir(parents=True, exist_ok=True) - (state_dir / "ACTIVE").write_text('{"id": "m-1", "sess', encoding="utf-8") - return state_dir / "ACTIVE" - - -def read_active(project): - return json.loads((project / STATE / "ACTIVE").read_text(encoding="utf-8")) - - -def make_registry(folder, entries, adapters=None): - folder.mkdir(parents=True, exist_ok=True) - (folder / "projects.json").write_text(json.dumps(entries), encoding="utf-8") - for name, deny in (adapters if adapters is not None else {"example": [SUBMIT_RULE]}).items(): - (folder / name).mkdir(exist_ok=True) - adapter = {"schema": 1, "paths": {"stateDir": "_My/missions"}, "guard": {"deny": deny}} - (folder / name / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - return folder - - -def run_raw(stdin, env_project=None, cwd=None, env=None, script=None): - base = {k: v for k, v in os.environ.items() if k not in CLEARED_ENV} - base["HAN_ADAPTERS_DIR"] = str(NO_REGISTRY) - base.update(env or {}) - if env_project is not None: - base["CLAUDE_PROJECT_DIR"] = str(env_project) - try: - value = json.loads(stdin) - except (ValueError, TypeError): - value = None - if isinstance(value, dict): - return run_lifecycle_hook(script or SCRIPT, value, env=base, cwd=cwd) - return subprocess.run([sys.executable, "-B", str(script or SCRIPT)], input=stdin, capture_output=True, env=base, cwd=cwd, timeout=30) - - -def run_guard(project, command, tool="Bash", session="s1", start=None, env=None, **extra): - payload = {"tool_name": tool, "tool_input": {"command": command}, "cwd": str(project), **extra} - if session is not None: - payload["session_id"] = session - result = run_raw(json.dumps(payload).encode("utf-8"), env_project=start or project, env=env) - assert result.returncode == 0 - text = result.stdout.decode("utf-8").strip() - return json.loads(text) if text else {} - - -def denial(output): - decision = output.get("hookSpecificOutput") or {} - return decision.get("permissionDecisionReason", "") if decision.get("permissionDecision") == "deny" else "" - - -def is_denied(output): - return denial(output) != "" - - -def context_of(output): - return (output.get("hookSpecificOutput") or {}).get("additionalContext", "") - - -def rule_reason(adapter, command, tool="Bash"): - verdict = mission_guard.judge_command(adapter, command, tool) - return verdict.reason if verdict.denied else "" - - -@pytest.fixture -def project(tmp_path): - return tmp_path - - -@pytest.fixture(scope="module") -def sample_adapter(): - return json.loads(SAMPLE_ADAPTER.read_text(encoding="utf-8")) - - -@pytest.mark.parametrize("command", MUST_DENY) -def test_sample_rules_deny(sample_adapter, command): - assert rule_reason(sample_adapter, command) != "", command - - -@pytest.mark.parametrize("command", MUST_ALLOW) -def test_sample_rules_allow(sample_adapter, command): - assert rule_reason(sample_adapter, command) == "", command - - -@pytest.mark.parametrize("command", POWERSHELL_DENY) -def test_sample_rules_deny_powershell(sample_adapter, command): - assert rule_reason(sample_adapter, command, POWERSHELL) != "", command - - -@pytest.mark.parametrize("command", POWERSHELL_ALLOW) -def test_sample_rules_allow_powershell(sample_adapter, command): - assert rule_reason(sample_adapter, command, POWERSHELL) == "", command - - -def test_sample_wrapper_quoted_submit_word_is_known_false_positive(sample_adapter): - assert rule_reason(sample_adapter, 'vcs-wrapper.exe pending new "fix submit-gate"') == "" - assert rule_reason(sample_adapter, 'vcs-wrapper.exe pending new "fix submit gate"') != "" - - -def test_sample_matches_example_adapter_rules(sample_adapter): - if not EXAMPLE_ADAPTER.is_file(): - pytest.skip("adapters/example/adapter.json 없음") - example = json.loads(EXAMPLE_ADAPTER.read_text(encoding="utf-8")) - assert sample_adapter["guard"] == example["guard"] - - -def test_example_regression_cases_via_check_guard(): - if not EXAMPLE_ADAPTER.is_file() or not EXAMPLE_CASES.is_file(): - pytest.skip("adapters/example 없음") - result = subprocess.run( - [sys.executable, "-B", str(CHECK_GUARD), str(EXAMPLE_ADAPTER), str(EXAMPLE_CASES)], capture_output=True, timeout=60 - ) - assert result.returncode == 0, result.stdout.decode("utf-8") - assert b"mismatches=0" in result.stdout - - -def test_fragments_join_continuations_and_split(): - assert mission_guard.command_fragments("p4\\\nsubmit -c 1") == ["p4 submit -c 1"] - assert mission_guard.command_fragments("a && b || c | d; e\nf") == list("abcdef") - - -def test_continuation_is_per_tool(): - assert mission_guard.command_fragments("p4\\\nsync", "PowerShell") == ["p4\\", "sync"] - assert mission_guard.command_fragments("p4`\nsync", "PowerShell") == ["p4 sync"] - assert mission_guard.command_fragments("p4`\nsync", "Bash") == ["p4`", "sync"] - - -def test_fragments_split_on_braces_and_single_ampersand(): - assert mission_guard.command_fragments("a & b") == ["a", "b"] - assert mission_guard.command_fragments("x { y } z") == ["x", "y", "z"] - assert mission_guard.command_fragments("a 2>&1 | b &> f >& g") == ["a 2>&1", "b &> f >& g"] - - -def test_fragments_keep_quoted_separators(): - assert mission_guard.command_fragments('echo "a; b" && c') == ['echo "a; b"', "c"] - - -def test_fragments_unclosed_quote_does_not_swallow_rest(): - assert mission_guard.command_fragments("echo it's; p4 submit") == ["echo it's", "p4 submit"] - - -def test_fragments_escaped_quote_does_not_hide_next_command(): - assert "p4 sync" in mission_guard.command_fragments('echo "a\\"b"; p4 sync; echo "x\\"y"') - assert "p4 sync" in mission_guard.command_fragments('echo "a`"b"; p4 sync; echo "x`"y"', "PowerShell") - - -def test_fragments_substitute_variables(): - assert mission_guard.command_fragments("CL=123\np4 edit -c $CL a") == ["CL=123", "p4 edit -c 123 a"] - assert mission_guard.command_fragments("$CL = 5; p4 edit -c ${CL} a")[-1] == "p4 edit -c 5 a" - assert mission_guard.command_fragments('$env:CL="7"; p4 edit -c "$env:CL" a')[-1] == "p4 edit -c 7 a" - - -def test_powershell_variables_ignore_case(): - assert "p4 sync" in mission_guard.command_fragments("$p = 'p4'; & $P sync", "PowerShell") - assert "$P sync" in mission_guard.command_fragments("$p = 'p4'; & $P sync", "Bash") - - -def test_fragments_add_substitution_bodies(): - assert "p4 sync" in mission_guard.command_fragments("echo $(p4 sync) tail") - assert "p4 sync" in mission_guard.command_fragments("echo `p4 sync` tail") - assert "p4 sync" in mission_guard.command_fragments("echo $(echo $(p4 sync))") - assert "p4 sync" in mission_guard.command_fragments("echo $(p4 sync)", "PowerShell") - assert "p4 sync" in mission_guard.command_fragments("Write-Host (p4 sync)", "PowerShell") - - -def test_fragments_peel_wrappers_recursively(): - assert "p4 sync" in mission_guard.command_fragments("sudo env A=1 nohup p4 sync") - assert "p4 sync" in mission_guard.command_fragments('cmd /c "echo a && p4 sync"') - assert "p4 sync" in mission_guard.command_fragments('powershell -NoProfile -c "p4 sync"') - - -def test_registry_root_matching(): - assert mission_guard.root_matches("D:\\Work\\Game_Main", "d:/work/game_main") - assert mission_guard.root_matches("D:/Work/slots/s1", "D:/Work/slots/*") - assert not mission_guard.root_matches("D:/Work/slots/s1/a", "D:/Work/slots/*") - assert not mission_guard.root_matches("D:/Work/slots", "D:/Work/slots/*") - assert mission_guard.root_matches("D:/Work/slots/s1/", "D:/Work/slots/s?") - - -def test_no_adapter_no_output(project): - assert run_guard(project, "p4 submit -c 123") == {} - - -def test_no_active_passes(project): - make_adapter(project) - assert run_guard(project, "p4 submit -c 123") == {} - - -def test_same_session_denies_with_mission_id(project): - make_adapter(project) - make_active(project, "m-042", session="s1") - output = run_guard(project, "p4 submit -c 123", session="s1") - assert "m-042" in denial(output) - - -def test_other_session_is_quiet_and_not_denied(project): - make_adapter(project) - make_active(project, "m-042", session="s1") - assert run_guard(project, "p4 submit -c 123", session="s2") == {} - - -def test_legacy_active_does_not_claim_any_session(project): - make_adapter(project) - make_active(project, "m-042", session=None) - assert run_guard(project, "p4 submit -c 1", session="s1") == {} - assert run_guard(project, "p4 submit -c 1", session="other") == {} - - -def test_subagent_follows_its_parent_session_id(project): - make_adapter(project) - make_active(project, "m-042", session="s1") - assert is_denied(run_guard(project, "p4 submit -c 1", session="s1", agent_id="agent-1")) - assert not is_denied(run_guard(project, "p4 submit -c 1", session="s2", agent_id="agent-1")) - - -def test_missing_session_id_does_not_claim_mission(project): - make_adapter(project) - make_active(project, session="s1") - assert run_guard(project, "p4 submit -c 1", session=None) == {} - - -@pytest.mark.parametrize("session", ["different", "", None]) -def test_nonparticipating_sessions_skip_command_policy_analysis(project, monkeypatch, session): - make_adapter(project) - make_active(project, session="owner") - - def unexpected_analysis(*args): - raise AssertionError("Ordinary commands must skip mission policy analysis") - - monkeypatch.setattr(mission_guard, "judge_command", unexpected_analysis) - fields = {"cwd": str(project), "session_id": session, "tool_name": "Bash", "tool_input": {"command": "p4 submit"}} - assert not mission_guard.decide(fields).deny - - -@pytest.mark.parametrize("action", ["open", "resume", "close"]) -def test_marker_requires_nonempty_session_before_changing_active(project, action): - make_adapter(project) - make_active(project, session="owner") - before = (project / STATE / "ACTIVE").read_bytes() - output = run_guard(project, f"echo han-mission {action} m-1", session=None) - assert is_denied(output) - assert (project / STATE / "ACTIVE").read_bytes() == before - - -def test_deny_output_shape(project): - make_adapter(project) - make_active(project, "m-1", session="s1") - output = run_guard(project, "p4 submit -c 1") - assert output["hookSpecificOutput"]["hookEventName"] == "PreToolUse" - assert set(output) == {"hookSpecificOutput"} - - -def test_allows_other_command(project): - make_adapter(project) - make_active(project) - assert run_guard(project, "p4 opened") == {} - - -def test_powershell_tool_is_denied(project): - make_adapter(project) - make_active(project) - assert is_denied(run_guard(project, "p4 submit -c 123", tool="PowerShell")) - - -def test_powershell_continuation_is_joined_only_for_powershell(project): - make_adapter(project, deny=[SYNC_RULE]) - make_active(project) - assert is_denied(run_guard(project, "p4 `\n sync", tool="PowerShell")) - assert is_denied(run_guard(project, "p4 \\\n sync", tool="Bash")) - assert not is_denied(run_guard(project, "p4 \\\n sync", tool="PowerShell")) - - -def test_other_tool_passes(project): - make_adapter(project) - make_active(project) - assert run_guard(project, "p4 submit -c 123", tool="Read") == {} - - -def test_multiline_command_is_checked_per_fragment(project): - make_adapter(project) - make_active(project) - assert is_denied(run_guard(project, "echo hi\np4 submit -c 1")) - - -def test_adapter_found_from_parent_folder_via_env(project): - make_adapter(project) - make_active(project) - sub = project / "a" / "b" - sub.mkdir(parents=True) - assert is_denied(run_guard(project, "p4 submit -c 1", start=sub)) - - -def test_adapter_found_from_parent_folder_via_cwd(project): - make_adapter(project) - make_active(project) - sub = project / "a" / "b" - sub.mkdir(parents=True) - payload = {"tool_name": "Bash", "tool_input": {"command": "p4 submit -c 1"}, "cwd": str(sub), "session_id": "s1"} - result = run_raw(json.dumps(payload).encode("utf-8")) - assert is_denied(json.loads(result.stdout.decode("utf-8"))) - - -def test_broken_adapter_json_turns_guard_off_with_message(project): - adapter_dir = project / ".claude" / "orchestrator" - adapter_dir.mkdir(parents=True) - (adapter_dir / "adapter.json").write_text("{not json", encoding="utf-8") - make_active(project) - output = run_guard(project, "p4 submit -c 123") - assert not is_denied(output) - assert "미션 가드 꺼짐" in output["systemMessage"] - assert "미션 가드 꺼짐" in context_of(output) - - -def test_unknown_schema_turns_guard_off_with_message(project): - make_adapter(project, schema=2) - make_active(project) - output = run_guard(project, "p4 submit -c 123") - assert not is_denied(output) - assert "미션 가드 꺼짐" in output["systemMessage"] - - -def test_missing_state_dir_turns_guard_off_with_message(project): - make_adapter(project, state_dir="") - output = run_guard(project, "p4 submit -c 123") - assert "미션 가드 꺼짐" in output["systemMessage"] - - -def test_invalid_regex_is_skipped_reported_and_later_rule_applies(project): - make_adapter(project, deny=[{"pattern": "([unclosed", "reason": "bad"}, SUBMIT_RULE]) - make_active(project) - output = run_guard(project, "p4 submit -c 123") - assert is_denied(output) - assert "잘못된 정규식" in output["systemMessage"] - assert "잘못된 정규식" in context_of(output) - - -def test_invalid_regex_is_reported_on_allowed_command_only_while_mission_active(project): - make_adapter(project, deny=[{"pattern": "([unclosed", "reason": "bad"}, SUBMIT_RULE]) - assert run_guard(project, "p4 opened") == {} - make_active(project) - output = run_guard(project, "p4 opened") - assert not is_denied(output) - assert "잘못된 정규식" in output["systemMessage"] - assert "잘못된 정규식" in context_of(output) - - -def test_rule_exception_matches_entire_fragment_and_only_its_own_rule(): - rule = {"pattern": "submit", "except": ["inspect submit"], "reason": "submit"} - adapter = {"guard": {"deny": [rule]}} - assert mission_guard.judge_command(adapter, "inspect submit").kind == "allow" - assert mission_guard.judge_command(adapter, "inspect submit extra").denied - assert mission_guard.judge_command(adapter, "rg submit extra").kind == "allow" - assert mission_guard.judge_command(adapter, "prefix rg submit").denied - adapter["guard"]["deny"].append({"pattern": "^rg", "reason": "separate rule"}) - assert mission_guard.judge_command(adapter, "rg submit").reason == "separate rule" - - -@pytest.mark.parametrize( - "command,tool", - [ - ("rg submit; p4 submit -c 1", "Bash"), - ("rg submit && p4 submit -c 1", "Bash"), - ('rg submit "$(p4 submit -c 1)"', "Bash"), - ('Write-Output "$(p4 submit -c 1)"', "PowerShell"), - ("Write-Output (p4 submit -c 1)", "PowerShell"), - ("cmd /c p4 submit -c 1", "Bash"), - ("$p='p4'; & $p submit -c 1", "PowerShell"), - ], -) -def test_rule_exception_leaves_other_fragments_checked(command, tool): - adapter = {"guard": {"deny": [{"pattern": "submit", "except": ["rg.*", "Write-Output.*"]}]}} - assert mission_guard.judge_command(adapter, command, tool).denied - - -@pytest.mark.parametrize("exceptions", [None, "rg submit", {}, [None], [1], ["rg submit", 1], ["rg submit", "["]]) -def test_invalid_rule_exceptions_do_not_grant_allowance(project, exceptions): - make_adapter(project, deny=[{"pattern": "submit", "except": exceptions}]) - make_active(project) - output = run_guard(project, "inspect submit") - assert is_denied(output) - assert "guard.deny.except" in output["systemMessage"] - assert "예외를 적용하지 않음" in context_of(output) - - -def test_invalid_rule_exceptions_report_on_allowed_commands(project): - make_adapter(project, deny=[{"pattern": "submit", "except": False}]) - make_active(project) - output = run_guard(project, "p4 opened") - assert not is_denied(output) - assert "guard.deny.except" in output["systemMessage"] - - -def test_check_guard_reports_invalid_exception_without_allowing_it(tmp_path): - make_adapter(tmp_path, deny=[{"pattern": "submit", "except": ["rg submit", "["]}]) - adapter = tmp_path / ".claude" / "orchestrator" / "adapter.json" - cases = tmp_path / "cases.json" - cases.write_text(json.dumps([{"expect": "deny", "command": "inspect submit"}]), encoding="utf-8") - mismatches, errors, problems = load_check_guard().evaluate(str(adapter), str(cases)) - assert (mismatches, errors) == ([], []) - assert len(problems) == 1 - result = run_check_guard_cli(str(adapter), str(cases)) - assert result.returncode == 1 - assert "guard.deny.except" in result.stdout.decode("utf-8") - - -def test_garbage_stdin_does_not_block(project): - result = run_raw(b"not json") - assert result.returncode == 0 - output = json.loads(result.stdout.decode("utf-8")) - assert "미션 가드 꺼짐" in output["systemMessage"] - assert not is_denied(output) - - -def test_output_is_ascii_json_that_round_trips_korean(project): - make_adapter(project) - make_active(project) - result = run_raw( - json.dumps( - {"tool_name": "Bash", "tool_input": {"command": "p4 submit"}, "cwd": str(project), "session_id": "s1"} - ).encode(), - env_project=project, - ) - result.stdout.decode("ascii") - assert "submit 금지" in denial(json.loads(result.stdout)) - - -def test_messages_are_also_additional_context(project): - make_adapter(project) - make_active(project, "m-042", session="s1") - assert run_guard(project, "p4 submit -c 123", session="s2") == {} - opened = run_guard(project, "echo han-mission resume m-042", session="s2") - assert "가드 세션 갱신" in context_of(opened) - - -def test_marker_open_creates_active_with_session(project): - make_adapter(project) - output = run_guard(project, "echo han-mission open m-1", session="s9") - assert not is_denied(output) - assert "m-1" in output["systemMessage"] - assert "가드 켜짐" in context_of(output) - active = read_active(project) - assert active["id"] == "m-1" - assert active["session"] == "s9" - assert active["openedAt"] - assert sorted(p.name for p in (project / STATE).iterdir()) == [".transitions", "ACTIVE", "ACTIVE.entry.lock.gate", "m-1"] - assert sorted(p.name for p in (project / STATE / "m-1").iterdir()) == ["sessions.tsv"] - - -def test_marker_works_with_quotes_and_powershell(project): - make_adapter(project) - assert not is_denied(run_guard(project, 'echo "han-mission open m-1"')) - assert read_active(project)["id"] == "m-1" - assert not is_denied(run_guard(project, "Write-Host han-mission close m-1", tool="PowerShell")) - assert not (project / STATE / "ACTIVE").exists() - - -def test_marker_open_same_id_rewrites(project): - make_adapter(project) - make_active(project, "m-1", session="old") - assert not is_denied(run_guard(project, "echo han-mission open m-1", session="new")) - assert read_active(project)["session"] == "new" - - -def test_marker_open_other_id_is_denied_and_keeps_active(project): - make_adapter(project) - make_active(project, "m-1", session="s1") - output = run_guard(project, "echo han-mission open m-2", session="s2") - assert "m-1" in denial(output) - assert read_active(project)["id"] == "m-1" - - -def test_marker_open_replaces_legacy_active_of_same_id(project): - make_adapter(project) - make_active(project, "m-1", session=None) - run_guard(project, "echo han-mission open m-1", session="s5") - assert read_active(project)["session"] == "s5" - - -def test_marker_resume_updates_session_and_names_previous(project): - make_adapter(project) - make_active(project, "m-1", session="old") - output = run_guard(project, "echo han-mission resume m-1", session="new") - assert not is_denied(output) - assert "이전 session: old" in output["systemMessage"] - active = read_active(project) - assert active["session"] == "new" - assert active["openedAt"] == "2026-10-15T09:00:00+09:00" - - -def read_sessions(project, mission_id="m-1"): - text = (project / STATE / mission_id / "sessions.tsv").read_text(encoding="utf-8") - return [line.split("\t") for line in text.splitlines()] - - -def test_marker_open_and_resume_append_session_rows(project): - make_adapter(project) - run_guard(project, "echo han-mission open m-1", session="s1", transcript_path="C:/t/s1.jsonl") - run_guard(project, "echo han-mission resume m-1", session="s2", transcript_path="C:/t/s2.jsonl") - rows = read_sessions(project) - assert rows[0] == ["at", "action", "session", "transcript"] - assert [row[1:] for row in rows[1:]] == [["open", "s1", "C:/t/s1.jsonl"], ["resume", "s2", "C:/t/s2.jsonl"]] - assert rows[1][0] and rows[2][0] - - -def test_marker_session_row_without_transcript_has_empty_value(project): - make_adapter(project) - run_guard(project, "echo han-mission open m-1", session="s1") - assert read_sessions(project)[1][1:] == ["open", "s1", ""] - - -def test_denied_or_close_marker_leaves_no_session_row(project): - make_adapter(project) - make_active(project, "m-1", session="s1") - run_guard(project, "echo han-mission open m-2", session="s2") - run_guard(project, "echo han-mission close m-1", session="s1") - assert not (project / STATE / "m-2").exists() - assert not (project / STATE / "m-1" / "sessions.tsv").exists() - - -def test_marker_resume_other_or_missing_is_denied(project): - make_adapter(project) - assert is_denied(run_guard(project, "echo han-mission resume m-1")) - make_active(project, "m-1", session="s1") - assert is_denied(run_guard(project, "echo han-mission resume m-2")) - assert read_active(project)["session"] == "s1" - - -def test_marker_close_removes_active(project): - make_adapter(project) - make_active(project, "m-1") - output = run_guard(project, "echo han-mission close m-1") - assert not is_denied(output) - assert not (project / STATE / "ACTIVE").exists() - - -def test_marker_close_other_is_denied(project): - make_adapter(project) - make_active(project, "m-1") - assert is_denied(run_guard(project, "echo han-mission close m-2")) - assert (project / STATE / "ACTIVE").exists() - - -def test_marker_close_from_other_session_is_denied_until_resume(project): - make_adapter(project) - make_active(project, "m-1", session="s1") - output = run_guard(project, "echo han-mission close m-1", session="s2") - assert "resume 후 close" in denial(output) - assert "허용 파일:" not in denial(output) - assert (project / STATE / "ACTIVE").exists() - assert not is_denied(run_guard(project, "echo han-mission resume m-1", session="s2")) - assert not is_denied(run_guard(project, "echo han-mission close m-1", session="s2")) - assert not (project / STATE / "ACTIVE").exists() - - -def test_marker_close_legacy_active_from_any_session(project): - make_adapter(project) - make_active(project, "m-1", session=None) - assert not is_denied(run_guard(project, "echo han-mission close m-1", session="whatever")) - assert not (project / STATE / "ACTIVE").exists() - - -def test_marker_close_removes_allow_once_of_that_mission(project): - make_adapter(project) - make_active(project, "m-1", session="s1") - path = write_allow_once(project, "m-1", ["p4 submit -c 1"]) - other = write_allow_once(project, "m-2", ["p4 submit -c 1"]) - run_guard(project, "echo han-mission close m-1", session="s1") - assert not path.exists() - assert other.exists() - - -@pytest.mark.parametrize("bad_id", [".", "..", "a..b", "../evil", "-x"]) -def test_marker_with_bad_id_is_denied(project, bad_id): - make_adapter(project) - output = run_guard(project, f"echo han-mission open {bad_id}") - assert is_denied(output) - assert not (project / STATE / "ACTIVE").exists() - - -@pytest.mark.parametrize("good_id", ["m-1", "a.b", "20261015-safe-submit-fix", "m_1"]) -def test_marker_with_good_id_is_accepted(project, good_id): - make_adapter(project) - assert not is_denied(run_guard(project, f"echo han-mission open {good_id}")) - assert read_active(project)["id"] == good_id - - -def test_marker_mixed_with_other_fragment_is_denied_and_not_processed(project): - make_adapter(project) - make_active(project, "m-1", session="s1") - for command in ( - "echo han-mission close m-1 && p4 submit -c 1", - "echo han-mission close m-1; ls", - "ls\necho han-mission close m-1", - "cmd /c echo han-mission close m-1", - ): - output = run_guard(project, command, session="s1") - assert "단독 호출" in denial(output), command - assert read_active(project)["id"] == "m-1" - - -def test_marker_mixed_is_denied_even_without_active_mission(project): - make_adapter(project) - assert "단독 호출" in denial(run_guard(project, "echo han-mission open m-1 && ls")) - assert not (project / STATE / "ACTIVE").exists() - - -def test_guard_applies_right_after_open_in_same_session(project): - make_adapter(project) - run_guard(project, "echo han-mission open m-1", session="s1") - assert is_denied(run_guard(project, "p4 submit -c 1", session="s1")) - assert not is_denied(run_guard(project, "p4 submit -c 1", session="s2")) - - -def test_corrupt_active_does_not_classify_ordinary_sessions_as_mission(project): - make_adapter(project) - make_corrupt_active(project) - for session in ("s1", "s2", None): - assert run_guard(project, "p4 submit -c 1", session=session) == {} - assert run_guard(project, "p4 opened") == {} - - -def test_corrupt_active_does_not_consume_allow_once(project): - make_adapter(project) - make_corrupt_active(project) - permit = write_allow_once(project, "m-1", ["p4 submit -c 1"]) - before = permit.read_bytes() - assert run_guard(project, "p4 submit -c 1") == {} - assert permit.read_bytes() == before - - -def test_corrupt_active_is_removed_by_close_of_any_id(project): - make_adapter(project) - make_corrupt_active(project) - output = run_guard(project, "echo han-mission close whatever", session="s7") - assert not is_denied(output) - assert not (project / STATE / "ACTIVE").exists() - assert run_guard(project, "p4 submit -c 1") == {} - - -def test_corrupt_active_blocks_open_and_resume(project): - make_adapter(project) - path = make_corrupt_active(project) - for action in ("open", "resume"): - reason = denial(run_guard(project, f"echo han-mission {action} m-1")) - assert "ACTIVE 손상" in reason - assert "허용 파일:" not in reason - assert path.exists() - - -def test_write_active_is_atomic_when_replace_fails(project, monkeypatch): - state_dir = project / STATE - make_active(project, "m-1", session="s1") - - def fail(*args): - raise PermissionError("locked") - - monkeypatch.setattr(mission_guard.os, "replace", fail) - with pytest.raises(PermissionError): - mission_guard.write_active(str(state_dir), mission_guard.Active("m-2", "s2", "t")) - assert read_active(project)["id"] == "m-1" - assert sorted(p.name for p in state_dir.iterdir()) == ["ACTIVE"] - - -def write_allow_once(project, mission_id, lines): - folder = project / STATE / mission_id - folder.mkdir(parents=True, exist_ok=True) - path = folder / "allow-once" - path.write_text("\n".join(lines) + "\n", encoding="utf-8") - return path - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_allow_once_recovery_at_runtime_hook_boundary(project, runtime): - make_adapter(project) - make_active(project, "m-1") - command = 'p4 submit -c "123"' - script = PLUGIN_ROOT / "codex/mission_guard.py" if runtime == "codex" else SCRIPT - if runtime == "grok": - payload = {"hookEventName": "pre_tool_use", "sessionId": "s1", "cwd": str(project), - "toolName": "run_terminal_command", "toolInput": {"command": command, "shell": "pwsh"}} - else: - payload = {"session_id": "s1", "cwd": str(project), "tool_name": "PowerShell" if runtime == "codex" else "Bash", - "tool_input": {"command": command}} - - def invoke(): - result = run_raw(json.dumps(payload).encode("utf-8"), env_project=project, script=script) - assert result.returncode == 0, result.stderr.decode("utf-8") - return json.loads(result.stdout) - - permit = project / STATE / "m-1" / "allow-once" - reason = denial(invoke()) - assert reason.startswith("submit 금지 (미션 진행 중: m-1)") - assert f"허용 파일: {permit}" in reason - assert reason.endswith(f"명령:\n{command}") - assert "코디네이터가 파일 편집 도구로" in reason - assert "명시적으로 승인받았으면 재질문하지 않는다" in reason - assert "계획·리뷰 승인을 실행 승인으로 확대하지 않는다" in reason - assert "사용자에게 파일 작성이나 명령 실행을 맡기지 않는다" in reason - assert not permit.exists() - write_allow_once(project, "m-1", [command]) - assert not is_denied(invoke()) - assert not permit.exists() - assert f"허용 파일: {permit}" in denial(invoke()) - - -@pytest.mark.parametrize("command", ["p4 submit -c 123\np4 opened", "p4 submit -c 123 && p4 opened", "p4 submit -c 123; p4 opened"]) -def test_allow_once_guidance_requires_single_line_single_command(project, command): - make_adapter(project) - make_active(project, "m-1") - reason = denial(run_guard(project, command)) - assert "한 줄의 단일 명령" in reason - assert "이 호출을 그대로 등록하지 말고" in reason - assert "허용 파일:" not in reason - assert not (project / STATE / "m-1" / "allow-once").exists() - - -def test_allow_once_passes_exact_command_then_is_consumed(project): - make_adapter(project) - make_active(project, "m-1") - path = write_allow_once(project, "m-1", ["p4 submit -c 123"]) - output = run_guard(project, " p4 submit -c 123 ") - assert not is_denied(output) - assert "1회 허용 사용: p4 submit -c 123" in output["systemMessage"] - assert "1회 허용 사용" in context_of(output) - assert not path.exists() - assert sorted(p.name for p in path.parent.iterdir()) == [] - assert is_denied(run_guard(project, "p4 submit -c 123")) - - -def test_allow_once_ignores_different_command(project): - make_adapter(project) - make_active(project, "m-1") - path = write_allow_once(project, "m-1", ["p4 submit -c 123"]) - assert is_denied(run_guard(project, "p4 submit -c 124")) - assert is_denied(run_guard(project, "p4 submit -c 123 extra")) - assert path.exists() - - -def test_allow_once_consumes_only_matching_line(project): - make_adapter(project) - make_active(project, "m-1") - path = write_allow_once(project, "m-1", ["p4 submit -c 1", "p4 submit -c 2"]) - assert not is_denied(run_guard(project, "p4 submit -c 1")) - assert path.read_text(encoding="utf-8").splitlines() == ["p4 submit -c 2"] - - -def test_allow_once_of_other_mission_does_not_apply(project): - make_adapter(project) - make_active(project, "m-1") - write_allow_once(project, "m-2", ["p4 submit -c 1"]) - assert is_denied(run_guard(project, "p4 submit -c 1")) - - -def test_allow_once_unreadable_file_denies_with_path_and_keeps_file(project): - make_adapter(project) - make_active(project, "m-1") - path = project / STATE / "m-1" / "allow-once" - path.parent.mkdir(parents=True) - path.write_bytes("p4 submit -c 1\n".encode("utf-16")) - reason = denial(run_guard(project, "p4 submit -c 1")) - assert "허용 안 함" in reason - assert str(path) in reason - assert path.exists() - - -def test_allow_once_lost_race_means_not_allowed(project, monkeypatch): - path = write_allow_once(project, "m-1", ["p4 submit -c 1"]) - - def vanished(*args): - raise FileNotFoundError("claimed by another") - - monkeypatch.setattr(mission_guard.os, "replace", vanished) - assert mission_guard.consume_allow_once(str(project / STATE), "m-1", "p4 submit -c 1") is False - assert path.exists() - - -def test_allow_once_second_consumer_after_claim_is_denied(project): - state_dir = str(project / STATE) - write_allow_once(project, "m-1", ["p4 submit -c 1"]) - assert mission_guard.consume_allow_once(state_dir, "m-1", "p4 submit -c 1") is True - assert mission_guard.consume_allow_once(state_dir, "m-1", "p4 submit -c 1") is False - - -def test_exception_inside_judge_denies_instead_of_passing(project, monkeypatch): - def boom(*args): - raise FileNotFoundError("gone") - - monkeypatch.setattr(mission_guard, "consume_allow_once", boom) - outcome = mission_guard.Outcome() - active = mission_guard.Active("m-1", "s1", "") - mission_guard.judge_denied_command({"session_id": "s1"}, "p4 submit", active, str(project / STATE), "no", outcome) - assert outcome.deny - assert "allow-once" in outcome.deny - assert not outcome.messages - - -def test_unreadable_active_does_not_claim_ordinary_session(project, monkeypatch): - make_adapter(project) - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project)) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(NO_REGISTRY)) - - def boom(*args): - raise RuntimeError("disk error") - - monkeypatch.setattr(mission_guard, "read_active", boom) - payload = {"tool_name": "Bash", "tool_input": {"command": "p4 submit -c 1"}, "cwd": str(project)} - assert not mission_guard.decide(payload).deny - payload["tool_input"]["command"] = "p4 opened" - assert not mission_guard.decide(payload).deny - - -def test_registry_exact_root_match_enables_guard(project): - registry = make_registry(project / "registry", [{"adapter": "example", "roots": [str(project / "repo")]}]) - repo = project / "repo" - repo.mkdir() - env = {"HAN_ADAPTERS_DIR": str(registry)} - assert not is_denied(run_guard(repo, "echo han-mission open m-1", env=env)) - assert (repo / STATE / "ACTIVE").exists() - assert is_denied(run_guard(repo, "p4 submit -c 1", env=env)) - - -def test_registry_glob_root_and_subfolder_walk_up(project): - registry = make_registry(project / "registry", [{"adapter": "example", "roots": [str(project / "slots" / "*")]}]) - slot = project / "slots" / "s1" - nested = slot / "Unity" / "Assets" - nested.mkdir(parents=True) - env = {"HAN_ADAPTERS_DIR": str(registry)} - assert not is_denied(run_guard(nested, "echo han-mission open m-1", env=env)) - assert (slot / STATE / "ACTIVE").exists() - assert not (nested / STATE / "ACTIVE").exists() - assert is_denied(run_guard(nested, "p4 submit -c 1", env=env)) - - -def test_registry_match_respects_native_filesystem_case(project): - repo = project / "Repo" - repo.mkdir() - shouted = str(repo).upper().replace("\\", "/") - registry = make_registry(project / "registry", [{"adapter": "example", "roots": [shouted]}]) - env = {"HAN_ADAPTERS_DIR": str(registry)} - if os.path.exists(shouted) and os.path.samefile(repo, shouted): - run_guard(repo, "echo han-mission open m-1", env=env) - assert is_denied(run_guard(repo, "p4 submit -c 1", env=env)) - else: - assert not mission_guard.root_matches(str(repo), shouted) - - -def test_registry_no_match_is_silent(project): - registry = make_registry(project / "registry", [{"adapter": "example", "roots": [str(project / "other")]}]) - repo = project / "repo" - repo.mkdir() - assert run_guard(repo, "p4 submit -c 1", env={"HAN_ADAPTERS_DIR": str(registry)}) == {} - - -def test_registry_missing_is_silent(project): - repo = project / "repo" - repo.mkdir() - assert run_guard(repo, "p4 submit -c 1", env={"HAN_ADAPTERS_DIR": str(project / "nope")}) == {} - - -def test_registry_broken_json_turns_guard_off_with_message(project): - registry = project / "registry" - registry.mkdir() - (registry / "projects.json").write_text("[{broken", encoding="utf-8") - repo = project / "repo" - repo.mkdir() - output = run_guard(repo, "p4 submit -c 1", env={"HAN_ADAPTERS_DIR": str(registry)}) - assert not is_denied(output) - assert "미션 가드 꺼짐" in output["systemMessage"] - assert "registry" in context_of(output) - - -@pytest.mark.parametrize("entries", [{"adapter": "example"}, [{"adapter": "example"}], [{"adapter": "../x", "roots": []}]]) -def test_registry_wrong_shape_turns_guard_off_with_message(project, entries): - registry = make_registry(project / "registry", entries) - repo = project / "repo" - repo.mkdir() - output = run_guard(repo, "p4 submit -c 1", env={"HAN_ADAPTERS_DIR": str(registry)}) - assert "미션 가드 꺼짐" in output["systemMessage"] - - -def test_registry_matched_adapter_file_missing_turns_guard_off(project): - repo = project / "repo" - repo.mkdir() - registry = make_registry( - project / "registry", [{"adapter": "ghost", "roots": [str(repo)]}], adapters={} - ) - output = run_guard(repo, "p4 submit -c 1", env={"HAN_ADAPTERS_DIR": str(registry)}) - assert "미션 가드 꺼짐" in output["systemMessage"] - - -def test_in_repo_adapter_takes_precedence_over_registry(project): - repo = project / "repo" - repo.mkdir() - make_adapter(repo, deny=[SUBMIT_RULE]) - make_active(repo) - registry = make_registry( - project / "registry", [{"adapter": "example", "roots": [str(repo)]}], adapters={"example": [SYNC_RULE]} - ) - env = {"HAN_ADAPTERS_DIR": str(registry)} - assert is_denied(run_guard(repo, "p4 submit -c 1", env=env)) - assert not is_denied(run_guard(repo, "p4 sync", env=env)) - - -def test_in_repo_adapter_makes_broken_registry_irrelevant(project): - repo = project / "repo" - repo.mkdir() - make_adapter(repo) - make_active(repo) - registry = project / "registry" - registry.mkdir() - (registry / "projects.json").write_text("nope", encoding="utf-8") - assert is_denied(run_guard(repo, "p4 submit -c 1", env={"HAN_ADAPTERS_DIR": str(registry)})) - - -@pytest.fixture -def clean_env(monkeypatch): - for name in CLEARED_ENV: - monkeypatch.delenv(name, raising=False) - return monkeypatch - - -def test_default_registry_dir_is_marketplace_adapters_folder(clean_env): - if not (REPO_ROOT / "adapters").is_dir(): - pytest.skip("제자리 실행이 아님") - choice = mission_guard.resolve_registry() - assert Path(choice.path) == REPO_ROOT / "adapters" - assert choice.source == "in-place" - - -def test_registry_order_han_env_beats_user_config(clean_env, tmp_path): - clean_env.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "a")) - clean_env.setenv("CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", str(tmp_path / "b")) - choice = mission_guard.resolve_registry() - assert Path(choice.path) == tmp_path / "a" - assert choice.source == "env" - - -def test_registry_order_user_config_beats_in_place(clean_env, tmp_path): - clean_env.setenv("CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", str(tmp_path / "b")) - choice = mission_guard.resolve_registry() - assert Path(choice.path) == tmp_path / "b" - assert choice.source == "userConfig" - - -def test_registry_order_env_wins_even_when_folder_missing(clean_env, tmp_path): - clean_env.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "missing")) - assert mission_guard.resolve_registry().source == "env" - - -def test_registry_order_empty_variables_fall_through(clean_env): - clean_env.setenv("HAN_ADAPTERS_DIR", "") - clean_env.setenv("CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "") - assert mission_guard.resolve_registry().source in ("in-place", "none") - - -def test_registry_order_none_when_in_place_folder_absent(clean_env, tmp_path): - clean_env.setattr(guard_adapters, "in_place_adapters_dir", lambda: str(tmp_path / "nope")) - assert mission_guard.resolve_registry() == mission_guard.Registry("", "none") - assert mission_guard.registry_dir() == "" - - -def test_registry_none_is_silent_for_hook(project): - repo = project / "repo" - repo.mkdir() - shim = "import sys,mission_guard as m;from chef.guards import adapters;a=adapters;a.in_place_adapters_dir=lambda:'" + str(project / "nope").replace("\\", "/") - shim += "';sys.exit(m.main())" - payload = {"tool_name": "Bash", "tool_input": {"command": "p4 submit"}, "cwd": str(repo)} - env = {k: v for k, v in os.environ.items() if k not in CLEARED_ENV} - env["PYTHONPATH"] = str(HOOKS_DIR) - result = subprocess.run( - [sys.executable, "-B", "-c", shim], input=json.dumps(payload).encode(), capture_output=True, env=env, timeout=30 - ) - assert result.returncode == 0 - assert result.stdout == b"" - - -def test_hook_uses_user_config_variable_when_han_env_absent(project): - registry = make_registry(project / "registry", [{"adapter": "example", "roots": [str(project / "repo")]}]) - repo = project / "repo" - repo.mkdir() - env = {"CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR": str(registry), "HAN_ADAPTERS_DIR": ""} - run_guard(repo, "echo han-mission open m-1", env=env) - assert is_denied(run_guard(repo, "p4 submit -c 1", env=env)) - - -def test_hook_han_env_beats_user_config_variable(project): - wanted = make_registry(project / "wanted", [{"adapter": "example", "roots": [str(project / "repo")]}]) - other = make_registry(project / "other", []) - repo = project / "repo" - repo.mkdir() - env = {"HAN_ADAPTERS_DIR": str(wanted), "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR": str(other)} - run_guard(repo, "echo han-mission open m-1", env=env) - assert is_denied(run_guard(repo, "p4 submit -c 1", env=env)) - - -def test_log_records_registry_source_only_when_registry_is_consulted(project): - registry = make_registry(project / "registry", []) - repo = project / "repo" - repo.mkdir() - log = project / "guard.log" - run_guard(repo, "p4 submit", env={"HAN_ADAPTERS_DIR": str(registry), "HAN_GUARD_LOG": str(log)}) - entries = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] - assert len(entries) == 2 - assert entries[1] == {"registry_source": "env", "registry_dir": str(registry)} - - -def test_log_has_no_registry_line_when_in_repo_adapter_found(project): - make_adapter(project) - log = project / "guard.log" - run_guard(project, "echo hi", env={"HAN_GUARD_LOG": str(log)}) - assert len(log.read_text(encoding="utf-8").splitlines()) == 1 - - -def write_json(path, data): - path.write_text(json.dumps(data), encoding="utf-8") - - -def test_merge_local_recurses_objects_and_replaces_arrays_and_scalars(): - base = {"schema": 1, "paths": {"stateDir": "a", "keep": "k"}, "guard": {"deny": [1, 2]}, "x": 1} - local = {"paths": {"stateDir": "b"}, "guard": {"deny": [3]}, "x": {"y": 2}, "new": True} - assert mission_guard.merge_local(base, local) == { - "schema": 1, - "paths": {"stateDir": "b", "keep": "k"}, - "guard": {"deny": [3]}, - "x": {"y": 2}, - "new": True, - } - assert base["paths"]["stateDir"] == "a" - - -def test_load_adapter_without_local_returns_adapter_json(project): - path = write_adapter_file(project) - assert mission_guard.load_adapter(str(path)) == json.loads(path.read_text(encoding="utf-8")) - - -def test_load_adapter_merges_local_next_to_adapter_json(project): - path = write_adapter_file(project) - write_json(path.parent / "local.json", {"paths": {"stateDir": "elsewhere"}, "guard": {"deny": [SYNC_RULE]}}) - adapter = mission_guard.load_adapter(str(path)) - assert adapter["paths"]["stateDir"] == "elsewhere" - assert adapter["guard"]["deny"] == [SYNC_RULE] - assert adapter["schema"] == 1 - - -@pytest.mark.parametrize("runtime", ["codex", "grok"]) -def test_load_adapter_runtime_precedence_preserves_other_runtimes(project, runtime): - path = write_adapter_file(project) - adapter = json.loads(path.read_text(encoding="utf-8")) - adapter["roles"] = {"research": "base-research", "implement": "base-implement"} - adapter["stages"] = ["base"] - adapter["runtimes"] = { - "codex": {"project": "codex-base", "roles": {"research": "codex-research"}, "stages": ["codex"]}, - "grok": {"project": "grok-base", "roles": {"research": "grok-research"}, "stages": ["grok"]}, - } - write_json(path, adapter) - write_json(path.parent / "local.json", { - "project": "local", - "roles": {"implement": "local-implement"}, - "runtimes": { - runtime: {"project": f"{runtime}-local", "paths": {"stateDir": f"{runtime}-state"}}, - }, - }) - loaded = mission_guard.load_adapter(str(path), runtime=runtime) - assert loaded["project"] == f"{runtime}-local" - assert loaded["roles"] == {"research": f"{runtime}-research", "implement": "local-implement"} - assert loaded["paths"]["stateDir"] == f"{runtime}-state" - assert loaded["stages"] == [runtime] - assert loaded["guard"]["deny"] == [SUBMIT_RULE] - assert mission_guard.load_adapter(str(path), runtime="claude")["roles"] == { - "research": "base-research", "implement": "local-implement", - } - if runtime == "codex": - other = "grok" - else: - other = "codex" - assert mission_guard.load_adapter(str(path), runtime=other)["roles"]["research"] == f"{other}-research" - - -@pytest.mark.parametrize("runtime", ["codex", "grok"]) -@pytest.mark.parametrize("source", ["adapter.json", "local.json"]) -@pytest.mark.parametrize("overlay", [[], "invalid", False, None]) -def test_load_adapter_rejects_invalid_runtime_overlay(project, runtime, source, overlay): - path = write_adapter_file(project) - target = path.parent / source - body = {} - if target.exists(): - body = json.loads(target.read_text(encoding="utf-8")) - body["runtimes"] = {runtime: overlay} - write_json(target, body) - with pytest.raises(mission_guard.GuardOff, match=rf"{source} .*runtimes\.{runtime}"): - mission_guard.load_adapter(str(path), runtime=runtime) - - -@pytest.mark.parametrize("runtime", ["codex", "grok"]) -def test_load_adapter_rejects_invalid_runtime_container(project, runtime): - path = write_adapter_file(project) - write_json(path.parent / "local.json", {"runtimes": []}) - with pytest.raises(mission_guard.GuardOff, match="local.json .*runtimes"): - mission_guard.load_adapter(str(path), runtime=runtime) - - -def test_load_adapter_broken_local_uses_adapter_only_and_reports(project): - path = write_adapter_file(project) - (path.parent / "local.json").write_text("{broken", encoding="utf-8") - problems = [] - adapter = mission_guard.load_adapter(str(path), problems) - assert adapter["guard"]["deny"] == [SUBMIT_RULE] - assert len(problems) == 1 - assert "local.json 무시" in problems[0] - - -def test_load_adapter_non_object_local_is_reported(project): - path = write_adapter_file(project) - (path.parent / "local.json").write_text("[1]", encoding="utf-8") - problems = [] - assert mission_guard.load_adapter(str(path), problems)["schema"] == 1 - assert "객체가 아님" in problems[0] - - -def test_load_adapter_local_cannot_hide_a_bad_schema(project): - path = write_adapter_file(project) - write_json(path.parent / "local.json", {"schema": 2}) - with pytest.raises(mission_guard.GuardOff): - mission_guard.load_adapter(str(path)) - - -def test_hook_applies_local_deny_rules(project): - path = write_adapter_file(project) - write_json(path.parent / "local.json", {"guard": {"deny": [SYNC_RULE]}}) - make_active(project) - assert is_denied(run_guard(project, "p4 sync")) - assert not is_denied(run_guard(project, "p4 submit -c 1")) - - -def test_hook_registry_adapter_gets_local_json_too(project): - repo = project / "repo" - repo.mkdir() - registry = make_registry(project / "registry", [{"adapter": "example", "roots": [str(repo)]}]) - write_json(registry / "example" / "local.json", {"guard": {"deny": [SYNC_RULE]}}) - make_active(repo) - env = {"HAN_ADAPTERS_DIR": str(registry)} - assert is_denied(run_guard(repo, "p4 sync", env=env)) - assert not is_denied(run_guard(repo, "p4 submit -c 1", env=env)) - - -def test_hook_warns_about_broken_local_while_mission_active(project): - path = write_adapter_file(project) - (path.parent / "local.json").write_text("{broken", encoding="utf-8") - assert run_guard(project, "p4 opened") == {} - make_active(project) - output = run_guard(project, "p4 opened") - assert "local.json 무시" in output["systemMessage"] - assert "local.json 무시" in context_of(output) - assert is_denied(run_guard(project, "p4 submit -c 1")) - - -def test_diagnostic_log_records_selected_fields_only(project): - make_adapter(project) - log = project / "guard.log" - long_command = "echo " + "x" * 300 - run_guard( - project, - long_command, - session="s1", - env={"HAN_GUARD_LOG": str(log)}, - agent_id="a1", - agent_type="dev", - hook_event_name="PreToolUse", - secret="nope", - ) - lines = log.read_text(encoding="utf-8").splitlines() - assert len(lines) == 1 - entry = json.loads(lines[0]) - assert set(entry) == {"session_id", "agent_id", "agent_type", "tool_name", "cwd", "hook_event_name", "command"} - assert entry["session_id"] == "s1" - assert entry["agent_id"] == "a1" - assert entry["agent_type"] == "dev" - assert entry["tool_name"] == "Bash" - assert entry["hook_event_name"] == "PreToolUse" - assert entry["cwd"] == str(project) - assert entry["command"] == long_command[:120] - - -def test_no_log_without_env(project): - make_adapter(project) - run_guard(project, "echo hi") - assert not list(project.glob("*.log")) - - -def test_unwritable_log_does_not_break_guard(project): - make_adapter(project) - make_active(project) - output = run_guard(project, "p4 submit -c 1", env={"HAN_GUARD_LOG": str(project)}) - assert is_denied(output) - - -def load_check_guard(): - spec = importlib.util.spec_from_file_location("check_guard", CHECK_GUARD) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def write_adapter_file(folder): - make_adapter(folder) - return folder / ".claude" / "orchestrator" / "adapter.json" - - -def test_check_guard_json_cases_with_multiline_and_tool(tmp_path): - adapter = write_adapter_file(tmp_path) - cases = [ - {"expect": "deny", "command": "echo a\np4 submit -c 1"}, - {"expect": "deny", "command": "p4 \\\n submit"}, - {"expect": "deny", "command": "p4 `\n submit", "tool": "PowerShell"}, - {"expect": "allow", "command": "p4 opened"}, - ] - path = tmp_path / "cases.json" - path.write_text(json.dumps(cases), encoding="utf-8") - mismatches, errors, problems = load_check_guard().evaluate(str(adapter), str(path)) - assert (mismatches, errors, problems) == ([], [], []) - - -def test_check_guard_uses_hook_marker_judgement(tmp_path): - adapter = write_adapter_file(tmp_path) - cases = [ - {"expect": "allow", "command": "echo han-mission open m-1"}, - {"expect": "deny", "command": "echo han-mission open m-1 && ls"}, - ] - path = tmp_path / "cases.json" - path.write_text(json.dumps(cases), encoding="utf-8") - assert load_check_guard().evaluate(str(adapter), str(path)) == ([], [], []) - - -def test_check_guard_reports_bad_tool_and_mismatch(tmp_path): - adapter = write_adapter_file(tmp_path) - path = tmp_path / "cases.json" - cases = [{"expect": "allow", "command": "p4 submit"}, {"expect": "deny", "command": "x", "tool": "Zsh"}] - path.write_text(json.dumps(cases), encoding="utf-8") - mismatches, errors, _ = load_check_guard().evaluate(str(adapter), str(path)) - assert [(m[0], m[1]) for m in mismatches] == [("allow", "deny")] - assert len(errors) == 1 - - -def test_check_guard_tsv_does_not_interpret_backslash_n_and_reports_bad_lines(tmp_path): - adapter = write_adapter_file(tmp_path) - path = tmp_path / "cases.tsv" - path.write_text( - "# 주석\nallow\tp4 opened\\nsubmit\nallow\tD:\\Work\\new\\p4 opened\nno tab here\n\nbad\tp4 opened\n", - encoding="utf-8", - ) - mismatches, errors, _ = load_check_guard().evaluate(str(adapter), str(path)) - assert mismatches == [] - assert len(errors) == 2 - assert "4번째 줄" in errors[0] - assert "6번째 줄" in errors[1] - - -def test_check_guard_resolves_registry_adapter_name(tmp_path, monkeypatch): - registry = make_registry(tmp_path / "registry", [], adapters={"demo": [SUBMIT_RULE]}) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - path = tmp_path / "cases.json" - path.write_text(json.dumps([{"expect": "deny", "command": "p4 submit"}]), encoding="utf-8") - assert load_check_guard().evaluate("demo", str(path)) == ([], [], []) - - -def test_check_guard_cli_exit_code(tmp_path): - adapter = write_adapter_file(tmp_path) - path = tmp_path / "cases.json" - path.write_text(json.dumps([{"expect": "deny", "command": "p4 submit"}]), encoding="utf-8") - ok = subprocess.run([sys.executable, "-B", str(CHECK_GUARD), str(adapter), str(path)], capture_output=True) - assert ok.returncode == 0 - assert b"mismatches=0" in ok.stdout - path.write_text(json.dumps([{"expect": "allow", "command": "p4 submit"}]), encoding="utf-8") - bad = subprocess.run([sys.executable, "-B", str(CHECK_GUARD), str(adapter), str(path)], capture_output=True) - assert bad.returncode == 1 - - -def test_check_guard_runtime_flag(tmp_path): - adapter = write_adapter_file(tmp_path) - path = tmp_path / "cases.json" - path.write_text(json.dumps([{"expect": "deny", "command": "p4 submit"}]), encoding="utf-8") - ok = subprocess.run( - [sys.executable, "-B", str(CHECK_GUARD), "--runtime", "grok", str(adapter), str(path)], - capture_output=True, - ) - assert ok.returncode == 0 - assert b"mismatches=0" in ok.stdout - bad = subprocess.run([sys.executable, "-B", str(CHECK_GUARD), "--runtime", "nope"], capture_output=True) - assert bad.returncode == 2 - assert b"ERROR --runtime" in bad.stdout - - -def test_check_guard_default_cases_file_next_to_adapter(tmp_path): - adapter = write_adapter_file(tmp_path) - (adapter.parent / "guard-cases.json").write_text( - json.dumps([{"expect": "deny", "command": "p4 submit"}]), encoding="utf-8" - ) - ok = subprocess.run([sys.executable, "-B", str(CHECK_GUARD), str(adapter)], capture_output=True) - assert ok.returncode == 0 - - -def test_check_guard_doctor_reports_python_resolution(): - result = subprocess.run([sys.executable, "-B", str(CHECK_GUARD), "--doctor"], capture_output=True, timeout=60) - text = result.stdout.decode("utf-8") - assert result.returncode in (0, 1) - assert "python=" in text - if "NOT FOUND" not in text: - assert "windowsapps_path=" in text - assert "stub=" in text - - -GUARD_OFF_MARKERS = [ - "echo han-mission open m-1", - "echo han-mission resume m-1", - "echo han-mission close m-1", - 'echo "han-mission open m-1"', - "echo han-mission open m-1 && ls", -] - - -def assert_guard_off_notice(output, reason_part): - if is_denied(output): - # The replacement lifecycle CLI fails closed when discovery fails. - assert "Mission transition rejected:" in denial(output) - assert reason_part in denial(output) - return - assert not is_denied(output) - for text in (output["systemMessage"], context_of(output)): - assert "미션 가드 꺼짐: 어댑터 못 찾음" in text - assert reason_part in text - - -@pytest.mark.parametrize("command", GUARD_OFF_MARKERS) -def test_marker_without_adapter_warns_guard_off_when_registry_folder_missing(project, command): - repo = project / "repo" - repo.mkdir() - output = run_guard(repo, command, env={"HAN_ADAPTERS_DIR": str(project / "nope")}) - assert_guard_off_notice(output, "레지스트리 폴더 없음") - assert not (repo / STATE / "ACTIVE").exists() - - -def test_marker_without_adapter_warns_when_powershell(project): - repo = project / "repo" - repo.mkdir() - output = run_guard( - repo, "Write-Host han-mission open m-1", tool=POWERSHELL, env={"HAN_ADAPTERS_DIR": str(project / "nope")} - ) - assert_guard_off_notice(output, "레지스트리 폴더 없음") - - -def test_marker_without_adapter_warns_when_projects_json_missing(project): - registry = project / "registry" - registry.mkdir() - repo = project / "repo" - repo.mkdir() - output = run_guard(repo, "echo han-mission open m-1", env={"HAN_ADAPTERS_DIR": str(registry)}) - assert_guard_off_notice(output, "projects.json 없음") - - -def test_marker_without_adapter_warns_when_no_root_matches(project): - registry = make_registry(project / "registry", [{"adapter": "example", "roots": [str(project / "other")]}]) - repo = project / "repo" - repo.mkdir() - output = run_guard(repo, "echo han-mission open m-1", env={"HAN_ADAPTERS_DIR": str(registry)}) - assert_guard_off_notice(output, "맞는 항목 없음") - assert str(repo) in (output.get("systemMessage", "") + denial(output)) - - -def test_marker_without_adapter_warns_when_registry_path_unset(project): - repo = project / "repo" - repo.mkdir() - shim = "import sys,mission_guard as m;from chef.guards import adapters;a=adapters;a.in_place_adapters_dir=lambda:'" + str(project / "nope").replace("\\", "/") - shim += "';sys.exit(m.main())" - payload = { - "tool_name": "Bash", - "tool_input": {"command": "echo han-mission open m-1"}, - "cwd": str(repo), - "session_id": "s1", - } - env = {k: v for k, v in os.environ.items() if k not in CLEARED_ENV} - env["PYTHONPATH"] = str(HOOKS_DIR) - result = subprocess.run( - [sys.executable, "-B", "-c", shim], input=json.dumps(payload).encode(), capture_output=True, env=env, timeout=30 - ) - assert_guard_off_notice(json.loads(result.stdout), "레지스트리 경로 미설정") - - -def test_marker_without_start_folder_warns_guard_off(): - result = run_raw(json.dumps({"tool_name": "Bash", "tool_input": {"command": "echo han-mission open m-1"}}).encode()) - assert_guard_off_notice(json.loads(result.stdout), "시작 폴더 없음") - - -@pytest.mark.parametrize("command", ["p4 submit -c 1", "echo hello", "echo han-mission open"]) -def test_non_marker_without_adapter_stays_silent(project, command): - repo = project / "repo" - repo.mkdir() - assert run_guard(repo, command, env={"HAN_ADAPTERS_DIR": str(project / "nope")}) == {} - - -def test_marker_open_success_message_is_what_skill_checks_for(project): - make_adapter(project) - output = run_guard(project, "echo han-mission open m-7") - assert "미션 m-7 가드 켜짐" in output["systemMessage"] - assert "어댑터 못 찾음" not in output["systemMessage"] - - -def test_find_adapter_raises_with_reason_and_locate_adapter_stays_none(project, monkeypatch): - repo = project / "repo" - repo.mkdir() - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(project / "nope")) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - with pytest.raises(mission_guard.AdapterNotFound, match="레지스트리 폴더 없음"): - mission_guard.find_adapter({"cwd": str(repo)}) - assert mission_guard.locate_adapter({"cwd": str(repo)}) is None - - -def run_check_guard_cli(*args, env=None): - base = {k: v for k, v in os.environ.items() if k not in CLEARED_ENV} - base.update(env or {}) - return subprocess.run([sys.executable, "-B", str(CHECK_GUARD), *args], capture_output=True, env=base, timeout=60) - - -def test_check_guard_registry_folder_missing_is_one_line_error_not_traceback(tmp_path): - result = run_check_guard_cli("demo", env={"HAN_ADAPTERS_DIR": str(tmp_path / "nope")}) - text = result.stdout.decode("utf-8") - assert result.returncode == 3 - assert text.startswith("ERROR 읽기 실패: ") - assert "Traceback" not in result.stderr.decode("utf-8") - assert len(text.strip().splitlines()) == 1 - - -def test_check_guard_unknown_adapter_name_in_existing_registry(tmp_path): - registry = make_registry(tmp_path / "registry", [], adapters={"demo": [SUBMIT_RULE]}) - result = run_check_guard_cli("ghost", env={"HAN_ADAPTERS_DIR": str(registry)}) - assert result.returncode == 3 - assert "ghost" in result.stdout.decode("utf-8") - - -def test_check_guard_registry_unset_is_one_line_error(tmp_path): - shim = "import sys,mission_guard as m;from chef.guards import adapters;a=adapters;a.in_place_adapters_dir=lambda:'" + str(tmp_path / "nope").replace("\\", "/") - shim += "';sys.argv=['check_guard.py','demo'];import runpy;runpy.run_path(r'" + str(CHECK_GUARD) - shim += "', run_name='__main__')" - env = {k: v for k, v in os.environ.items() if k not in CLEARED_ENV} - env["PYTHONPATH"] = str(HOOKS_DIR) - result = subprocess.run([sys.executable, "-B", "-c", shim], capture_output=True, env=env, timeout=60) - assert result.returncode == 3 - assert "레지스트리 경로도 없음" in result.stdout.decode("utf-8") - assert "Traceback" not in result.stderr.decode("utf-8") - - -def test_check_guard_missing_cases_file_is_one_line_error(tmp_path): - adapter = write_adapter_file(tmp_path) - result = run_check_guard_cli(str(adapter), str(tmp_path / "nope.json")) - assert result.returncode == 3 - assert result.stdout.decode("utf-8").startswith("ERROR 읽기 실패: ") - - -def test_check_guard_applies_local_json_deep_merge_like_the_hook(tmp_path): - adapter = write_adapter_file(tmp_path) - write_json(adapter.parent / "local.json", {"guard": {"deny": [SYNC_RULE]}}) - cases = tmp_path / "cases.json" - cases.write_text( - json.dumps([{"expect": "deny", "command": "p4 sync"}, {"expect": "allow", "command": "p4 submit -c 1"}]), - encoding="utf-8", - ) - assert load_check_guard().evaluate(str(adapter), str(cases)) == ([], [], []) - - -def test_check_guard_reports_broken_local_json_as_problem(tmp_path): - adapter = write_adapter_file(tmp_path) - (adapter.parent / "local.json").write_text("{broken", encoding="utf-8") - cases = tmp_path / "cases.json" - cases.write_text(json.dumps([{"expect": "deny", "command": "p4 submit"}]), encoding="utf-8") - _, _, problems = load_check_guard().evaluate(str(adapter), str(cases)) - assert any("local.json 무시" in problem for problem in problems) diff --git a/tests/integration/hooks/test_mission_policy.py b/tests/integration/hooks/test_mission_policy.py deleted file mode 100644 index d459bc8..0000000 --- a/tests/integration/hooks/test_mission_policy.py +++ /dev/null @@ -1,168 +0,0 @@ -"""External mission policy failures must precede lifecycle state changes.""" -import json -import os -import sys -import threading -from pathlib import Path - -import pytest - -from chef.cli import mission_entry -from chef.guards import mission, policy -from chef.runtimes.hermes import workers - - -def execute_marker(value): - # Test commit-time policy and lock semantics; hook/CLI separation has its own integration tests. - return mission.decide(value, marker_mode="execute") - - -@pytest.fixture -def project(tmp_path, monkeypatch): - root = tmp_path / "fictional-garden" - root.mkdir() - adapter = root / ".claude/orchestrator/adapter.json" - adapter.parent.mkdir(parents=True) - active = root / "state/ACTIVE" - active.parent.mkdir() - original = {"id": "orchard", "session": "gardener-a", "runtime": "claude"} - active.write_text(json.dumps(original), encoding="utf-8") - for key in tuple(os.environ): - if key.startswith(("CHEF_", "HAN_", "CLAUDE_", "GROK_")): - monkeypatch.delenv(key, raising=False) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "registry")) - monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex")) - return root, adapter, active - - -def configure(project, argv=None): - root, adapter, active = project - data = {"schema": 1, "paths": {"stateDir": "state"}} - if argv is not None: - data["guard"] = {"missionPolicyCommand": argv} - adapter.write_text(json.dumps(data), encoding="utf-8") - - -def payload(project, runtime="claude", session="gardener-b", action="resume", **extra): - return {"cwd": str(project[0]), "han_runtime": runtime, "session_id": session, - "tool_name": "Bash", "tool_input": {"command": f"echo han-mission {action} orchard"}, **extra} - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_unconfigured_resume_keeps_existing_takeover_behavior(project, runtime): - configure(project) - result = execute_marker(payload(project, runtime)) - assert not result.deny - assert json.loads(project[2].read_text())["session"] == "gardener-b" - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_child_markers_do_not_change_active(project, runtime): - configure(project) - original = project[2].read_bytes() - assert execute_marker(payload(project, runtime, agent_id="seedling")).deny - assert project[2].read_bytes() == original - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -@pytest.mark.parametrize("code", [ - "print('not-json')", "print('{}')", "print('[]')", - "import json; print(json.dumps({'hookSpecificOutput': {'permissionDecision': 'deny', 'permissionDecisionReason': 'fictional restriction'}}))", - "import sys; sys.exit(4)", "print('x'*65537)", -]) -def test_external_policy_failures_preserve_active(project, runtime, code): - configure(project, [sys.executable, "-c", code]) - original = project[2].read_bytes() - assert execute_marker(payload(project, runtime)).deny - assert project[2].read_bytes() == original - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -@pytest.mark.parametrize("code", ["pass", "import json; print(json.dumps({'hookSpecificOutput': {'permissionDecision': 'allow'}}))"]) -def test_successful_policy_allows_transition(project, runtime, code): - configure(project, [sys.executable, "-c", code]) - assert not execute_marker(payload(project, runtime)).deny - assert json.loads(project[2].read_text())["session"] == "gardener-b" - - -@pytest.mark.parametrize("argv", [[], None, "not-argv", [""], ["fictional-missing-executable"]]) -def test_invalid_configured_policy_denies(project, argv): - configure(project) - data = json.loads(project[1].read_text()) - data["guard"] = {"missionPolicyCommand": argv} - project[1].write_text(json.dumps(data), encoding="utf-8") - original = project[2].read_bytes() - assert execute_marker(payload(project)).deny - assert project[2].read_bytes() == original - - -def test_timeout_and_stderr_limit_are_fail_closed(project): - assert policy.command_denial([sys.executable, "-c", "import time; time.sleep(5)"], {}, str(project[0]), timeout=.1) - assert policy.command_denial([sys.executable, "-c", "import sys; sys.stderr.write('x'*65537)"], {}, str(project[0])) - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_close_policy_and_timeout_preserve_active(project, runtime, monkeypatch): - configure(project, [sys.executable, "-c", "import time; time.sleep(5)"]) - monkeypatch.setattr(policy, "POLICY_TIMEOUT", .1) - original = project[2].read_bytes() - assert execute_marker(payload(project, runtime, session="gardener-a", action="close")).deny - assert project[2].read_bytes() == original - - -def test_shared_worker_protocol_denies_exit_zero_deny(project): - request = payload(project) - request["han_hermes_worker"] = {"cwd": str(project[0]), "guard": [sys.executable, "-c", - "print('{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\"}}')"]} - assert workers.project_denial(request) - request["han_hermes_worker"]["guard"] = [sys.executable, "-c", "pass"] - assert not workers.project_denial(request) - - -def test_policy_validation_and_marker_share_existing_active_lock(project, monkeypatch): - configure(project, [sys.executable, "-c", "pass"]) - checked = threading.Event() - release = threading.Event() - contender_checked = threading.Event() - outcomes = {} - - def validate(adapter, request): - if request["session_id"] == "gardener-b": - checked.set() - assert release.wait(5) - return "" - contender_checked.set() - return "owner changed" if json.loads(project[2].read_text())["session"] != "gardener-a" else "" - - monkeypatch.setattr(mission, "mission_policy_denial", validate) - # FileLock uses timeout=0; contention must deny rather than overlap or deadlock. - thread = threading.Thread(target=lambda: outcomes.setdefault("resume", execute_marker(payload(project)))) - thread.start() - try: - assert checked.wait(5) - outcome = execute_marker(payload(project, session="gardener-a", action="close")) - assert outcome.deny - assert not contender_checked.is_set() - assert json.loads(project[2].read_text())["session"] == "gardener-a" - finally: - release.set() - thread.join(5) - assert not thread.is_alive() - assert not outcomes["resume"].deny - assert json.loads(project[2].read_text())["session"] == "gardener-b" - - -def test_adapter_change_during_lock_acquisition_is_rejected(project, monkeypatch): - configure(project, [sys.executable, "-c", "pass"]) - original = project[2].read_bytes() - real_lock = mission_entry.active_lock - - def changed(state): - data = json.loads(project[1].read_text()) - del data["guard"] - project[1].write_text(json.dumps(data), encoding="utf-8") - return real_lock(state) - - monkeypatch.setattr(mission_entry, "active_lock", changed) - assert execute_marker(payload(project)).deny - assert project[2].read_bytes() == original diff --git a/tests/integration/hooks/test_mission_transitions.py b/tests/integration/hooks/test_mission_transitions.py deleted file mode 100644 index cdcbee0..0000000 --- a/tests/integration/hooks/test_mission_transitions.py +++ /dev/null @@ -1,228 +0,0 @@ -import json -import os -import subprocess -import sys -import uuid -from pathlib import Path - -import pytest - -from chef.guards import mission -from chef.mission import transitions -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture -def workspace(tmp_path, monkeypatch): - root = tmp_path / "fictional-workspace" - folder = root / ".claude/orchestrator" - folder.mkdir(parents=True) - (folder / "adapter.json").write_text(json.dumps({ - "schema": 1, "paths": {"stateDir": "state"}}), encoding="utf-8") - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "no-registry")) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - monkeypatch.delenv("CHEF_WORKER_CONTEXT", raising=False) - monkeypatch.delenv("CHEF_HERMES_WORKER", raising=False) - monkeypatch.chdir(root) - return root - - -def command(root, action="open", runtime="claude", session="parent"): - return [sys.executable, "-B", str(PLUGIN_ROOT / "mission_control.py"), action, "sample-mission", - "--runtime", runtime, "--session", session, "--project", str(root), "--request", uuid.uuid4().hex] - - -def preflight(root, argv, runtime="claude", **extra): - payload = {"cwd": str(root), "session_id": "parent", "tool_name": "Bash", - "tool_input": {"command": " ".join('"' + item + '"' if ' ' in item else item for item in argv)}, - **extra} - if runtime == "grok": - payload["hookEventName"] = "pre_tool_use" - payload["toolName"] = "run_terminal_command" - hook = PLUGIN_ROOT / ("hooks/mission_guard.py" if runtime == "claude" else - "codex/mission_guard.py" if runtime == "codex" else "hooks/mission_guard.py") - result = subprocess.run([sys.executable, "-B", str(hook)], input=json.dumps(payload).encode(), - capture_output=True, cwd=root, timeout=20) - assert result.returncode == 0, result.stderr.decode() - return json.loads(result.stdout or b"{}") - - -def denied(result): - return result.get("hookSpecificOutput", {}).get("permissionDecision") == "deny" - - -def commit(argv): - return subprocess.run(argv, capture_output=True, timeout=20) - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -@pytest.mark.parametrize("unified", [False, True]) -def test_permission_check_does_not_open_until_cli_executes(workspace, runtime, unified): - argv = command(workspace, runtime=runtime) - if unified: - argv[2:3] = [str(PLUGIN_ROOT / "chef_cli.py"), "mission"] - assert not denied(preflight(workspace, argv, runtime)) - assert not (workspace / "state/ACTIVE").exists() - assert not (workspace / "state/sample-mission/sessions.tsv").exists() - result = commit(argv) - assert result.returncode == 0, result.stderr.decode() - active = mission.read_active(str(workspace / "state")) - assert active.runtime == runtime and active.session == "parent" - assert commit(argv).returncode == 1 - - -def test_unified_transition_rejects_a_different_bundle(workspace): - argv = command(workspace) - argv[2:3] = [str(workspace / "chef_cli.py"), "mission"] - assert denied(preflight(workspace, argv)) - assert not (workspace / "state/.transitions").exists() - - -@pytest.mark.parametrize("previous", ["claude", "codex", "grok", ""]) -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_resume_updates_both_identity_fields_and_preserves_open_time(workspace, previous, runtime): - state = str(workspace / "state") - mission.write_active(state, mission.Active("sample-mission", "old-session", "original-time", runtime=previous)) - argv = command(workspace, "resume", runtime) - assert not denied(preflight(workspace, argv, runtime)) - assert mission.read_active(state).session == "old-session" - result = commit(argv) - assert result.returncode == 0, result.stderr.decode() - active = mission.read_active(state) - assert (active.session, active.runtime, active.opened_at) == ("parent", runtime, "original-time") - - -def test_host_denial_after_preflight_preserves_active_and_allowance(workspace): - state = workspace / "state" - mission.write_active(str(state), mission.Active("sample-mission", "parent", "original", runtime="claude")) - allowance = state / "sample-mission/allow-once" - allowance.parent.mkdir(parents=True) - allowance.write_bytes(b"fictional-command\n") - original = (state / "ACTIVE").read_bytes() - argv = command(workspace, "close") - assert not denied(preflight(workspace, argv)) - # The host denies execution: it never starts the prepared CLI. - assert (state / "ACTIVE").read_bytes() == original - assert allowance.read_bytes() == b"fictional-command\n" - assert commit(argv).returncode == 0 - assert not (state / "ACTIVE").exists() and not allowance.exists() - - -@pytest.mark.parametrize("change", ["owner", "adapter", "expiry"]) -def test_changed_inputs_refuse_execution_without_mutation(workspace, change): - argv = command(workspace) - assert not denied(preflight(workspace, argv)) - if change == "owner": - mission.write_active(str(workspace / "state"), mission.Active("other-mission", "other-session", "time")) - elif change == "adapter": - (workspace / ".claude/orchestrator/adapter.json").write_text( - '{"schema":1,"project":"changed","paths":{"stateDir":"state"}}', encoding="utf-8") - else: - path = next((workspace / "state/.transitions").glob("*.json")) - data = json.loads(path.read_text(encoding="utf-8")); data["createdAt"] -= 1000 - path.write_text(json.dumps(data), encoding="utf-8") - before = mission.read_active(str(workspace / "state")) - assert commit(argv).returncode == 1 - assert mission.read_active(str(workspace / "state")) == before - - -@pytest.mark.parametrize("extra", [{"session_id": "other"}, {"agent_id": "child"}]) -def test_native_identity_must_match_and_workers_cannot_prepare(workspace, extra): - assert denied(preflight(workspace, command(workspace), **extra)) - assert not (workspace / "state/ACTIVE").exists() - - -@pytest.mark.parametrize("action", ["open", "resume", "close"]) -def test_cli_without_hook_receipt_and_legacy_echo_cannot_change_state(workspace, action): - assert commit(command(workspace)).returncode == 1 - if action != "open": - mission.write_active(str(workspace / "state"), mission.Active("sample-mission", "parent", "time", runtime="claude")) - before = mission.read_active(str(workspace / "state")) - payload = {"cwd": str(workspace), "session_id": "parent", "han_runtime": "claude", - "tool_name": "Bash", "tool_input": {"command": f"echo han-mission {action} sample-mission"}} - assert mission.decide(payload).deny - assert mission.read_active(str(workspace / "state")) == before - - -def test_policy_is_rechecked_when_prepared_command_executes(workspace): - gate = workspace / "gate.txt" - gate.write_text("deny", encoding="utf-8") - policy = workspace / "policy.py" - policy.write_text("import pathlib,sys\nsys.exit(0 if pathlib.Path(sys.argv[1]).read_text() == 'allow' else 1)\n", - encoding="utf-8") - adapter = workspace / ".claude/orchestrator/adapter.json" - value = json.loads(adapter.read_text(encoding="utf-8")) - value["guard"] = {"missionPolicyCommand": [sys.executable, str(policy), str(gate)]} - adapter.write_text(json.dumps(value), encoding="utf-8") - assert denied(preflight(workspace, command(workspace))) - gate.write_text("allow", encoding="utf-8") - argv = command(workspace) - assert not denied(preflight(workspace, argv)) - gate.write_text("deny", encoding="utf-8") - assert commit(argv).returncode == 1 - assert not (workspace / "state/ACTIVE").exists() - - -def test_session_log_failure_restores_previous_active(workspace, monkeypatch): - from chef.infrastructure import storage - - state = str(workspace / "state") - mission.write_active(state, mission.Active("sample-mission", "old-session", "original", runtime="codex")) - before = (workspace / "state/ACTIVE").read_bytes() - argv = command(workspace, "resume") - assert not denied(preflight(workspace, argv)) - original = storage.atomic_write_bytes - - def fail_log(path, value, **kwargs): - if Path(path).name == "sessions.tsv": - raise PermissionError("fictional log error") - return original(path, value, **kwargs) - - monkeypatch.setattr(storage, "atomic_write_bytes", fail_log) - with pytest.raises(ValueError, match="ACTIVE"): - transitions.execute(transitions.arguments(argv[3:])) - assert (workspace / "state/ACTIVE").read_bytes() == before - assert not (workspace / "state/sample-mission/sessions.tsv").exists() - - -def test_two_prepared_calls_cannot_overwrite_a_committed_owner(workspace): - first = command(workspace) - second = command(workspace, session="next-session") - assert not denied(preflight(workspace, first)) - assert not denied(preflight(workspace, second, session_id="next-session")) - assert commit(first).returncode == 0 - before = (workspace / "state/ACTIVE").read_bytes() - assert commit(second).returncode == 1 - assert (workspace / "state/ACTIVE").read_bytes() == before - - -def test_resume_preserves_existing_session_history_bytes(workspace): - state = str(workspace / "state") - mission.write_active(state, mission.Active("sample-mission", "old-session", "original", runtime="codex")) - history = workspace / "state/sample-mission/sessions.tsv" - history.parent.mkdir(parents=True) - previous = b"at\taction\tsession\ttranscript\r\nold\topen\told-session\t\r\n" - history.write_bytes(previous) - argv = command(workspace, "resume") - assert not denied(preflight(workspace, argv)) - assert commit(argv).returncode == 0 - assert history.read_bytes().startswith(previous) - - -@pytest.mark.parametrize("prefix", [["env", "SAMPLE=1"], ["cmd", "/c"]]) -def test_wrapped_transition_cannot_skip_native_identity_check(workspace, prefix): - assert denied(preflight(workspace, prefix + command(workspace), agent_id="child")) - assert not (workspace / "state/ACTIVE").exists() - - -def test_searching_transition_source_is_still_read_only(workspace): - payload = {"cwd": str(workspace), "session_id": "parent", "han_runtime": "claude", - "tool_name": "Bash", "tool_input": {"command": 'rg "mission_control.py" README.md'}} - assert not mission.decide(payload).deny - - -def test_cli_without_adapter_returns_an_error_without_traceback(workspace): - (workspace / ".claude/orchestrator/adapter.json").unlink() - result = commit(command(workspace)) - assert result.returncode == 1 - assert "error" in json.loads(result.stderr) diff --git a/tests/integration/hooks/test_question_integrity.py b/tests/integration/hooks/test_question_integrity.py deleted file mode 100644 index 46dcf52..0000000 --- a/tests/integration/hooks/test_question_integrity.py +++ /dev/null @@ -1,284 +0,0 @@ -import copy -import hashlib -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest -from chef.guards import integrity as question_integrity -from chef.questions import records as question_records - -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture -def project(tmp_path, monkeypatch): - for key in ("HAN_ADAPTERS_DIR", "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "CLAUDE_PROJECT_DIR", "HAN_REPO", "HAN_GUARD_LOG"): - monkeypatch.delenv(key, raising=False) - monkeypatch.setenv("CODEX_HOME", str(tmp_path / "codex-home")) - folder = tmp_path / "project" - adapter = folder / ".claude/orchestrator/adapter.json" - adapter.parent.mkdir(parents=True) - adapter.write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}}), encoding="utf-8") - mission = folder / "state/example-mission" - mission.mkdir(parents=True) - (mission.parent / "ACTIVE").write_text(json.dumps({"id": mission.name, "session": "owner", "openedAt": "2026-01-01"}), encoding="utf-8") - return folder, mission - - -def document(): - return {"schema": 1, "id": "ask-palette", "revision": 1, "title": "Choose a palette", - "intro": "Choose colors for a fictional garden.", - "items": [{"id": "1", "title": "Use blue?", "body": "Blue or green", "status": "pending", "answer": ""}], - "body": "", "approval": {"status": "none", "reason": ""}, "answers": []} - - -def answer(): - return {"schema": 1, "id": "reply-palette", "revision": 1, "at": "2026-01-01", "text": "Use blue for the fictional garden.", - "updates": [{"id": "1", "status": "answered", "answer": "Use blue."}]} - - -def payload(project, event="Stop", **fields): - folder, _ = project - return {"hook_event_name": event, "session_id": "owner", "cwd": str(folder), "tool_name": "Bash", - "tool_input": {"command": "python opaque-writer.py"}, **fields} - - -def snapshot(folder): - return {str(path.relative_to(folder)): (path.read_bytes(), path.stat().st_mtime_ns) - for path in folder.rglob("*") if path.is_file()} - - -@pytest.mark.parametrize("event", ["Stop"]) -@pytest.mark.parametrize("state", ["pending", "answered", "approval-pending"]) -def test_consistent_questions_pass_without_changing_records(project, event, state): - _, mission = project - question_records.publish_document(mission, document()) - if state != "pending": - reply = answer() - if state == "approval-pending": - reply["approval"] = {"status": "pending", "reason": "The fictional border still needs approval."} - question_records.answer_document(mission, "ask-palette.md", reply) - before = snapshot(project[0]) - assert question_integrity.decide(payload(project, event)) == {} - assert snapshot(project[0]) == before - - -@pytest.mark.parametrize("event", ["Stop"]) -@pytest.mark.parametrize("mutation", ["markdown-answer", "markdown-status", "stale-json", "missing-json", "corrupt-json", "missing-markdown", "invalid-utf8"]) -def test_opaque_writes_are_detected_without_rewriting(project, event, mutation): - _, mission = project - question_records.publish_document(mission, document()) - markdown = mission / "ask-palette.md" - source = mission / "questions/ask-palette.json" - if mutation == "markdown-answer": - markdown.write_text(markdown.read_text(encoding="utf-8") + "\n## Past answer\nUse blue.\n", encoding="utf-8") - elif mutation == "markdown-status": - markdown.write_text(markdown.read_text(encoding="utf-8").replace("답변 대기", "답변 완료"), encoding="utf-8") - elif mutation == "stale-json": - before = source.read_bytes() - question_records.answer_document(mission, markdown.name, answer()) - source.write_bytes(before) - elif mutation == "missing-json": - source.unlink() - elif mutation == "corrupt-json": - source.write_text("{broken", encoding="utf-8") - elif mutation == "missing-markdown": - markdown.unlink() - else: - source.write_bytes(b"\xff") - before = snapshot(project[0]) - output = question_integrity.decide(payload(project, event)) - assert output["systemMessage"] - assert "ask-palette.md" in output["systemMessage"] or "검사 실패" in output["systemMessage"] - assert "question check" in output["systemMessage"] and "question restore" in output["systemMessage"] - assert "permissionDecision" not in output.get("hookSpecificOutput", {}) - if event == "PostToolUse": - assert output["hookSpecificOutput"] == {"hookEventName": event, "additionalContext": output["systemMessage"]} - else: - assert "hookSpecificOutput" not in output - assert question_integrity.decide(payload(project, event, stop_hook_active=True)) == {} - assert snapshot(project[0]) == before - - -@pytest.mark.parametrize("fields,blocked", [({}, True), ({"agent_id": "child", "agent_type": "default"}, True), - ({"session_id": "unrelated"}, False), ({"session_id": "child-session", "parent_session_id": "owner"}, False)]) -def test_owner_and_common_parent_child_session_scope(project, fields, blocked): - _, mission = project - (mission / "ask-palette.md").write_text("# Unregistered fictional question", encoding="utf-8") - output = question_integrity.decide(payload(project, **fields)) - assert bool(output.get("systemMessage")) is blocked - - -@pytest.mark.parametrize("runtime", ["grok", "codex", "claude"]) -@pytest.mark.parametrize("event", ["Stop"]) -def test_repair_command_preserves_detected_runtime_and_adapter(project, runtime, event): - root, mission = project - if runtime != "claude": - (root / ".claude").rename(root / f".{runtime}") - (mission / "ask-palette.md").write_text("# Unregistered fictional question", encoding="utf-8") - fields = payload(project, event) - if runtime == "grok": - fields = {"hookEventName": {"PostToolUse": "post_tool_use", "Stop": "stop"}[event], "sessionId": "owner", "cwd": str(root), - "toolName": "write", "toolInput": {"path": "notes.md", "contents": "Fictional note"}} - output = question_integrity.decide(fields) - else: - output = question_integrity.decide(fields, runtime) - assert output["systemMessage"] - expected = f'python "{os.path.join(question_integrity.SCRIPTS, "mission_state.py")}" --runtime {runtime} question check --project "{root}" --mission "{mission.name}"' - assert expected in output["systemMessage"] - assert str(mission) in output["systemMessage"] - - -def test_no_active_or_adapter_does_not_audit_archived_questions(project): - _, mission = project - (mission / "ask-palette.md").write_text("# Archived fictional question", encoding="utf-8") - active = mission.parent / "ACTIVE" - active.unlink() - assert question_integrity.decide(payload(project)) == {} - (project[0] / ".claude/orchestrator/adapter.json").unlink() - assert not question_integrity.decide(payload(project)).get("decision") - - -@pytest.mark.parametrize("invalid", ["{broken", '{"id":"../outside","session":"owner"}', '{"id":"example-mission"}']) -def test_unowned_active_is_quiet(project, invalid): - (project[1].parent / "ACTIVE").write_text(invalid, encoding="utf-8") - output = question_integrity.decide(payload(project)) - assert output == {} - - -def test_missing_owned_mission_and_inspector_errors_block(project, monkeypatch): - project[1].rmdir() - assert question_integrity.decide(payload(project))["systemMessage"] - project[1].mkdir() - monkeypatch.setattr(question_integrity.mission_state, "question_inspections", lambda folder: (_ for _ in ()).throw(OSError("unreadable"))) - output = question_integrity.decide(payload(project)) - assert output["systemMessage"] and "unreadable" in output["systemMessage"] - - -def test_unavailable_adapter_and_missing_session_are_quiet(project): - adapter = project[0] / ".claude/orchestrator/adapter.json" - adapter.write_text("{broken", encoding="utf-8") - output = question_integrity.decide(payload(project)) - assert output == {} - adapter.write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}}), encoding="utf-8") - output = question_integrity.decide(payload(project, session_id="")) - assert output == {} - - -def test_unsupported_events_and_tools_are_ignored(project): - assert question_integrity.decide(payload(project, "PreToolUse")) == {} - assert question_integrity.decide(payload(project, "PostToolUse", tool_name="Read")) == {} - assert question_integrity.decide([]) == {} - assert question_integrity.decide({}) == {} - - -@pytest.mark.parametrize("tool_input", ["*** Begin Patch\n*** End Patch", [], 42]) -def test_patch_payload_shape_does_not_bypass_owned_inspection(project, tool_input): - (project[1] / "ask-palette.md").write_text("# Unregistered fictional question", encoding="utf-8") - output = question_integrity.decide(payload(project, "Stop", tool_name="apply_patch", tool_input=tool_input)) - assert output["systemMessage"] and "ask-palette.md" in output["systemMessage"] - - -def test_codex_relative_command_cwd_is_resolved_once(project): - unrelated = project[0].parent - (project[1] / "ask-palette.md").write_text("# Unregistered fictional question", encoding="utf-8") - fields = payload(project, "Stop", cwd=str(unrelated), tool_input={"command": "opaque-writer", "cwd": project[0].name}) - assert question_integrity.decide(fields, "codex")["systemMessage"] - - -def test_malformed_stdin_is_quiet_without_writes(project): - before = snapshot(project[0]) - done = subprocess.run([sys.executable, "-B", str(PLUGIN_ROOT / "hooks/question_integrity.py")], input=b"{invalid", capture_output=True, check=True) - output = json.loads(done.stdout or b"{}") - assert output == {} - assert snapshot(project[0]) == before - - -def run_cli(project, *args): - done = subprocess.run([sys.executable, "-B", str(Path(question_integrity.SCRIPTS) / "mission_state.py"), - "question", *args, "--project", str(project[0]), "--mission", project[1].name], capture_output=True, check=False) - assert done.returncode == 0, done.stderr.decode("utf-8") - - -def test_real_cli_publish_answer_and_reviewed_restore_pass(project, tmp_path): - draft = tmp_path / "draft.json" - draft.write_text(json.dumps(document()), encoding="utf-8") - run_cli(project, "publish", "--input", str(draft)) - assert question_integrity.decide(payload(project)) == {} - reply = tmp_path / "reply.json" - reply.write_text(json.dumps(answer()), encoding="utf-8") - run_cli(project, "answer", "ask-palette.md", "--input", str(reply)) - assert question_integrity.decide(payload(project)) == {} - record = question_records.read_document(project[1], "ask-palette.md") - restored = copy.deepcopy(record) - extra = {**answer(), "id": "reply-border", "text": "Use a white fictional border.", - "updates": [{"id": "1", "status": "answered", "answer": "Blue with a white border."}]} - restored["answers"].append(extra) - restored["items"][0].update(status="answered", answer=extra["updates"][0]["answer"]) - markdown = project[1] / "ask-palette.md" - markdown.write_text(markdown.read_text(encoding="utf-8") + "\n" + extra["text"] + "\n", encoding="utf-8") - assert question_integrity.decide(payload(project))["systemMessage"] - evidence = tmp_path / "original.md" - evidence.write_bytes(markdown.read_bytes()) - draft.write_text(json.dumps(restored), encoding="utf-8") - digest = hashlib.sha256((project[1] / "questions/ask-palette.json").read_bytes()).hexdigest() - run_cli(project, "restore", "--input", str(draft), "--source", str(evidence), "--expect-revision", "1", "--expect-sha256", digest) - run_cli(project, "check") - assert question_integrity.decide(payload(project, "PostToolUse")) == {} - assert question_integrity.decide(payload(project)) == {} - - -def test_cli_answer_repairs_markdown_only_answer_without_question_changes(project, tmp_path): - question_records.publish_document(project[1], document()) - source = project[1] / "questions/ask-palette.json" - before = source.read_bytes() - question_records.answer_document(project[1], "ask-palette.md", answer()) - source.write_bytes(before) - output = question_integrity.decide(payload(project)) - assert output["systemMessage"] - assert output["systemMessage"].index("question answer") < output["systemMessage"].index("question restore") - reply = tmp_path / "confirmed-reply.json" - reply.write_text(json.dumps(answer()), encoding="utf-8") - run_cli(project, "answer", "ask-palette.md", "--input", str(reply)) - run_cli(project, "check") - assert question_integrity.decide(payload(project)) == {} - - -@pytest.fixture -def inspections(monkeypatch): - original = question_integrity.mission_state.question_inspections - calls = [] - - def inspect(folder): - calls.append(folder) - return original(folder) - - monkeypatch.setattr(question_integrity.mission_state, "question_inspections", inspect) - return calls - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_only_stop_inspects_and_each_stop_rechecks(project, inspections, runtime): - question_records.publish_document(project[1], document()) - for _ in range(3): - assert question_integrity.decide(payload(project, "PostToolUse"), runtime) == {} - assert inspections == [] - for _ in range(2): - assert question_integrity.decide(payload(project), runtime) == {} - assert len(inspections) == 2 - path = project[1] / "ask-palette.md" - info = path.stat() - path.write_bytes(path.read_bytes().replace(b"Choose", b"Select")) - os.utime(path, ns=(info.st_atime_ns, info.st_mtime_ns)) - assert question_integrity.decide(payload(project), runtime)["systemMessage"] - assert len(inspections) == 3 - - -def test_grok_child_stop_participates_only_with_nonempty_session(project): - (project[1] / "ask-palette.md").write_text("# Unregistered fictional question", encoding="utf-8") - fields = payload(project, session_id="child", subagentType="chef:dev-medium") - assert question_integrity.decide(fields, "grok")["systemMessage"] - assert question_integrity.decide({**fields, "session_id": ""}, "grok") == {} diff --git a/tests/integration/hooks/test_question_write.py b/tests/integration/hooks/test_question_write.py new file mode 100644 index 0000000..3f54900 --- /dev/null +++ b/tests/integration/hooks/test_question_write.py @@ -0,0 +1,46 @@ +"""Question files stay protected from direct tool writes.""" +import json + +import pytest +from chef.guards import mission as mission_guard + +from tests.support import isolate + + +@pytest.fixture +def project(tmp_path, monkeypatch): + isolate(monkeypatch, tmp_path) + monkeypatch.setattr(mission_guard.execution, "registry_directory", lambda: tmp_path / "execution-registry") + root = tmp_path / "sample-project" + adapter = root / ".claude/orchestrator" + adapter.mkdir(parents=True) + (adapter / "adapter.json").write_text(json.dumps({ + "schema": 1, "paths": {"stateDir": "state"}, "guard": {"coordinatorWrite": ["state/**"]}, + }), encoding="utf-8") + state = root / "state" + state.mkdir() + (state / "ACTIVE").write_text('{"id":"mission","session":"owner"}', encoding="utf-8") + return root + + +def decide(project, tool, key, target, session="owner"): + return mission_guard.decide({ + "cwd": str(project), "session_id": session, "han_runtime": "claude", + "tool_name": tool, "tool_input": {key: target}, + }) + + +def test_question_paths_are_denied_for_each_write_tool(project): + tools = [("Write", "file_path"), ("Edit", "path"), ("MultiEdit", "file_path"), ("NotebookEdit", "notebook_path")] + targets = ["state/mission/ask-1.md", "state/mission/questions/ask-1.json"] + for tool, key in tools: + for target in targets: + assert decide(project, tool, key, target).deny, (tool, target) + + +def test_ordinary_source_read_is_allowed(project): + result = mission_guard.decide({ + "cwd": str(project), "session_id": "owner", "han_runtime": "claude", + "tool_name": "Read", "tool_input": {"file_path": "src/app.py"}, + }) + assert not result.deny diff --git a/tests/integration/hooks/test_question_write_guard.py b/tests/integration/hooks/test_question_write_guard.py deleted file mode 100644 index 94f0484..0000000 --- a/tests/integration/hooks/test_question_write_guard.py +++ /dev/null @@ -1,501 +0,0 @@ -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest -from chef.guards import mission as mission_guard -from chef.guards import questions as question_write_guard - -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture -def project(tmp_path, monkeypatch): - monkeypatch.setattr(mission_guard.execution, "registry_directory", lambda: tmp_path / "execution-registry") - root = tmp_path / "sample-project" - adapter_folder = root / ".claude" / "orchestrator" - adapter_folder.mkdir(parents=True) - adapter = {"schema": 1, "paths": {"stateDir": "state"}, "guard": {"coordinatorWrite": ["state/**"]}} - (adapter_folder / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "no-registry")) - state = root / "state" - state.mkdir() - (state / "ACTIVE").write_text('{"id":"mission","session":"owner"}', encoding="utf-8") - return root - - -def outcome(project, tool="Write", *, runtime="claude", **tool_input): - return mission_guard.decide({"cwd": str(project), "session_id": "owner", "han_runtime": runtime, "tool_name": tool, "tool_input": tool_input}) - - -@pytest.mark.parametrize("tool,key", [("Write", "file_path"), ("Edit", "path"), ("MultiEdit", "file_path"), ("NotebookEdit", "notebook_path")]) -@pytest.mark.parametrize("target", ["state/mission/ask-1.md", "state/mission/confirm-A.md", "state/mission/questions/ask-1.json", "state/mission/questions/history/ask-1/r1.json"]) -def test_structured_new_and_existing_question_files(project, tool, key, target): - assert outcome(project, tool, **{key: target}).deny - path = project / target - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text("old", encoding="utf-8") - assert outcome(project, tool, **{key: target}).deny - - -@pytest.mark.parametrize("active", ["", '{"id":"mission","session":"owner"}', "{broken", '{"id":"mission"}']) -@pytest.mark.parametrize("session", ["owner", "different", ""]) -def test_question_scan_requires_valid_participating_session(project, monkeypatch, active, session): - state = project / "state" - (state / "ACTIVE").unlink() - if active: - (state / "ACTIVE").write_text(active, encoding="utf-8") - scans = [] - monkeypatch.setattr(question_write_guard, "shell_targets", lambda *args: (scans.append(args) or (["state/mission/ask-1.md"], []))) - payload = {"cwd": str(project), "session_id": session, "tool_name": "Bash", "tool_input": {"command": "opaque-writer"}} - participating = active == '{"id":"mission","session":"owner"}' and session == "owner" - assert bool(mission_guard.decide(payload).deny) == participating - assert bool(scans) == participating - - -@pytest.mark.parametrize("command", ["Rename-Item src/old.txt -NewName new.txt", - "Rename-Item -LiteralPath src/old.txt -NewName new.txt", - "ren src/old.txt new.txt"]) -def test_shell_rename_new_name_uses_source_directory(project, command): - targets, _ = question_write_guard.shell_targets(command, "PowerShell", str(project), mission_guard) - assert str(project / "src/new.txt") in targets - assert str(project / "src/old.txt") in targets - assert str(project / "new.txt") not in targets - - -@pytest.mark.parametrize("target", ["state/mission/details/ask-1.md", "state/mission/details/history/notes.md", "state/mission/details/history/ask-1-original.md.txt", "state/mission/draft.json", "state/mission/reply.json", "state/mission/report.md", "src/app.py"]) -def test_other_project_writes_allowed_without_active(project, target): - (project / "state/ACTIVE").unlink() - assert not outcome(project, path=target).deny - - -@pytest.mark.parametrize("header", ["Add File", "Update File", "Delete File", "Move to"]) -@pytest.mark.parametrize("key", ["command", "patch", "input", "patch_text"]) -def test_all_patch_targets_and_aliases(project, header, key): - patch = f"*** Begin Patch\n*** Update File: draft.md\n@@\n-old\n+new\n*** {header}: state/mission/ask-1.md\n*** End Patch" - assert outcome(project, "apply_patch", **{key: patch}).deny - - -def test_patch_allows_draft_and_detail(project): - assert not outcome(project, "apply_patch", command="*** Begin Patch\n*** Add File: state/mission/details/ask-1.md\n+text\n*** End Patch").deny - - -@pytest.mark.parametrize("target", ["state/mission/details", "state/mission/details/history"]) -@pytest.mark.parametrize("source", ["confirm-A2.md", "questions/confirm-A2.json"]) -def test_removing_parent_of_generated_history_is_protected(project, target, source): - mission = project / "state/mission" - history = mission / "details/history/confirm-A2.md" - history.parent.mkdir(parents=True) - history.write_text("# Generated example history", encoding="utf-8") - corresponding = mission / source - corresponding.parent.mkdir(parents=True, exist_ok=True) - corresponding.write_text("Example", encoding="utf-8") - assert outcome(project, "Bash", command=f'rm -rf "{target}"').deny - - -def test_handwritten_history_remains_editable(project): - history = project / "state/mission/details/history/notes.md" - history.parent.mkdir(parents=True) - history.write_text("# Handwritten garden notes", encoding="utf-8") - assert not outcome(project, "Bash", command='rm -rf "state/mission/details/history"').deny - - -@pytest.mark.parametrize("sources", [(), ("confirm-A2.md",), ("questions/confirm-A2.json",), ("confirm-A2.md", "questions/confirm-A2.json")]) -@pytest.mark.parametrize("tool,key", [("Write", "file_path"), ("Edit", "path"), ("MultiEdit", "file_path"), ("NotebookEdit", "notebook_path")]) -def test_generated_history_requires_matching_root_or_record(project, sources, tool, key): - mission = project / "state/mission" - mission.mkdir(parents=True) - for name in sources: - source = mission / name - source.parent.mkdir(parents=True, exist_ok=True) - source.write_text("Example", encoding="utf-8") - target = "state/mission/details/history/confirm-A2.md" - assert bool(outcome(project, tool, **{key: target}).deny) == bool(sources) - history = project / target - history.parent.mkdir(parents=True, exist_ok=True) - history.write_text("# Example history", encoding="utf-8") - assert bool(outcome(project, tool, **{key: target}).deny) == bool(sources) - - -@pytest.mark.parametrize("source", ["confirm-A2.md", "questions/confirm-A2.json"]) -@pytest.mark.parametrize("target", ["details/history/confirm-A2.md", "details", "details/history"]) -def test_mixed_case_mission_preserves_filesystem_case_for_history_protection(project, monkeypatch, source, target): - assert mission_guard.valid_mission_id("MyMission") - mission = project / "state/MyMission" - history = mission / "details/history/confirm-A2.md" - history.parent.mkdir(parents=True) - history.write_text("# Generated example history", encoding="utf-8") - corresponding = mission / source - corresponding.parent.mkdir(parents=True, exist_ok=True) - corresponding.write_text("Example", encoding="utf-8") - generated_history = question_write_guard.generated_history - queried = [] - - def check_filesystem_case(folder, name): - assert Path(folder).name == "MyMission" - queried.append((folder, name)) - return generated_history(folder, name) - - monkeypatch.setattr(question_write_guard, "generated_history", check_filesystem_case) - if target == "details/history/confirm-A2.md": - result = outcome(project, path=str(mission / target)) - else: - result = outcome(project, "Bash", command=f'rm -rf "{mission / target}"') - assert result.deny and queried - - -@pytest.mark.parametrize("name", ["confirm-A2.before-current-history.r11.md", "confirm-A2.details.before-current-history.r11.md", "notes.md"]) -@pytest.mark.parametrize("target", ["state/mission/details", "state/mission/details/history"]) -def test_original_history_names_are_editable_and_do_not_protect_parents(project, name, target): - mission = project / "state/mission" - history = mission / "details/history" / name - history.parent.mkdir(parents=True) - history.write_text("# Original example bytes", encoding="utf-8") - (mission / "confirm-A2.md").write_text("# Current example", encoding="utf-8") - assert not outcome(project, path=str(history)).deny - assert not outcome(project, "Bash", command=f'rm -rf "{target}"').deny - - -def test_orphan_history_cannot_grant_automatic_document_sharing(project, monkeypatch): - monkeypatch.syspath_prepend(str(PLUGIN_ROOT / "skills/mission/scripts")) - from chef.mission import state as mission_state - - mission = project / "state/mission" - history = mission / "details/history/confirm-A2.md" - history.parent.mkdir(parents=True) - history.write_text("# Orphan example history", encoding="utf-8") - assert not outcome(project, path=str(history)).deny - for parent in (history.parent, history.parent.parent): - assert not outcome(project, "Bash", command=f'rm -rf "{parent}"').deny - assert not mission_state.auto_question_document(str(mission), "details/history/confirm-A2.md") - assert mission_state.auto_question_documents(str(mission)) == set() - assert outcome(project, path=str(mission / "confirm-A2.md")).deny - assert outcome(project, path=str(mission / "questions/confirm-A2.json")).deny - - -def test_raw_patch_string_and_malformed_input(project): - payload = {"cwd": str(project), "session_id": "owner", "tool_name": "apply_patch", "tool_input": "*** Begin Patch\n*** Delete File: state/mission/ask-1.md\n*** End Patch"} - assert mission_guard.decide(payload).deny - payload["tool_input"] = [] - assert not mission_guard.decide(payload).deny - - -@pytest.mark.parametrize("target", ["state/mission/../mission/ASK-1.MD", "STATE/mission/ask-1.md"]) -def test_dot_and_case_aliases(project, target): - assert outcome(project, path=target).deny - - -def test_absolute_target_finds_adapter_from_elsewhere(project, tmp_path, monkeypatch): - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(tmp_path / "elsewhere")) - assert outcome(tmp_path, path=str(project / "state" / "mission" / "ask-1.md")).deny - - -def test_registry_adapter_and_runtime_local_state_override(project, tmp_path, monkeypatch): - adapter_folder = project / ".claude" / "orchestrator" - original = json.loads((adapter_folder / "adapter.json").read_text(encoding="utf-8")) - (adapter_folder / "adapter.json").unlink() - registry = tmp_path / "registry" - (registry / "sample").mkdir(parents=True) - (registry / "projects.json").write_text(json.dumps([{"adapter": "sample", "roots": [str(project)]}]), encoding="utf-8") - (registry / "sample" / "adapter.json").write_text(json.dumps(original), encoding="utf-8") - (registry / "sample" / "local.json").write_text(json.dumps({"runtimes": {"codex": {"paths": {"stateDir": "records"}}}}), encoding="utf-8") - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - payload = {"session_id": "owner", "han_runtime": "codex", "cwd": str(tmp_path), "tool_name": "Write", "tool_input": {"path": str(project / "records" / "mission" / "ask-1.md")}} - records = project / "records" - records.mkdir() - (records / "ACTIVE").write_text('{"id":"mission","session":"owner"}', encoding="utf-8") - assert mission_guard.decide(payload).deny - - -def test_tool_cwd_resolved_once(project, tmp_path): - payload = {"session_id": "owner", "cwd": str(tmp_path), "tool_name": "Write", "tool_input": {"cwd": "sample-project", "path": "state/mission/ask-1.md"}} - assert mission_guard.decide(payload).deny - - -def test_codex_main_resolves_relative_tool_cwd_once(project): - payload = {"session_id": "owner", "cwd": str(project), "tool_name": "Bash", "tool_input": {"cwd": "state/mission", "command": "echo answer > ask-1.md"}} - source = "import sys; sys.path.insert(0,sys.argv[1]); import mission_guard; mission_guard.main('codex')" - result = subprocess.run([sys.executable, "-B", "-c", source, str((PLUGIN_ROOT / 'hooks'))], input=json.dumps(payload).encode("utf-8"), capture_output=True, cwd=project) - assert result.returncode == 0 - assert json.loads(result.stdout)["hookSpecificOutput"]["permissionDecision"] == "deny" - - -def test_symlink_target_finds_real_adapter(project, tmp_path): - alias = tmp_path / "alias" - try: - alias.symlink_to(project, target_is_directory=True) - except OSError: - pytest.skip("directory symlinks unavailable") - assert outcome(tmp_path, path=str(alias / "state" / "mission" / "ask-1.md")).deny - - -@pytest.mark.skipif(os.name != "nt", reason="Windows junction") -def test_junction_target_finds_real_adapter(project, tmp_path): - alias = tmp_path / "junction" - result = subprocess.run(["cmd", "/c", "mklink", "/J", str(alias), str(project)], capture_output=True) - assert result.returncode == 0, result.stderr - assert outcome(tmp_path, path=str(alias / "state" / "mission" / "ask-1.md")).deny - - -def test_file_alias_outside_project_is_protected(project, tmp_path): - source = project / "state" / "mission" / "ask-1.md" - source.parent.mkdir(parents=True) - source.write_text("question", encoding="utf-8") - alias = tmp_path / "alias.md" - try: - alias.symlink_to(source) - except OSError: - pytest.skip("file symlinks unavailable") - assert outcome(tmp_path, path=str(alias)).deny - - -@pytest.mark.parametrize("source", [ - "from pathlib import Path\np=Path('state/mission/ask-1.md'); s=p.read_text(); p.write_text(s.replace('pending','answered'))", - "from pathlib import Path\np=Path('state')/'mission'/'questions'/'ask-1.json'; p.write_bytes(b'{}')", - "from pathlib import Path\np=Path('state/mission/ask-1.md'); p.open('a').write('answer')", - "open('state/mission/confirm-A.md', mode='w').write('answer')", - "from pathlib import Path\np=Path('state/mission/ask-1.md'); q=p; q.unlink()", - "import shutil\nshutil.copy('draft.json','state/mission/questions/ask-1.json')", - "from pathlib import Path\np=Path('state/mission/ask-1.md'); p.rename('draft.md')", - "import shutil\nshutil.rmtree('state/mission')", -]) -def test_python_heredoc_regression_and_ordinary_mutations(project, source): - question = project / "state" / "mission" / "ask-1.md" - question.parent.mkdir(parents=True) - question.write_text("question", encoding="utf-8") - assert outcome(project, "Bash", command=f"python - <<'PY'\n{source}\nPY").deny - - -def test_python_c_and_powershell_herestring(project): - assert outcome(project, "Bash", command='python -c "from pathlib import Path; p=Path(\'state/mission/ask-1.md\'); p.write_text(\'x\')"').deny - assert outcome(project, "PowerShell", command="@'\nfrom pathlib import Path\nPath('state/mission/ask-1.md').write_text('x')\n'@ | python -").deny - - -@pytest.mark.parametrize("command", [ - "echo answer > state/mission/ask-1.md", "echo answer >> state/mission/ask-1.md", - "Set-Content -LiteralPath state/mission/ask-1.md -Value answer", - "Add-Content state/mission/ask-1.md answer", "echo answer | Out-File -FilePath state/mission/ask-1.md", - "Set-Content -Encoding utf8 state/mission/ask-1.md answer", - "cp draft.md state/mission/ask-1.md", "mv state/mission/ask-1.md draft.md", - "Remove-Item -LiteralPath state/mission/questions -Recurse", "rm state/mission/questions/history/r1.json", - "rm -rf state/mission", "Move-Item -LiteralPath state/mission -Destination archive", - "$p='state/mission/ask-1.md'; Set-Content $p answer", - "echo okay; echo answer > state/mission/ask-1.md", -]) -def test_shell_write_targets(project, command): - question = project / "state" / "mission" / "ask-1.md" - question.parent.mkdir(parents=True) - question.write_text("question", encoding="utf-8") - assert outcome(project, "PowerShell", command=command).deny - - -def test_draft_directory_removal_allowed_without_question_descendants(project): - drafts = project / "state" / "drafts" - drafts.mkdir(parents=True) - (drafts / "report.md").write_text("draft", encoding="utf-8") - assert not outcome(project, "Bash", command="rm -rf state/drafts").deny - assert not outcome(project, "PowerShell", command="Move-Item state/drafts archive").deny - - -@pytest.mark.parametrize("command", [ - "cd state/mission; Set-Content ask-1.md answer", - "Set-Location -LiteralPath state/mission; Add-Content ask-1.md answer", - "cd state/mission; echo answer > ask-1.md", - "cd state/mission; cd ../..; cd state/mission; Set-Content ask-1.md answer", - "cd state/mission; python - <<'PY'\nfrom pathlib import Path\nPath('ask-1.md').write_text('x')\nPY", -]) -def test_literal_directory_changes_resolve_following_targets(project, command): - assert outcome(project, "PowerShell", command=command).deny - - -@pytest.mark.parametrize("command", [ - "cat state/mission/ask-1.md", "Get-Content state/mission/questions/ask-1.json", - "cat state/mission/questions/ask-1.json > state/mission/draft.json", - "cp state/mission/ask-1.md state/mission/draft.md", - "Copy-Item -LiteralPath state/mission/ask-1.md -Destination state/mission/draft.md", - "echo '>' state/mission/ask-1.md", - "cd state/mission/details; Set-Content ask-1.md draft", - "cat > draft.py <<'PY'\nfrom pathlib import Path\nPath('state/mission/ask-1.md').write_text('example')\nPY", - "@'\nfrom pathlib import Path\nPath('state/mission/ask-1.md').write_text('example')\n'@ | Set-Content draft.py", - "python - <<'PY'\nfrom pathlib import Path\np=Path('state/mission/questions/ask-1.json'); s=p.read_text(); Path('draft.json').write_text(s)\nPY", - "python - <<'PY'\nfrom pathlib import Path\np=Path('state/mission/ask-1.md'); s=p.read_text(); p=Path('draft.md'); p.write_text(s)\nPY", -]) -def test_reads_and_read_to_external_draft_allowed(project, command): - assert not outcome(project, "Bash", command=command).deny - - -def test_move_and_copy_to_mission_directory_uses_actual_destination_filename(project): - mission = project / "state" / "mission" - mission.mkdir(parents=True) - (mission / "ask-1.md").write_text("question", encoding="utf-8") - (project / "draft.json").write_text("{}", encoding="utf-8") - for executable in ("Move-Item", "Copy-Item", "mv", "cp"): - assert not outcome(project, "PowerShell", command=f"{executable} draft.json state/mission").deny - assert outcome(project, "PowerShell", command=f"{executable} ask-1.md state/mission").deny - - -@pytest.mark.parametrize("action", ["publish --input draft.json", "answer ask-1.md --input reply.json", "restore --input draft.json --source history.json --expect-revision 1 --expect-sha256 abc", "render ask-1.md"]) -@pytest.mark.parametrize("skill,runtime,tool", [ - ("skills/mission/SKILL.md", "claude", "Bash"), - ("codex/skills/chef-mission/SKILL.md", "codex", "PowerShell"), - ("grok/skills/chef-mission/SKILL.md", "grok", "run_terminal_command"), -]) -def test_documented_cli_and_appended_direct_write(project, action, skill, runtime, tool): - instructions = (PLUGIN_ROOT / skill).read_text(encoding="utf-8") - assert 'python "/chef_cli.py"' in instructions - assert f"`--runtime {runtime}`" in instructions - script = PLUGIN_ROOT / "chef_cli.py" - assert script.is_file() - command = f'python "{script}" question {action} --runtime {runtime} --project "{project}" --mission mission' - - assert not outcome(project, tool, runtime=runtime, command=command).deny - assert outcome(project, tool, runtime=runtime, command=command + " > state/mission/ask-1.md").deny - combined = command + "; echo answer > state/mission/questions/ask-1.json" - assert outcome(project, tool, runtime=runtime, command=combined).deny - - -def test_nonbundled_question_cli_writes_denied_but_reads_allowed(project): - reason = outcome(project, "Bash", command="python other/mission_state.py question answer ask-1.md --input reply.json").deny - assert str(project / "other" / "mission_state.py") in reason - assert question_write_guard.BUNDLED_CLI in reason - assert not outcome(project, "Bash", command="python other/mission_state.py question show ask-1.md").deny - - -def test_allow_once_does_not_override_question_protection(project): - state = project / "state" - folder = state / "mission" - folder.mkdir(parents=True) - (state / "ACTIVE").write_text('{"id":"mission","session":"owner"}', encoding="utf-8") - command = "echo answer > state/mission/ask-1.md" - (folder / "allow-once").write_text(command + "\n", encoding="utf-8") - reason = outcome(project, "Bash", command=command).deny - assert reason - assert "허용 파일:" not in reason - assert (folder / "allow-once").read_text(encoding="utf-8") == command + "\n" - - -def test_coordinator_guard_still_runs(project): - (project / "state").mkdir(exist_ok=True) - (project / "state" / "ACTIVE").write_text('{"id":"mission","session":"owner"}', encoding="utf-8") - payload = {"cwd": str(project), "session_id": "owner", "tool_name": "Write", "tool_input": {"file_path": "src/app.py"}} - reason = mission_guard.decide(payload).deny - assert "roles.implement" in reason - assert "허용 파일:" not in reason - payload["tool_input"]["file_path"] = "state/mission/report.md" - assert not mission_guard.decide(payload).deny - - -def test_unavailable_target_registry_does_not_skip_existing_shell_deny(project, tmp_path, monkeypatch): - adapter_path = project / ".claude" / "orchestrator" / "adapter.json" - adapter = json.loads(adapter_path.read_text(encoding="utf-8")) - adapter["guard"]["deny"] = [{"pattern": "^p4 submit", "reason": "blocked submit"}] - adapter_path.write_text(json.dumps(adapter), encoding="utf-8") - (project / "state").mkdir(exist_ok=True) - (project / "state" / "ACTIVE").write_text('{"id":"mission","session":"owner"}', encoding="utf-8") - registry = tmp_path / "broken-registry" - registry.mkdir() - (registry / "projects.json").write_text("{broken", encoding="utf-8") - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - result = outcome(project, "Bash", command=f'cp draft.md "{tmp_path / "external.md"}"; p4 submit') - assert "blocked submit" in result.deny - - -def test_bad_registry_cannot_discard_valid_local_question_context(project, tmp_path, monkeypatch): - registry = tmp_path / "broken-registry" - registry.mkdir() - (registry / "projects.json").write_text("{broken", encoding="utf-8") - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(registry)) - command = f'echo draft > "{tmp_path / "external.md"}"; echo answer > state/mission/ask-1.md' - assert outcome(project, "Bash", command=command).deny - patch = f"*** Begin Patch\n*** Add File: {tmp_path / 'external.md'}\n+draft\n*** Delete File: state/mission/ask-1.md\n*** End Patch" - assert outcome(project, "apply_patch", command=patch).deny - - -@pytest.mark.parametrize("source", [ - "print('state/mission/ask-1.md'.replace('old.md', 'new.md'))", - "value='state/mission/ask-1.md'; print(value.replace('ask', 'confirm'))", - "value='state/mission/ask-1.md'; alias=value; alias.replace('x', 'state/mission/confirm-A.md')", - "from pathlib import Path\np=Path('state/mission/ask-1.md'); p='state/mission/ask-1.md'; p.replace('ask', 'confirm')", - "def replace(a, b): return a\nreplace('state/mission/ask-1.md', 'state/mission/confirm-A.md')", - "value = 2 > 'state/mission/ask-1.md'", - "value = 2 >= 'state/mission/questions/ask-1.json'", -]) -@pytest.mark.parametrize("shell", ["Bash", "PowerShell"]) -def test_python_strings_and_comparisons_are_not_file_operations(project, source, shell): - if shell == "Bash": - command = f"python - <<'PY'\n{source}\nPY" - else: - command = f"@'\n{source}\n'@ | python -" - assert not outcome(project, shell, command=command).deny - - -@pytest.mark.parametrize("source", [ - "from pathlib import Path as P\np=P('state/mission/ask-1.md'); p.replace('draft.md')", - "import pathlib as paths\np=paths.Path('state/mission/ask-1.md'); q=p; q.rename('draft.md')", - "import os as files\nfiles.replace('state/mission/ask-1.md', 'draft.md')", - "from os import replace as relocate\nrelocate('draft.md', 'state/mission/ask-1.md')", - "import os\nrelocate=os.replace; relocate('state/mission/ask-1.md', 'draft.md')", - "import shutil as files\nfiles.move('state/mission/ask-1.md', 'draft.md')", - "from shutil import rmtree as remove_tree\nremove_tree('state/mission/questions')", - "from os.path import join as path_join\nopen(path_join('state', 'mission', 'ask-1.md'), 'w')", - "from pathlib import Path\nPath.replace(Path('state/mission/ask-1.md'), 'draft.md')", - "from pathlib import Path as P\nP.rename(P('state/mission/ask-1.md'), 'draft.md')", - "import pathlib as paths\npaths.Path.open(paths.Path('state/mission/ask-1.md'), 'w')", - "from pathlib import Path\nPath.unlink(Path('state/mission/ask-1.md'))", - "from pathlib import Path\nPath.write_text(Path('state/mission/ask-1.md'), 'answer')", - "from pathlib import Path\nrelocate=Path.replace; relocate(Path('state/mission/ask-1.md'), 'draft.md')", -]) -def test_python_filesystem_receiver_and_callable_aliases_stay_protected(project, source): - assert outcome(project, "Bash", command=f"python - <<'PY'\n{source}\nPY").deny - - -@pytest.mark.parametrize("command", [ - "python - <<'PY' > state/mission/ask-1.md\nprint(2 > 1)\nPY", - "python - <<'PY'\nprint(2 > 1)\nPY\necho answer > state/mission/ask-1.md", - "@'\nprint(2 > 1)\n'@ | python - > state/mission/ask-1.md", - "@'\nprint(2 > 1)\n'@ | python -; Set-Content state/mission/ask-1.md answer", - 'python - < state/mission/ask-1.md)"\nPY', - '@"\nvalue="$(Set-Content state/mission/ask-1.md answer)"\n"@ | python -', -]) -def test_embedded_python_preserves_external_redirection_and_shell_substitutions(project, command): - assert outcome(project, "PowerShell" if command.startswith("@") else "Bash", command=command).deny - - -@pytest.mark.parametrize("command", [ - "python - <<'PY'\nvalue='$(echo answer > state/mission/ask-1.md)'\nPY", - "@'\nvalue='$(Set-Content state/mission/ask-1.md answer)'\n'@ | python -", -]) -def test_literal_embedded_shell_syntax_is_data(project, command): - assert not outcome(project, "PowerShell" if command.startswith("@") else "Bash", command=command).deny - - -@pytest.mark.parametrize("command", [ - '@"\nx=2\nprint(x>15)\n"@ | python -', - '@"\nx=2\nprint(x > "state/mission/ask-1.md")\n"@ | python -', - 'python - < state/mission/ask-1.md)"\nPY', -]) -def test_interpolating_python_bodies_do_not_execute_bare_groups(project, command): - shell = "PowerShell" if command.startswith("@") else "Bash" - targets, trees = question_write_guard.shell_targets(command, shell, str(project), mission_guard) - assert targets == [] and trees == [] - assert not outcome(project, shell, command=command).deny - - -def test_tool_cwd_outside_owner_project_retains_original_mission_context(project, tmp_path): - target = project / "state/mission/ask-1.md" - fields = {"han_runtime": "codex", "session_id": "owner", "cwd": str(project), "tool_name": "Bash", - "tool_input": {"cwd": str(tmp_path), "command": f'echo answer > "{target}"'}} - assert mission_guard.decide(fields).deny - fields["session_id"] = "unrelated" - assert not mission_guard.decide(fields).deny - - -def test_grok_child_question_writes_require_valid_owner_and_nonempty_session(project): - fields = {"han_runtime": "grok", "subagentType": "chef:dev-medium", "sessionId": "child", "cwd": str(project), - "toolName": "write", "toolInput": {"path": "state/mission/ask-1.md"}} - assert mission_guard.decide(fields).deny - fields["sessionId"] = "" - assert not mission_guard.decide(fields).deny diff --git a/tests/integration/hooks/test_session_rules.py b/tests/integration/hooks/test_session_rules.py deleted file mode 100644 index 14dfd7e..0000000 --- a/tests/integration/hooks/test_session_rules.py +++ /dev/null @@ -1,242 +0,0 @@ -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest - -from tests.paths import PLUGIN_ROOT - -HOOKS_DIR = (PLUGIN_ROOT / 'hooks') - -from chef.runtimes import session as session_rules - -SCRIPT = HOOKS_DIR / "session_rules.py" -CLEARED_ENV = ( - "CLAUDE_ENV_FILE", "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "HAN_ADAPTERS_DIR", - "GROK_HOOK_EVENT", "GROK_SESSION_ID", -) -SUBAGENT_START = {"hook_event_name": "SubagentStart", "agent_id": "a1"} - - -def run_hook(env=None, payload=None, raw=None): - base = {k: v for k, v in os.environ.items() if k not in CLEARED_ENV} - base.update(env or {}) - if raw is None: - stdin = json.dumps(payload or {}).encode("utf-8") - else: - stdin = raw - result = subprocess.run( - [sys.executable, "-B", str(SCRIPT)], input=stdin, capture_output=True, env=base, timeout=30 - ) - assert result.returncode == 0 - text = result.stdout.decode("ascii").strip() - if text: - return json.loads(text) - return {} - - -@pytest.mark.parametrize("raw", [b"", b"not json", b"[1]", b'{}']) -def test_invalid_or_empty_payload_outputs_nothing(raw): - assert run_hook(raw=raw) == {} - - -@pytest.mark.parametrize("event", ["SubagentStart", "Other", 5, ["SessionStart"]]) -def test_other_events_do_not_export_paths(tmp_path, event): - assert run_hook(registry_env(tmp_path), {"hook_event_name": event, "transcript_path": "C:/session.jsonl"}) == {} - assert env_lines(tmp_path) == [] - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -@pytest.mark.parametrize("value", ["on", "shared"]) -def test_legacy_rule_options_never_read_or_inject_files(tmp_path, monkeypatch, runtime, value): - monkeypatch.delenv("CLAUDE_ENV_FILE", raising=False) - rules = tmp_path / "rules" - rules.mkdir() - (rules / "personal-rules.md").write_bytes(b"\xff\xfe") - monkeypatch.setenv("CLAUDE_PLUGIN_ROOT", str(tmp_path)) - monkeypatch.setenv("GROK_PLUGIN_ROOT", str(tmp_path)) - monkeypatch.setenv("CLAUDE_PLUGIN_OPTION_INJECT_RULES", value) - monkeypatch.setenv(f"HAN_{runtime.upper()}_INJECT_RULES", value) - monkeypatch.setenv("HAN_RULES_DISABLE", "0") - assert session_rules.decide({"hook_event_name": "SessionStart"}, runtime) == {} - assert session_rules.decide(SUBAGENT_START, runtime) == {} - - -def test_plugin_no_longer_distributes_rules_or_injection_option(): - manifest = json.loads((HOOKS_DIR.parent / ".claude-plugin/plugin.json").read_text(encoding="utf-8")) - assert set(manifest["userConfig"]) == {"adapters_dir"} - for folder in (HOOKS_DIR.parent / "rules", HOOKS_DIR.parent / "codex/rules"): - assert not list(folder.glob("*.md")) - - -def test_hooks_do_not_register_subagent_start(): - for path in (HOOKS_DIR / "hooks.json", HOOKS_DIR.parent / "codex/hooks.json"): - assert "SubagentStart" not in json.loads(path.read_text(encoding="utf-8"))["hooks"] - - -def registry_env(tmp_path, value=r"D:\Work\adapters"): - return {"CLAUDE_ENV_FILE": str(tmp_path / "env.sh"), "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR": value} - - -def env_lines(tmp_path): - path = tmp_path / "env.sh" - return path.read_text(encoding="utf-8").splitlines() if path.exists() else [] - - -def test_session_start_exports_registry_dir_to_env_file(tmp_path): - output = run_hook(registry_env(tmp_path)) - assert env_lines(tmp_path) == ['export HAN_ADAPTERS_DIR="D:/Work/adapters"'] - assert "systemMessage" not in output - - -def test_export_appends_after_existing_lines_and_is_not_repeated(tmp_path): - (tmp_path / "env.sh").write_text("export OTHER=1\n", encoding="utf-8") - run_hook(registry_env(tmp_path)) - run_hook(registry_env(tmp_path)) - assert env_lines(tmp_path) == ["export OTHER=1", 'export HAN_ADAPTERS_DIR="D:/Work/adapters"'] - - -def test_export_escapes_quote_dollar_and_backtick(tmp_path): - run_hook(registry_env(tmp_path, r'C:\a "b"\$x\`y')) - assert env_lines(tmp_path) == [r'export HAN_ADAPTERS_DIR="C:/a \"b\"/\$x/\`y"'] - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX literal backslash filename") -def test_posix_export_preserves_literal_backslash_and_shell_metacharacters(tmp_path): - value = str(tmp_path / 'folder\\name "quoted" $literal `literal`') - line = session_rules.export_line("HAN_TRANSCRIPT", value) - result = subprocess.run(["/bin/sh", "-c", line + '; printf %s "$HAN_TRANSCRIPT"'], - capture_output=True, text=True, timeout=10) - assert result.returncode == 0, result.stderr - assert result.stdout == value - - -@pytest.mark.parametrize( - "case", - ["no_env_file", "empty_option", "han_env_already_set", "no_option"], -) -def test_export_is_skipped(tmp_path, case): - env = registry_env(tmp_path) - if case == "no_env_file": - del env["CLAUDE_ENV_FILE"] - elif case == "empty_option": - env["CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR"] = " " - elif case == "han_env_already_set": - env["HAN_ADAPTERS_DIR"] = "E:/already" - else: - del env["CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR"] - run_hook(env) - assert env_lines(tmp_path) == [] - - -def test_subagent_start_does_not_touch_env_file(tmp_path): - run_hook(registry_env(tmp_path), payload=SUBAGENT_START) - assert env_lines(tmp_path) == [] - - -def test_export_still_happens_when_rules_are_disabled(tmp_path): - output = run_hook({**registry_env(tmp_path), "HAN_RULES_DISABLE": "1"}) - assert output == {} - assert len(env_lines(tmp_path)) == 1 - - -def test_export_write_failure_warns(tmp_path): - folder = tmp_path / "env.sh" - folder.mkdir() - output = run_hook(registry_env(tmp_path)) - assert "HAN_ADAPTERS_DIR" in output["systemMessage"] - assert "CLAUDE_ENV_FILE" in output["systemMessage"] - - -def transcript_payload(path=r"C:\Users\example\.claude\projects\p\s1.jsonl"): - return {"hook_event_name": "SessionStart", "transcript_path": path} - - -def transcript_env(tmp_path): - return {"CLAUDE_ENV_FILE": str(tmp_path / "env.sh")} - - -def test_session_start_exports_transcript_path_to_env_file(tmp_path): - output = run_hook(transcript_env(tmp_path), payload=transcript_payload()) - assert env_lines(tmp_path) == ['export HAN_TRANSCRIPT="C:/Users/example/.claude/projects/p/s1.jsonl"'] - assert "systemMessage" not in output - - -def test_transcript_export_is_not_repeated_for_same_path(tmp_path): - run_hook(transcript_env(tmp_path), payload=transcript_payload()) - run_hook(transcript_env(tmp_path), payload=transcript_payload()) - assert len(env_lines(tmp_path)) == 1 - - -def test_transcript_export_appends_for_different_path_even_if_env_already_set(tmp_path): - env = {**transcript_env(tmp_path), "HAN_TRANSCRIPT": "C:/old.jsonl"} - run_hook(env, payload=transcript_payload("C:/old.jsonl")) - run_hook(env, payload=transcript_payload("C:/new.jsonl")) - assert env_lines(tmp_path) == ['export HAN_TRANSCRIPT="C:/old.jsonl"', 'export HAN_TRANSCRIPT="C:/new.jsonl"'] - - -@pytest.mark.parametrize("payload", [{}, {"transcript_path": ""}, {"transcript_path": " "}, {"transcript_path": 5}]) -def test_transcript_export_is_skipped_without_usable_path(tmp_path, payload): - run_hook(transcript_env(tmp_path), payload=payload) - assert env_lines(tmp_path) == [] - - -def test_transcript_export_is_skipped_without_env_file(tmp_path): - output = run_hook(payload=transcript_payload()) - assert "systemMessage" not in output - assert env_lines(tmp_path) == [] - - -def test_transcript_export_still_happens_when_rules_are_disabled(tmp_path): - output = run_hook({**transcript_env(tmp_path), "HAN_RULES_DISABLE": "1"}, payload=transcript_payload()) - assert output == {} - assert len(env_lines(tmp_path)) == 1 - - -def test_transcript_export_is_skipped_for_codex(tmp_path, monkeypatch): - monkeypatch.setenv("CLAUDE_ENV_FILE", str(tmp_path / "env.sh")) - session_rules.decide(transcript_payload(), "codex") - assert env_lines(tmp_path) == [] - - -def test_subagent_start_does_not_export_transcript_path(tmp_path): - run_hook(transcript_env(tmp_path), payload={**SUBAGENT_START, "transcript_path": "C:/a.jsonl"}) - assert env_lines(tmp_path) == [] - - -def test_transcript_export_write_failure_warns(tmp_path): - (tmp_path / "env.sh").mkdir() - output = run_hook(transcript_env(tmp_path), payload=transcript_payload()) - assert "HAN_TRANSCRIPT" in output["systemMessage"] - assert "CLAUDE_ENV_FILE" in output["systemMessage"] - - -def test_hooks_json_registers_session_start_for_every_source(): - hooks = json.loads((HOOKS_DIR / "hooks.json").read_text(encoding="utf-8"))["hooks"] - group = hooks["SessionStart"][0] - assert set(group["matcher"].split("|")) >= {"startup", "resume", "clear", "compact"} - handler = group["hooks"][0] - assert "hooks/session_rules.py" in handler["command"] - assert "PreToolUse" in hooks - - -def test_all_runtime_and_marketplace_versions_match(): - manifest = json.loads((HOOKS_DIR.parent / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8")) - market = json.loads((HOOKS_DIR.parents[2] / ".claude-plugin" / "marketplace.json").read_text(encoding="utf-8")) - assert market["plugins"][0]["version"] == manifest["version"] - for folder in (".codex-plugin", ".grok-plugin"): - runtime = json.loads((HOOKS_DIR.parent / folder / "plugin.json").read_text(encoding="utf-8")) - assert runtime["version"] == manifest["version"] - hermes = (HOOKS_DIR.parent / "hermes" / "plugin.yaml").read_text(encoding="utf-8") - version = next(line.removeprefix("version:").strip() for line in hermes.splitlines() if line.startswith("version:")) - assert version == manifest["version"] - - -def test_plugin_json_declares_adapters_dir_user_config(): - manifest = json.loads((HOOKS_DIR.parent / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8")) - option = manifest["userConfig"]["adapters_dir"] - assert {"type", "title", "description"} <= set(option) - assert option["type"] == "string" - assert not option.get("sensitive") diff --git a/tests/integration/hooks/test_shared_allow_once_hooks.py b/tests/integration/hooks/test_shared_allow_once_hooks.py deleted file mode 100644 index 6efbb94..0000000 --- a/tests/integration/hooks/test_shared_allow_once_hooks.py +++ /dev/null @@ -1,94 +0,0 @@ -"""The source hook and a second generic participant share one native call.""" - -import json - -import pytest - -from chef.guards import allow_once as broker -from chef.guards import mission -from tests.integration.hooks.test_mission_guard import ( - NO_REGISTRY, PLUGIN_ROOT, SCRIPT, STATE, denial, make_active, make_adapter, - project, run_raw, write_allow_once, -) - - -def shared_fixture(project, monkeypatch, runtime, command): - make_adapter(project) - make_active(project, "m-demo") - adapter_path = project / ".claude/orchestrator/adapter.json" - data = json.loads(adapter_path.read_text(encoding="utf-8")) - data["guard"]["allowOnceParticipants"] = ["chef-mission", "alpha"] - adapter_path.write_text(json.dumps(data), encoding="utf-8") - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(NO_REGISTRY)) - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project)) - payload = { - "han_runtime": runtime, "session_id": "s1", "tool_use_id": "fixture-call", - "cwd": str(project), "tool_name": "Bash", - "tool_input": {"command": command, "shell": "pwsh" if runtime == "codex" else "bash"}, - } - located = mission.find_adapter(payload) - adapter = mission.load_adapter(located.adapter_path, runtime=runtime) - state = project / STATE - write_allow_once(project, "m-demo", [command]) - return payload, adapter, state - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -@pytest.mark.parametrize("command", ["p4 submit -c 17", "widget inspect"]) -@pytest.mark.parametrize("chef_first", [True, False]) -def test_source_hook_shared_with_generic_participant(project, monkeypatch, runtime, command, chef_first): - payload, adapter, state = shared_fixture(project, monkeypatch, runtime, command) - script = PLUGIN_ROOT / "codex/mission_guard.py" if runtime == "codex" else SCRIPT - - def chef(): - result = run_raw(json.dumps(payload).encode(), env_project=project, script=script) - assert result.returncode == 0, result.stderr.decode() - return json.loads(result.stdout or b"{}") - - def alpha(): - return broker.consume_shared_allow_once( - state, "m-demo", command, payload=payload, participant="alpha", - participants=adapter["guard"]["allowOnceParticipants"], active=mission.read_active(state), - config=broker.shared_once_context(adapter), - ) - - if chef_first: - assert not denial(chef()) - assert alpha() - else: - assert alpha() - assert not denial(chef()) - assert "already consumed" in denial(chef()) - with pytest.raises(broker.SharedAllowOnceError, match="already consumed"): - alpha() - assert (state / "m-demo/allow-once").read_bytes() == b"" - - -@pytest.mark.parametrize("protection", ["execution", "question", "worker"]) -def test_hard_protections_run_before_shared_consumption(project, monkeypatch, protection): - command = "p4 submit -c 17" - payload, _adapter, state = shared_fixture(project, monkeypatch, "claude", command) - if protection == "execution": - monkeypatch.setattr(mission, "execution_write_reason", lambda _payload: "fixture execution protection") - elif protection == "question": - monkeypatch.setattr(mission.question_write_guard, "question_write_reason", lambda *_args: "fixture question protection") - else: - from chef.workers import context - - payload["han_worker"] = True - monkeypatch.setattr(context, "denial", lambda _payload: "fixture worker protection") - before = (state / "m-demo/allow-once").read_bytes() - assert "fixture" in mission.decide(payload).deny - assert (state / "m-demo/allow-once").read_bytes() == before - assert not (state / "m-demo/allow-once.receipts").exists() - - -def test_normal_command_without_opt_in_keeps_legacy_token(project, monkeypatch): - make_adapter(project) - make_active(project, "m-demo") - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(NO_REGISTRY)) - monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project)) - token = write_allow_once(project, "m-demo", ["widget inspect"]) - payload = {"tool_name": "Bash", "tool_input": {"command": "widget inspect"}, "cwd": str(project), "session_id": "s1"} - assert not mission.decide(payload).deny - assert token.read_text(encoding="utf-8") == "widget inspect\n" diff --git a/tests/integration/hooks/test_stale_p4.py b/tests/integration/hooks/test_stale_p4.py deleted file mode 100644 index fc5f03a..0000000 --- a/tests/integration/hooks/test_stale_p4.py +++ /dev/null @@ -1,165 +0,0 @@ -import json -import os -import sys -import time -from pathlib import Path - -import pytest - -from tests.paths import PLUGIN_ROOT - -HOOKS_DIR = (PLUGIN_ROOT / 'hooks') - -from chef.guards import mission as mission_guard - -DAY = 24 * 3600 -P4_ADAPTER = { - "schema": 1, - "paths": {"stateDir": "state"}, - "guard": {"deny": [{"pattern": r"(?:^|\s)submit(?:\s|$)", "reason": "submit 금지"}], "p4Client": {"require": True}}, - "slots": {"root": "D:/Work/slots", "client": "ws_{name}", "mainClient": "ws_main"}, - "vars": {"main": "D:/Work/main"}, -} - - -def write_active(state, mission_id="m-1", session="s1", age=0.0): - state.mkdir(parents=True, exist_ok=True) - path = state / "ACTIVE" - path.write_text(json.dumps({"id": mission_id, "session": session, "openedAt": "2026-10-15T09:00:00+09:00"}), encoding="utf-8") - moment = time.time() - age - os.utime(path, (moment, moment)) - return path - - -def age_folder(folder, age): - moment = time.time() - age - for path in folder.rglob("*"): - os.utime(path, (moment, moment)) - - -def test_stale_hours_precedence(monkeypatch): - monkeypatch.delenv(mission_guard.STALE_ENV, raising=False) - assert mission_guard.stale_hours_of({}) == 24 - assert mission_guard.stale_hours_of({"mission": {"staleHours": 6}}) == 6 - assert mission_guard.stale_hours_of({"mission": {"staleHours": "x"}}) == 24 - monkeypatch.setenv(mission_guard.STALE_ENV, "0") - assert mission_guard.stale_hours_of({"mission": {"staleHours": 6}}) == 0 - - -def test_staleness_uses_newest_activity(tmp_path): - state = tmp_path / "state" - write_active(state, age=3 * DAY) - folder = state / "m-1" - folder.mkdir() - (folder / "mission.md").write_text("x", encoding="utf-8") - age_folder(folder, 3 * DAY) - active = mission_guard.read_active(str(state)) - result = mission_guard.staleness(str(state), active, 24) - assert result.stale and 71 < result.hours < 73 - assert "끊김 의심" in mission_guard.stale_text(result) - (folder / "note.md").write_text("fresh", encoding="utf-8") - assert not mission_guard.staleness(str(state), active, 24).stale - assert not mission_guard.staleness(str(state), active, 0).stale - - -def test_heartbeat_touches_only_own_session_and_never_resurrects(tmp_path): - state = tmp_path / "state" - path = write_active(state, age=DAY) - before = path.stat().st_mtime - mission_guard.heartbeat(str(state), {"session_id": "other"}) - assert path.stat().st_mtime == before - mission_guard.heartbeat(str(state), {"session_id": "s1"}) - assert path.stat().st_mtime > before + DAY / 2 - assert sorted(os.listdir(state)) == ["ACTIVE"] - path.unlink() - mission_guard.heartbeat(str(state), {"session_id": "s1"}) - assert not path.exists() - - -def test_open_denied_by_stale_active_mentions_force_close(tmp_path): - state = tmp_path / "state" - write_active(state, age=3 * DAY) - marker = mission_guard.MARKER.match("echo han-mission open m-2") - outcome = mission_guard.Outcome() - mission_guard.handle_marker(marker, str(state), "s2", outcome, stale_hours=24) - assert "다른 미션" in outcome.deny and "끊김 의심" in outcome.deny and "--force-close-stale" in outcome.deny - assert mission_guard.read_active(str(state)).id == "m-1" - - -def test_open_denied_by_live_active_has_no_stale_note(tmp_path): - state = tmp_path / "state" - write_active(state) - marker = mission_guard.MARKER.match("echo han-mission open m-2") - outcome = mission_guard.Outcome() - mission_guard.handle_marker(marker, str(state), "s2", outcome, stale_hours=24) - assert outcome.deny and "끊김" not in outcome.deny - - -@pytest.mark.parametrize( - "project, expected", - [("D:/Work/slots/slot2", "ws_slot2"), ("D:/Work/main", "ws_main"), ("D:/Elsewhere", "")], -) -def test_expected_p4_client(project, expected): - assert mission_guard.expected_p4_client(project, P4_ADAPTER) == expected - - -def test_expected_p4_client_from_p4config(tmp_path): - (tmp_path / ".p4config").write_text("P4PORT=x:1666\nP4CLIENT=ws_cfg\n", encoding="utf-8") - assert mission_guard.expected_p4_client(str(tmp_path), {}) == "ws_cfg" - - -def reason(command, project="D:/Work/slots/slot2", tool="Bash", adapter=P4_ADAPTER): - return mission_guard.judge_command(adapter, command, tool, [], project).reason - - -@pytest.mark.parametrize( - "command", - [ - "p4 sync", - "p4 edit -c 1 a.cs", - "p4 -x list.txt add", - "C:\\Perforce\\p4.exe reconcile -c 1 a", - "p4 -c ws_slot3 edit -c 1 a.cs", - "p4 -c ws_main sync", - "python p4c.py --client ws_slot1 sync", - "python p4c.py submit -c 1", - ], -) -def test_p4_writes_need_matching_client(command): - assert reason(command) != "", command - - -@pytest.mark.parametrize( - "command", - [ - "p4 -c ws_slot2 sync", - "p4 -cws_slot2 edit -c 1 a.cs", - "p4 -c WS_SLOT2 edit -c 1 a.cs", - "p4 -c $WS edit -c 1 a.cs", - "p4 opened -c 1", - "p4 changes -s pending", - "p4 change -o", - "p4 info", - "python p4c.py edit -c 1 a.cs", - 'python "D:/x y/p4c.py" --project D:/Work/slots/slot2 sync', - ], -) -def test_p4_reads_and_pinned_writes_pass(command): - assert reason(command) == "", command - - -def test_p4_policy_off_by_default(): - adapter = {key: value for key, value in P4_ADAPTER.items() if key != "guard"} - assert reason("p4 sync", adapter=adapter) == "" - - -def test_p4_policy_custom_commands(): - adapter = {**P4_ADAPTER, "guard": {"p4Client": {"require": True, "commands": ["submit"]}}} - assert reason("p4 sync", adapter=adapter) == "" - assert reason("p4 submit", adapter=adapter) != "" - - -def test_p4c_call_is_checked_as_p4(): - assert mission_guard.p4c_as_p4("python p4c.py --which", "D:/Work/slots/slot2", P4_ADAPTER) == "p4 -c ws_slot2" - assert mission_guard.p4c_as_p4("py -3 C:/h/p4c.py --client w edit a", "", {}) == "p4 -c w edit a" - assert mission_guard.p4c_as_p4("python other.py edit", "", {}) == "" diff --git a/tests/integration/hooks/test_subagent_allow.py b/tests/integration/hooks/test_subagent_allow.py deleted file mode 100644 index 1ac1f6b..0000000 --- a/tests/integration/hooks/test_subagent_allow.py +++ /dev/null @@ -1,313 +0,0 @@ -import json -import os -import subprocess -import sys -from pathlib import Path - -import pytest - -from tests.paths import PLUGIN_ROOT - -HOOKS = (PLUGIN_ROOT / 'hooks') -PLUGIN = HOOKS.parent - -from chef.guards import subagents as subagent_allow - -ADAPTER_DIRS = {"claude": ".claude", "codex": ".codex", "grok": ".grok"} -SPAWN = {"claude": "Agent", "codex": "collaborationspawn_agent", "grok": "spawn_subagent"} -TYPE_KEY = {"claude": "subagent_type", "codex": "agent_type", "grok": "subagent_type"} -ROLES = {"dev": "team-dev", "review": "chef:code-reviewer", "reviewLoopSkill": "team-loop-skill"} -ALLOW = {"allow": ["team-*", "chef:*"]} - - -@pytest.fixture(autouse=True) -def clean_env(monkeypatch): - for name in ("HAN_ADAPTERS_DIR", "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "GROK_HOOK_EVENT", "GROK_SESSION_ID", "GROK_WORKSPACE_ROOT"): - monkeypatch.delenv(name, raising=False) - - -def write_adapter(project, runtime, extra=None, local=None): - folder = project / ADAPTER_DIRS[runtime] / "orchestrator" - folder.mkdir(parents=True, exist_ok=True) - adapter = {"schema": 1, "project": "t", "paths": {"stateDir": "state"}, "roles": ROLES} - adapter.update(extra or {}) - (folder / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - if local is not None: - (folder / "local.json").write_text(local if isinstance(local, str) else json.dumps(local), encoding="utf-8") - return folder / "adapter.json" - - -def payload_of(project, runtime, name=None, tool_name=None, tool_input=None): - if tool_input is None: - tool_input = {"description": "x", "prompt": "y"} - if name is not None: - tool_input[TYPE_KEY[runtime]] = name - tool_name = tool_name or SPAWN[runtime] - if runtime == "grok": - return {"hookEventName": "pre_tool_use", "toolName": tool_name, "toolInput": tool_input, "cwd": str(project), "sessionId": "s"} - return {"hook_event_name": "PreToolUse", "tool_name": tool_name, "tool_input": tool_input, "cwd": str(project), "session_id": "s"} - - -def run_hook(project, runtime, payload): - script = PLUGIN / ("codex/subagent_allow.py" if runtime == "codex" else "hooks/subagent_allow.py") - env = dict(os.environ, PYTHONUTF8="1", CLAUDE_PROJECT_DIR=str(project)) - for name in ("HAN_ADAPTERS_DIR", "GROK_HOOK_EVENT", "GROK_SESSION_ID"): - env.pop(name, None) - done = subprocess.run([sys.executable, "-B", str(script)], input=json.dumps(payload).encode(), capture_output=True, timeout=20, env=env) - assert done.returncode == 0, done.stderr.decode("utf-8", "replace") - return json.loads(done.stdout or b"{}") - - -def decision(project, runtime, name=None, **kwargs): - return run_hook(project, runtime, payload_of(project, runtime, name, **kwargs)) - - -def denial(output): - specific = output.get("hookSpecificOutput", {}) - if specific.get("permissionDecision") == "deny": - return specific["permissionDecisionReason"] - return "" - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_matching_name_passes_and_other_name_is_denied(tmp_path, runtime): - write_adapter(tmp_path, runtime, {"agents": ALLOW}) - assert decision(tmp_path, runtime, "team-dev") == {} - assert decision(tmp_path, runtime, "chef:verifier") == {} - output = decision(tmp_path, runtime, "outsider") - reason = denial(output) - assert output["hookSpecificOutput"]["hookEventName"] == "PreToolUse" - assert "outsider" in reason and "team-*" in reason and "chef:*" in reason - assert "team-dev" in reason and "chef:code-reviewer" in reason - assert "team-loop-skill" not in reason - - -@pytest.mark.parametrize("runtime,default", [("claude", "general-purpose"), ("codex", "default"), ("grok", "general-purpose")]) -def test_omitted_name_is_judged_by_runtime_default(tmp_path, runtime, default): - write_adapter(tmp_path, runtime, {"agents": {"allow": ["team-*"]}}) - assert default in denial(decision(tmp_path, runtime, None)) - write_adapter(tmp_path, runtime, {"agents": {"allow": ["team-*", default]}}) - assert decision(tmp_path, runtime, None) == {} - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_blank_or_non_string_name_falls_back_to_default(tmp_path, runtime): - write_adapter(tmp_path, runtime, {"agents": {"allow": ["team-*"]}}) - for value in ("", " ", 3, None): - output = decision(tmp_path, runtime, tool_input={TYPE_KEY[runtime]: value}) - assert denial(output) - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_without_agents_key_or_adapter_passes(tmp_path, runtime): - assert decision(tmp_path, runtime, "anything") == {} - write_adapter(tmp_path, runtime) - assert decision(tmp_path, runtime, "anything") == {} - write_adapter(tmp_path, runtime, {"agents": {}}) - assert decision(tmp_path, runtime, "anything") == {} - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_allow_applies_regardless_of_active_mission(tmp_path, runtime): - write_adapter(tmp_path, runtime, {"agents": ALLOW}) - assert not (tmp_path / "state" / "ACTIVE").exists() - assert denial(decision(tmp_path, runtime, "outsider")) - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_empty_allow_denies_everything(tmp_path, runtime): - write_adapter(tmp_path, runtime, {"agents": {"allow": []}}) - assert denial(decision(tmp_path, runtime, "team-dev")) - - -@pytest.mark.parametrize("runtime", ["codex", "grok"]) -def test_runtime_overlay_replaces_top_level_allow(tmp_path, runtime): - write_adapter(tmp_path, runtime, {"agents": {"allow": ["team-*"]}, "runtimes": {runtime: {"agents": {"allow": ["other-*"]}}}}) - assert denial(decision(tmp_path, runtime, "team-dev")) - assert decision(tmp_path, runtime, "other-x") == {} - - -def test_claude_runtime_overlay_overrides_top_level(tmp_path): - write_adapter(tmp_path, "claude", {"agents": {"allow": ["team-*"]}, "runtimes": {"claude": {"agents": {"allow": ["other-*"]}}}}) - assert denial(decision(tmp_path, "claude", "team-dev")) - assert decision(tmp_path, "claude", "other-x") == {} - - -def test_local_json_overrides_adapter(tmp_path): - write_adapter(tmp_path, "claude", {"agents": {"allow": ["team-*"]}}, local={"agents": {"allow": ["local-*"]}}) - assert denial(decision(tmp_path, "claude", "team-dev")) - assert decision(tmp_path, "claude", "local-a") == {} - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_other_tools_are_not_checked(tmp_path, runtime): - write_adapter(tmp_path, runtime, {"agents": {"allow": []}}) - assert decision(tmp_path, runtime, "x", tool_name="Bash") == {} - assert decision(tmp_path, runtime, "x", tool_name="collaborationwait_agent") == {} - - -def test_claude_task_alias_is_checked(tmp_path): - write_adapter(tmp_path, "claude", {"agents": ALLOW}) - assert denial(decision(tmp_path, "claude", "outsider", tool_name="Task")) - - -def test_grok_accepts_task_alias_and_camel_case_type(tmp_path): - write_adapter(tmp_path, "grok", {"agents": ALLOW}) - assert denial(decision(tmp_path, "grok", "outsider", tool_name="Task")) - assert decision(tmp_path, "grok", tool_input={"subagentType": "team-dev"}) == {} - assert denial(decision(tmp_path, "grok", tool_input={"subagentType": "outsider"})) - - -def test_codex_matches_namespaced_spawn_tool_names(tmp_path): - write_adapter(tmp_path, "codex", {"agents": ALLOW}) - for tool in ("collaborationspawn_agent", "spawn_agent"): - assert denial(decision(tmp_path, "codex", "outsider", tool_name=tool)) - - -def test_pattern_match_is_case_sensitive_glob(): - assert subagent_allow.allows(["team-*"], "team-a") - assert subagent_allow.allows(["chef:?-dev"], "chef:x-dev") - assert not subagent_allow.allows(["team-*"], "Team-a") - assert not subagent_allow.allows(["team-*"], "xteam-a") - - -CHEF_DEFAULTS = ["chef:researcher", "chef:dev-medium", "chef:verifier", "chef:code-reviewer", "chef:reviewer-small"] - - -def test_role_names_skip_review_loop_skill_and_duplicates(): - adapter = {"roles": {"a": "team-a", "b": "team-a", "reviewLoopSkill": "skill", "c": 3, "d": ""}} - assert subagent_allow.role_names(adapter) == [*CHEF_DEFAULTS, "team-a"] - assert subagent_allow.role_names({}) == CHEF_DEFAULTS - - -def test_role_names_use_chef_defaults_for_missing_keys(): - adapter = {"roles": {"research": "team-research", "implement": "team-dev"}} - assert subagent_allow.role_names(adapter, "claude") == [ - "team-research", "team-dev", "chef:verifier", "chef:code-reviewer", "chef:reviewer-small"] - assert subagent_allow.role_names(adapter, "codex")[-1] == "chef:dev-small" - assert subagent_allow.role_names({"roles": {"review": "team-review"}})[3] == "team-review" - - -def test_role_names_implement_small_and_audit_follow_defaults(): - adapter = {"roles": {"implement": "team-dev", "review": "team-review"}} - claude = subagent_allow.role_names(adapter, "claude") - assert "chef:dev-small" not in claude and claude.count("team-dev") == 1 and claude.count("team-review") == 1 - assert "chef:dev-small" in subagent_allow.role_names(adapter, "grok") - explicit = {"roles": {"implementSmall": "team-small", "audit": "team-audit"}} - assert {"team-small", "team-audit"} <= set(subagent_allow.role_names(explicit)) - - -def test_role_names_map_legacy_names_and_grok_review_aliases(): - adapter = {"roles": {"research": "chef_researcher", "review": "code-reviewer", "verify": "chef_verifier"}} - claude = subagent_allow.role_names(adapter, "claude") - assert "chef_researcher" not in claude and "chef:researcher" in claude and "code-reviewer" in claude - grok = subagent_allow.role_names(adapter, "grok") - assert "code-reviewer" not in grok and "chef:code-reviewer" in grok - - -def test_deny_reason_lists_effective_names_and_says_not_to_substitute(tmp_path): - write_adapter(tmp_path, "claude", {"roles": {"research": "team-research"}, "agents": {"allow": ["team-*"]}}) - reason = denial(decision(tmp_path, "claude", "outsider")) - assert "chef:verifier" in reason and "team-research" in reason - assert "다른 에이전트로 대신하지 말고 사용자에게 알릴 것" in reason - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_json_string_tool_input_is_parsed(tmp_path, runtime): - write_adapter(tmp_path, runtime, {"agents": {"allow": ["team-*"]}}) - assert decision(tmp_path, runtime, tool_input=json.dumps({TYPE_KEY[runtime]: "team-dev"})) == {} - assert denial(decision(tmp_path, runtime, tool_input=json.dumps({TYPE_KEY[runtime]: "outsider"}))) - assert denial(decision(tmp_path, runtime, tool_input=json.dumps({"prompt": "x"}))) - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -@pytest.mark.parametrize("tool_input", ["{broken", "[1]"]) -def test_unreadable_tool_input_passes_with_notice(tmp_path, runtime, tool_input): - write_adapter(tmp_path, runtime, {"agents": {"allow": ["team-*"]}}) - output = decision(tmp_path, runtime, tool_input=tool_input) - assert not denial(output) - assert output["systemMessage"].startswith("서브에이전트 허용 목록 꺼짐") - - -def test_grok_truncated_input_passes_with_notice(tmp_path): - write_adapter(tmp_path, "grok", {"agents": {"allow": ["team-*"]}}) - payload = payload_of(tmp_path, "grok", "outsider") - payload["toolInputTruncated"] = True - output = run_hook(tmp_path, "grok", payload) - assert not denial(output) - assert "잘려" in output["systemMessage"] - - -@pytest.mark.parametrize("agents", ["team-*", ["team-*"], {"allow": "team-*"}, {"allow": ["team-*", 3]}, {"allow": [""]}]) -def test_malformed_allow_passes_with_notice(tmp_path, agents): - write_adapter(tmp_path, "claude", {"agents": agents}) - output = decision(tmp_path, "claude", "outsider") - assert not denial(output) - assert output["systemMessage"].startswith("서브에이전트 허용 목록 꺼짐") - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_unreadable_adapter_passes_with_notice(tmp_path, runtime): - folder = write_adapter(tmp_path, runtime, {"agents": ALLOW}) - folder.write_text("{broken", encoding="utf-8") - output = decision(tmp_path, runtime, "outsider") - assert not denial(output) - assert output["systemMessage"].startswith("서브에이전트 허용 목록 꺼짐") - - -def test_broken_runtimes_overlay_passes_with_notice(tmp_path): - write_adapter(tmp_path, "codex", {"agents": ALLOW, "runtimes": {"codex": "bad"}}) - output = decision(tmp_path, "codex", "outsider") - assert not denial(output) - assert "꺼짐" in output["systemMessage"] - - -def test_broken_local_json_is_reported_when_allow_applies(tmp_path): - write_adapter(tmp_path, "claude", {"agents": ALLOW}, local="{broken") - output = decision(tmp_path, "claude", "outsider") - assert denial(output) - assert "local.json" in output["systemMessage"] - - -def test_invalid_stdin_passes_without_output(tmp_path): - script = PLUGIN / "hooks/subagent_allow.py" - done = subprocess.run([sys.executable, "-B", str(script)], input=b"not json", capture_output=True, timeout=20) - assert done.returncode == 0 - assert json.loads(done.stdout)["systemMessage"].startswith("서브에이전트 허용 목록 꺼짐") - - -def test_output_is_ascii_json(tmp_path): - write_adapter(tmp_path, "claude", {"agents": ALLOW}) - script = PLUGIN / "hooks/subagent_allow.py" - env = dict(os.environ, CLAUDE_PROJECT_DIR=str(tmp_path)) - done = subprocess.run([sys.executable, "-B", str(script)], input=json.dumps(payload_of(tmp_path, "claude", "outsider")).encode(), - capture_output=True, timeout=20, env=env) - done.stdout.decode("ascii") - - -def registered(path, key): - hooks = json.loads(path.read_text(encoding="utf-8"))["hooks"]["PreToolUse"] - return [entry for entry in hooks if "subagent_allow.py" in json.dumps(entry)], hooks, key - - -def test_claude_and_grok_share_hooks_json_registration(): - entries, hooks, _ = registered(PLUGIN / "hooks/hooks.json", "claude") - assert len(entries) == 1 - matcher = entries[0]["matcher"].split("|") - assert {"Agent", "Task", "spawn_subagent"} == set(matcher) - assert "hooks/subagent_allow.py" in entries[0]["hooks"][0]["command"] - assert "mission_guard.py" in json.dumps(hooks[0]) - assert not any(tool in hooks[0]["matcher"].split("|") for tool in matcher) - - -def test_codex_hooks_json_registers_spawn_agent_matcher(): - import re - - entries, hooks, _ = registered(PLUGIN / "codex/hooks.json", "codex") - assert len(entries) == 1 - matcher = entries[0]["matcher"] - assert re.fullmatch(matcher, "collaborationspawn_agent") - assert not re.fullmatch(matcher, "Bash") - assert "codex/subagent_allow.py" in entries[0]["hooks"][0]["command"] - assert "mission_guard.py" in json.dumps(hooks[0]) - assert (PLUGIN / "codex/subagent_allow.py").is_file() diff --git a/tests/integration/mission/test_chaos.py b/tests/integration/mission/test_chaos.py deleted file mode 100644 index f841076..0000000 --- a/tests/integration/mission/test_chaos.py +++ /dev/null @@ -1,235 +0,0 @@ -from pathlib import Path - -from tests.paths import PLUGIN_ROOT - -"""Bounded, synthetic fault injection; no runtime CLI, adapter registry or server. - -Workers only import local Python modules and write under pytest's temporary root. -They never spawn descendants; the fixture reaps every worker even on assertion failure. -Resource locks deliberately require operator recovery after a killed holder. -""" - -import json -import os -import subprocess -import sys -import time -from pathlib import Path - -import pytest -from tests.transition_support import run_lifecycle_hook -from chef.mission import state as mission_state -from chef.verification import runner as verification -from test_verification import ( # Reuse synthetic mission helpers. - mission, - review, - verify, -) - -slots = verification.locking -PLUGIN = PLUGIN_ROOT - -WORKER = r""" -import os, sys, time -from pathlib import Path -sys.path.insert(0, sys.argv[1]) -import verification -mode, directory, label = sys.argv[2:] -root = Path(directory) -lock_type = verification.ResourceLock if mode == 'resource' else verification.locking.FileLock -if mode == 'counter': - (root / (label + '.ready')).touch() - deadline = time.monotonic() + 15 - while not (root / 'go').exists(): - if time.monotonic() > deadline: - raise RuntimeError('parent never released start gate') - time.sleep(.01) - for _ in range(8): - with lock_type(str(root / 'shared.lock'), 'counter', timeout=15): - counter = root / 'counter' - value = int(counter.read_text()) if counter.exists() else 0 - with (root / 'events').open('a') as log: - log.write(f'enter {label}\n') - log.flush() - time.sleep(.005) - counter.write_text(str(value + 1)) - log.write(f'exit {label}\n') -else: - with lock_type(str(root / 'shared.lock'), 'holder'): - (root / (label + '.ready')).touch() - time.sleep(30) -""" - - -@pytest.fixture(autouse=True) -def isolated_chaos_environment(tmp_path, monkeypatch): - home = tmp_path / 'home' - home.mkdir() - for key in ('HOME', 'USERPROFILE', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'GROK_HOME', - 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME'): - monkeypatch.setenv(key, str(home / key.lower())) - for key in ('CLAUDE_PROJECT_DIR', 'CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR', 'HAN_REPO', - 'GROK_HOOK_EVENT', 'GROK_SESSION_ID', 'GROK_WORKSPACE_ROOT', 'HAN_GUARD_LOG'): - monkeypatch.delenv(key, raising=False) - monkeypatch.setenv('HAN_ADAPTERS_DIR', str(tmp_path / 'empty-registry')) - monkeypatch.setenv('PYTHONUTF8', '1') - monkeypatch.setenv('PYTHONIOENCODING', 'utf-8') - monkeypatch.chdir(tmp_path) - - -@pytest.fixture -def workers(tmp_path): - children = [] - - def start(mode, label): - process = subprocess.Popen( - [sys.executable, '-B', '-c', WORKER, str((PLUGIN_ROOT / 'skills/mission/scripts')), mode, str(tmp_path), label], - cwd=tmp_path, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, - ) - children.append(process) - return process - - try: - yield start - finally: - for process in children: - if process.poll() is None: - process.kill() - process.communicate(timeout=10) - - -def await_ready(tmp_path, labels, children): - deadline = time.monotonic() + 15 - while not all((tmp_path / (label + '.ready')).exists() for label in labels): - assert all(child.poll() is None for child in children), 'worker exited before readiness' - assert time.monotonic() < deadline, 'worker readiness timed out' - time.sleep(.01) - - -def test_real_process_contention_preserves_critical_sections(tmp_path, workers): - labels = ['one', 'two', 'three', 'four'] - children = [workers('counter', label) for label in labels] - await_ready(tmp_path, labels, children) - (tmp_path / 'go').touch() - for child in children: - _, errors = child.communicate(timeout=25) - assert child.returncode == 0, errors.decode('utf-8', errors='replace') - assert (tmp_path / 'counter').read_text() == '32' - events = (tmp_path / 'events').read_text().splitlines() - assert len(events) == 64 - for enter, exit_ in zip(events[::2], events[1::2]): - assert enter.startswith('enter ') - assert exit_ == enter.replace('enter ', 'exit ', 1) - assert not (tmp_path / 'shared.lock').exists() - - -@pytest.mark.parametrize('mode', ['slot', 'resource']) -def test_killed_lock_holder_has_explicit_recovery_contract(tmp_path, workers, mode): - child = workers(mode, 'holder') - await_ready(tmp_path, ['holder'], [child]) - path = tmp_path / 'shared.lock' - lock_type = verification.ResourceLock if mode == 'resource' else slots.FileLock - original = path.read_bytes() - with pytest.raises(slots.LockBusy): - with lock_type(str(path), 'live contender'): - pytest.fail('a live holder must exclude contenders') - assert path.read_bytes() == original - child.kill() - child.communicate(timeout=10) - assert not slots.process_alive(child.pid) - if mode == 'resource': - # Killing the Python owner says nothing about an external editor's lifetime. - # Preserve the stale evidence until an operator has checked that resource. - with pytest.raises(verification.VerificationError) as failure: - with verification.resource_locks({'resourceDir': str(tmp_path), 'resources': ['shared']}): - pytest.fail('resource ownership must fail closed') - assert failure.value.category == 'resource_busy' - assert path.read_bytes() == original - path.unlink() # Simulated operator recovery, only inside this synthetic root. - with lock_type(str(path), 'recovered'): - assert path.read_text().startswith(str(os.getpid()) + '\t') - assert not path.exists() - - -@pytest.mark.parametrize('damage', ['header', 'truncated-row']) -def test_corrupt_mission_state_blocks_transition_without_overwrite(mission, damage): - _, folder, _ = mission - path = folder / 'units.tsv' - if damage == 'header': - path.write_text('unrecognized\n', encoding='utf-8') - else: - path.write_text(path.read_text(encoding='utf-8').splitlines()[0] + '\nM1\tbroken\n', encoding='utf-8') - corrupted = path.read_bytes() - assert mission_state.main(['unit', 'set', 'M1', '--goal', 'Updated synthetic goal']) != 0 - assert path.read_bytes() == corrupted - - -@pytest.mark.parametrize('damage', ['json', 'status', 'snapshot', 'logHash', 'steps']) -def test_damaged_receipt_cannot_complete_or_write_pass_ledger(mission, damage): - root, folder, _ = mission - code, receipt = verify(mission) - assert code == 0 - clean_review = review(mission, receipt) - value = json.loads(receipt.read_text(encoding='utf-8')) - verification.validate_receipt(root, folder, 'M1', value, - settings={'grades': ['pytest-pass', 'editmode-pass']}) - verification.validate_review(folder, 'M1', receipt, clean_review) - if damage == 'json': - receipt.write_text('{"status":', encoding='utf-8') - else: - value[damage] = {'status': 'fail', 'snapshot': {}, 'logHash': 'tampered', 'steps': []}[damage] - receipt.write_text(json.dumps(value), encoding='utf-8') - ledger = folder / 'ledger.tsv' - before = ledger.read_bytes() - assert mission_state.main(['complete', 'M1', '--receipt', str(receipt), - '--review', str(clean_review), '--done-evidence', 'Synthetic check passed']) != 0 - assert ledger.read_bytes() == before - - -@pytest.mark.parametrize('runtime', ['claude', 'codex', 'grok']) -def test_runtime_guard_owner_and_child_contract_in_real_hook_process(tmp_path, runtime): - root = tmp_path / 'fictional-project' - adapter = root / f'.{runtime}/orchestrator/adapter.json' - adapter.parent.mkdir(parents=True) - adapter.write_text(json.dumps({'schema': 1, 'paths': {'stateDir': 'state'}, - 'guard': {'deny': [{'pattern': r'^p4\s+submit\b', 'reason': 'blocked'}]}}), - encoding='utf-8') - script = PLUGIN / ('codex/mission_guard.py' if runtime == 'codex' else 'hooks/mission_guard.py') - - def hook(command, session='owner', child=False): - payload = {'cwd': str(root)} - if runtime == 'grok': - payload.update(hookEventName='pre_tool_use', sessionId=session, - toolName='run_terminal_command', toolInput={'command': command, 'shell': 'bash'}) - if child: - payload['subagentType'] = 'developer' - else: - payload.update(hook_event_name='PreToolUse', session_id=session, - tool_name='Bash', tool_input={'command': command}) - if child: - payload.update(agent_id='child', agent_type='developer') - result = run_lifecycle_hook(script, payload, cwd=root, timeout=15) - assert result.returncode == 0, result.stderr - return json.loads(result.stdout or b'{}') - - def denied(value): - return value.get('hookSpecificOutput', {}).get('permissionDecision') == 'deny' - - assert not denied(hook('echo han-mission open garden')) - active = root / 'state/ACTIVE' - assert json.loads(active.read_text(encoding='utf-8'))['session'] == 'owner' - assert denied(hook('p4 submit -c 123')) - # Claude/Codex children carry the parent's session; Grok has a native child session. - child_session = 'child' if runtime == 'grok' else 'owner' - assert denied(hook('p4 submit -c 123', session=child_session, child=True)) - assert not denied(hook('p4 opened -c 123')) - assert not denied(hook('p4 submit -c 123', session='unrelated')) - before = active.read_bytes() - hook('echo han-mission close garden', session='unrelated') - assert active.read_bytes() == before - if runtime == 'grok': - # Grok identifies a native child independently of the owner session. - assert denied(hook('echo han-mission close garden', session=child_session, child=True)) - assert active.read_bytes() == before - assert not denied(hook('echo han-mission close garden')) - assert not active.exists() diff --git a/tests/integration/mission/test_check_human_doc.py b/tests/integration/mission/test_check_human_doc.py deleted file mode 100644 index 6999901..0000000 --- a/tests/integration/mission/test_check_human_doc.py +++ /dev/null @@ -1,393 +0,0 @@ -import copy -import json -import re -import sys -from pathlib import Path - -import pytest -from chef.questions import check as check_human_doc - -from tests.paths import PLUGIN_ROOT - -SCHEMA_TABLE = "| 컬럼 | 타입 |\n| --- | --- |\n| Id | long |" -CURRENT_TABLE = "| 필드 | 타입 |\n| --- | --- |\n| Color | string |" -ANSWER_TEXT = "2026-10-20 승인\n\n1번은 권장대로 진행.\n날짜와 원문을 유지." - - -def document(): - return { - "schema": 1, - "id": "confirm-A", - "revision": 1, - "title": "설계 확인", - "intro": "결정할 내용을 확인합니다.", - "items": [{"id": "1", "title": "방향", "body": "권장대로 진행할까요?", "status": "pending", "answer": ""}], - "body": SCHEMA_TABLE, - "approval": {"status": "none", "reason": ""}, - "answers": [{"schema": 1, "id": "legacy-1", "revision": 1, "at": "2026-10-20T12:00:00+09:00", "text": ANSWER_TEXT, "updates": []}], - } - - -def write_record(path, record): - path.write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8") - return path - - -def publish_legacy_record(folder, record): - # These archive fixtures represent documents already saved by schema 1 releases. - records = check_human_doc.question_records - source = records.source_path(folder, record['id'] + '.md') - source.parent.mkdir(parents=True, exist_ok=True) - write_record(source, record) - return records.publish_document(folder, record) - - -def migration(tmp_path): - raw = "\ufeff# 원문\r\n\r\n" + SCHEMA_TABLE.replace("\n", "\r\n") - raw += "\r\n\r\n```md\r\n## 답\r\n예시 답은 이관 대상 아님\r\n```\r\n\r\n## 답변 (2026-10-20)\r\n\r\n" - raw += ANSWER_TEXT.replace("\n", "\r\n") + "\r\n\r\n## 후속\r\n\r\n후속 설명\r\n" - source = tmp_path / "source.md" - source.write_bytes(raw.encode("utf-8")) - record = document() - record["legacy_markdown"] = raw - target = write_record(tmp_path / "draft.json", record) - return source, target, record - - -def test_large_design_table_remains_allowed_in_short_report(tmp_path): - table = "| 컬럼 | 타입 | 제약 |\n| --- | --- | --- |\n" + "".join(f"| Field{number} | int | 0 이상 |\n" for number in range(100)) - original = tmp_path / "original.md" - original.write_text("# 원문\n" + table, encoding="utf-8") - report = tmp_path / "report.md" - report.write_text("# 설계 결과\n\n## 지금\n\n설계 표를 확인받습니다.\n\n" + table, encoding="utf-8") - assert not check_human_doc.check(report, original)["issues"] - - -def test_rewrite_cannot_change_approved_answer_or_schema(tmp_path): - original = tmp_path / "original.md" - original.write_text("# 확인\n\n| 컬럼 | 타입 |\n| --- | --- |\n| Id | long |\n\n## 답\n\n2026-10-20 승인\n", encoding="utf-8") - result = tmp_path / "confirm-A.md" - result.write_text("# 확인\n\n| 컬럼 | 타입 |\n| --- | --- |\n| Id | int |\n\n## 답\n", encoding="utf-8") - assert len(check_human_doc.check(result, original)["issues"]) == 2 - - -def test_length_alone_does_not_decide_readability(tmp_path): - report = tmp_path / "report.md" - report.write_text("# 진행 보고\n\n## 지금\n\n" + "상세 실행 기록입니다. " * 150, encoding="utf-8") - result = check_human_doc.check(report) - assert not result["issues"] - assert result["semantic_review_required"] - - -def test_markdown_migration_preserves_raw_source_and_answer_under_generated_history_heading(tmp_path): - source, target, _ = migration(tmp_path) - result = check_human_doc.check(target, source) - assert not result["issues"] - assert result["semantic_review_required"] - assert result["prose_characters"] > len(ANSWER_TEXT) - - -@pytest.mark.parametrize("body", [ - "", - "```text\n답 작성 예시\n```", - " 답 작성 예시", - "(대기)", - "대기", - "답변 대기", - "답변대기", - "\n\n```text\n예시\n```\n\n(대기)", -]) -def test_markdown_migration_does_not_require_hidden_examples_or_placeholder_answers(tmp_path, body): - raw = "# 원문\n\n## 답\n\n" + body + "\n\n## 후속\n\n설명\n" - source = tmp_path / "source.md" - source.write_bytes(raw.encode("utf-8")) - record = document() - record.update(answers=[], legacy_markdown=raw) - target = write_record(tmp_path / "draft.json", record) - assert not check_human_doc.check(target, source)["issues"] - - -def test_real_answer_preserves_raw_body_including_surrounding_examples_and_comments(tmp_path): - body = "\n\n```text\n예시\n```\n\n권장대로 진행." - raw = "# 원문\n\n## 답\n\n" + body + "\n" - source = tmp_path / "source.md" - source.write_bytes(raw.encode("utf-8")) - record = document() - record["legacy_markdown"] = raw - record["answers"][0]["text"] = body - target = write_record(tmp_path / "draft.json", record) - assert not check_human_doc.check(target, source)["issues"] - record["answers"][0]["text"] = "권장대로 진행." - write_record(target, record) - assert any("답 절 본문" in issue for issue in check_human_doc.check(target, source)["issues"]) - - -@pytest.mark.parametrize("date", ["2026-10-20", "2026.10.20", "2026/10/20", "2026.1.2"]) -@pytest.mark.parametrize("preservation", ["at", "text", "missing"]) -def test_markdown_migration_preserves_answer_heading_date_in_history(tmp_path, date, preservation): - body = "권장대로 진행." - raw = f"# 원문\n\n## 답({date})\n\n{body}\n" - source = tmp_path / "source.md" - source.write_bytes(raw.encode("utf-8")) - record = document() - record["legacy_markdown"] = raw - history = record["answers"][0] - history.update(at="2026-10-26T16:00:00+09:00", text=body) - if preservation == "at": - year, month, day = (int(part) for part in re.split(r"[-./]", date)) - history["at"] = f"{year:04}-{month:02}-{day:02}T12:00:00+09:00" - if preservation == "text": - history["text"] = f"{date}\n\n{body}" - target = write_record(tmp_path / "draft.json", record) - issues = check_human_doc.check(target, source)["issues"] - if preservation == "missing": - assert any("제목의 날짜" in issue for issue in issues) - else: - assert not issues - - -def test_migration_can_group_past_answers_with_heading_dates_in_one_history_text(tmp_path): - raw = "# 원문\n\n## 답변 (2026-10-20)\n\n첫 답.\n\n## 답: 2026/10/21\n\n둘째 답.\n" - source = tmp_path / "source.md" - source.write_bytes(raw.encode("utf-8")) - record = document() - record["legacy_markdown"] = raw - record["answers"][0].update(at="2026-10-26T16:00:00+09:00", text="2026-10-20\n\n첫 답.\n\n2026/10/21\n\n둘째 답.") - target = write_record(tmp_path / "draft.json", record) - assert not check_human_doc.check(target, source)["issues"] - - -@pytest.mark.parametrize("change", [ - lambda record: record.pop("legacy_markdown"), - lambda record: record.update(legacy_markdown=record["legacy_markdown"].lstrip("\ufeff")), - lambda record: record.update(legacy_markdown=record["legacy_markdown"].replace("\r\n", "\n")), - lambda record: record.update(legacy_markdown=record["legacy_markdown"].replace("후속 설명", "변경 설명")), -]) -def test_markdown_migration_rejects_any_raw_source_change(tmp_path, change): - source, target, record = migration(tmp_path) - change(record) - write_record(target, record) - assert any("legacy_markdown" in issue for issue in check_human_doc.check(target, source)["issues"]) - - -@pytest.mark.parametrize("change", [ - lambda record: record.update(answers=[]), - lambda record: record["answers"][0].update(text=ANSWER_TEXT.replace("2026-10-20", "2026-10-21")), - lambda record: record["answers"][0].update(text=ANSWER_TEXT.replace("권장대로", "대안대로")), -]) -def test_markdown_migration_requires_original_answer_text_in_history(tmp_path, change): - source, target, record = migration(tmp_path) - change(record) - write_record(target, record) - assert any("답 절 본문" in issue for issue in check_human_doc.check(target, source)["issues"]) - - -@pytest.mark.parametrize("change", [ - lambda record: record.update(answers=[]), - lambda record: record["answers"][0].update(text="바뀐 답"), - lambda record: record["answers"][0].update(at="2026-10-21T12:00:00+09:00"), -]) -def test_json_revision_rejects_deleted_or_changed_answer_history(tmp_path, change): - original = document() - source = write_record(tmp_path / "source.json", original) - revised = copy.deepcopy(original) - revised["revision"] = 2 - change(revised) - target = write_record(tmp_path / "draft.json", revised) - assert any("답 원문 이력" in issue for issue in check_human_doc.check(target, source)["issues"]) - - -@pytest.mark.parametrize("change", [ - lambda record: record.pop("legacy_markdown"), - lambda record: record.update(legacy_markdown="변경 원문"), -]) -def test_json_revision_preserves_original_legacy_markdown(tmp_path, change): - original = document() - original["legacy_markdown"] = "\ufeff# 원문\r\n" - source = write_record(tmp_path / "source.json", original) - revised = copy.deepcopy(original) - change(revised) - target = write_record(tmp_path / "draft.json", revised) - assert any("legacy_markdown" in issue for issue in check_human_doc.check(target, source)["issues"]) - - -def test_json_revision_accepts_appended_history_and_unchanged_schema(tmp_path): - original = document() - source = write_record(tmp_path / "source.json", original) - revised = copy.deepcopy(original) - revised["revision"] = 2 - appended = copy.deepcopy(revised["answers"][0]) - appended.update(id="reply-2", revision=2, text="새 개정의 추가 답") - revised["answers"].append(appended) - target = write_record(tmp_path / "draft.json", revised) - assert not check_human_doc.check(target, source)["issues"] - - -@pytest.mark.parametrize("source_type", ["markdown", "json"]) -def test_structured_document_rejects_schema_column_type_change(tmp_path, source_type): - source, target, record = migration(tmp_path) - if source_type == "json": - source = write_record(tmp_path / "source.json", record) - record["body"] = SCHEMA_TABLE.replace("long", "int") - write_record(target, record) - assert any("설계 표" in issue for issue in check_human_doc.check(target, source)["issues"]) - - -def test_generated_markdown_must_match_source_json(tmp_path): - record = document() - source = write_record(tmp_path / "source.json", record) - target = tmp_path / "preview.md" - target.write_bytes(check_human_doc.question_records.render_document(record).replace("\n", "\r\n").encode("utf-8")) - assert not check_human_doc.check(target, source)["issues"] - target.write_text("# 임의로 바꾼 화면", encoding="utf-8") - assert any("렌더 결과" in issue for issue in check_human_doc.check(target, source)["issues"]) - - -def test_json_without_source_checks_structure_and_rendered_prose(tmp_path): - record = document() - target = write_record(tmp_path / "draft.json", record) - result = check_human_doc.check(target) - assert not result["issues"] - assert result["prose_characters"] == check_human_doc.prose_length(check_human_doc.question_records.render_document(record)) - record["items"] = [] - write_record(target, record) - assert check_human_doc.check(target)["issues"] - - -def test_damaged_json_is_reported_as_cli_failure_without_traceback(tmp_path, capsys): - target = tmp_path / "broken.json" - target.write_text('{"schema":', encoding="utf-8") - assert check_human_doc.main([str(target)]) == 1 - output = capsys.readouterr() - assert json.loads(output.out)["issues"] - assert not output.err - - -def test_revision_can_retire_old_design_only_after_actual_archive_verification(tmp_path): - record = document() - publish_legacy_record(tmp_path, record) - source = tmp_path / "questions/confirm-A.json" - revised = copy.deepcopy(record) - revised.update(revision=2, body="## Current shape\n\n" + CURRENT_TABLE) - target = write_record(tmp_path / "draft.json", revised) - assert not check_human_doc.check(target, source)["issues"] - archive = check_human_doc.question_records.history_path(tmp_path, "confirm-A.md") - archive.unlink() - assert any("설계 표" in issue for issue in check_human_doc.check(target, source)["issues"]) - assert any("전체 이력" in issue for issue in check_human_doc.check(target, source, archive)["issues"]) - - -@pytest.mark.parametrize("change", ["tampered", "wrong-document", "wrong-revision", "arbitrary-path", "damaged-snapshot"]) -def test_archive_cannot_exempt_loss_when_content_identity_revision_or_path_is_wrong(tmp_path, change): - records = check_human_doc.question_records - original = document() - publish_legacy_record(tmp_path, original) - source = write_record(tmp_path / "original.json", original) - revised = copy.deepcopy(original) - revised.update(revision=2, body=CURRENT_TABLE) - target = write_record(tmp_path / "draft.json", revised) - archive = records.history_path(tmp_path, "confirm-A.md") - if change == "tampered": - archive.write_text("# Missing original design", encoding="utf-8") - elif change == "wrong-document": - another = copy.deepcopy(original) - another["id"] = "confirm-B" - records.publish_document(tmp_path, another) - archive = records.history_path(tmp_path, "confirm-B.md") - elif change == "wrong-revision": - original["revision"] = 9 - write_record(source, original) - elif change == "arbitrary-path": - copied = tmp_path / "copied.md" - copied.write_bytes(archive.read_bytes()) - archive = copied - else: - newer = copy.deepcopy(original) - newer.update(revision=2, title="Second wording") - records.publish_document(tmp_path, newer, 1, editorial=True) - snapshot = tmp_path / "questions/history/confirm-A/1.json" - damaged = copy.deepcopy(original) - damaged["body"] = "Changed original field." - write_record(snapshot, damaged) - issues = check_human_doc.check(target, source, archive)["issues"] - assert any("전체 이력" in issue for issue in issues) - assert any("설계 표" in issue for issue in issues) - - -def test_explicit_archive_checks_unpublished_draft_and_prior_revision_snapshot(tmp_path, capsys): - records = check_human_doc.question_records - original = document() - publish_legacy_record(tmp_path, original) - old_source = write_record(tmp_path / "original.json", original) - revised = copy.deepcopy(original) - revised.update(revision=2, body=CURRENT_TABLE) - revised["approval"] = {"status": "pending", "reason": "Review the new design."} - draft = write_record(tmp_path / "draft.json", revised) - archive = records.history_path(tmp_path, "confirm-A.md") - assert check_human_doc.main([str(draft), "--source", str(old_source), "--archive", str(archive)]) == 0 - assert not json.loads(capsys.readouterr().out)["issues"] - records.publish_document(tmp_path, revised, 1) - assert not check_human_doc.check(draft, old_source, archive)["issues"] - generated = tmp_path / "confirm-A.md" - assert not check_human_doc.check(generated, tmp_path / "questions/confirm-A.json")["issues"] - - -@pytest.mark.parametrize("body", ["", "## Current plan\n\nThe old design is only in history."]) -def test_verified_archive_does_not_allow_removing_every_current_design_table(tmp_path, body): - records = check_human_doc.question_records - original = document() - publish_legacy_record(tmp_path, original) - revised = copy.deepcopy(original) - revised.update(revision=2, body=body) - target = write_record(tmp_path / "draft.json", revised) - archive = records.history_path(tmp_path, "confirm-A.md") - assert records.validate_history_archive(archive, original) - assert any("설계 표" in issue for issue in check_human_doc.check(target, tmp_path / "questions/confirm-A.json", archive)["issues"]) - - -@pytest.mark.parametrize("field_type", ["long", "int"]) -def test_legacy_schema_migration_compares_actual_current_field_definitions(tmp_path, field_type): - source, target, record = migration(tmp_path) - record.update(body="", blocks=[{"id": "shape", "type": "fields", "fields": [{"name": "Id", "type": field_type}]}]) - write_record(target, record) - result = check_human_doc.check(target, source) - assert result["semantic_review_required"] - assert bool(result["issues"]) == (field_type != "long") - - -@pytest.mark.parametrize("location", ["blocks", "detail_blocks"]) -def test_verified_archive_requires_fields_in_current_body_not_only_details(tmp_path, location): - records = check_human_doc.question_records - original = document() - publish_legacy_record(tmp_path, original) - revised = copy.deepcopy(original) - revised.update(revision=2, body="") - revised[location] = [{"id": "shape", "type": "fields", "fields": [{"name": "Color", "type": "string"}]}] - target = write_record(tmp_path / "draft.json", revised) - result = check_human_doc.check(target, tmp_path / "questions/confirm-A.json") - assert result["semantic_review_required"] - assert bool(result["issues"]) == (location == "detail_blocks") - - -def test_detail_only_fields_are_not_treated_as_current_approval_contract(tmp_path): - original = document() - original.update(body="Current purpose.", detail_blocks=[{"id": "extra", "type": "fields", "fields": [{"name": "Note", "type": "string"}]}]) - source = write_record(tmp_path / "source.json", original) - revised = copy.deepcopy(original) - revised.update(revision=2, detail_blocks=[]) - target = write_record(tmp_path / "draft.json", revised) - assert not check_human_doc.check(target, source)["issues"] - - -def test_structured_field_loss_is_detected_without_legacy_header_heuristic(tmp_path): - records = check_human_doc.question_records - original = document() - original.update(body="", blocks=[{"id": "shape", "type": "fields", "fields": [{"name": "Id", "type": "long"}]}]) - source = write_record(tmp_path / "source.json", original) - revised = copy.deepcopy(original) - revised["blocks"][0]["fields"][0]["type"] = "int" - target = write_record(tmp_path / "draft.json", revised) - assert any("필드 정의" in issue for issue in check_human_doc.check(target, source)["issues"]) - generated = tmp_path / "preview.md" - generated.write_text(records.render_document(original), encoding="utf-8") - assert not check_human_doc.check(generated, source)["issues"] diff --git a/tests/integration/mission/test_execution_leases.py b/tests/integration/mission/test_execution_leases.py deleted file mode 100644 index 2d3476b..0000000 --- a/tests/integration/mission/test_execution_leases.py +++ /dev/null @@ -1,744 +0,0 @@ -"""Public cooperative execution coordination, with wholly synthetic inputs.""" - -import json -import io -import contextlib -import os -import signal -import subprocess -import sys -import threading -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from chef.guards import mission as guard -from chef.verification import execution -from chef.verification import plan as verification_plan -from chef.verification import runner - - -@pytest.fixture(autouse=True) -def registry(tmp_path, monkeypatch): - directory = tmp_path / "registry" - monkeypatch.setattr(execution, "registry_directory", lambda: directory) - return directory - - -@pytest.fixture -def project(tmp_path): - root = tmp_path / "example" - root.mkdir() - (root / "src").mkdir() - (root / "src" / "main.txt").write_text("example input", encoding="utf-8") - folder = root / "mission" - folder.mkdir() - plan = {"grade": "example-pass", "inputs": ["src"], "environment": {"target": "example"}, - "commands": [{"argv": [sys.executable, "-c", "pass"]}]} - return root, folder, plan - - -@pytest.fixture -def mocked_file_symlink(project, monkeypatch): - """Exercise DirEntry/realpath behavior where Windows denies real symlinks.""" - root, _, _ = project - link = root / "src/link.txt" - target = root / "common.txt" - link.write_text("simulated link node", encoding="utf-8") - target.write_text("example resolved target", encoding="utf-8") - original_scan = execution.os.scandir - original_canonical = execution.paths.canonical_path - - class LinkEntry: - path = str(link) - - def is_dir(self, *, follow_symlinks=True): - return False - - def is_symlink(self): - return True - - @contextlib.contextmanager - def scan(path): - with original_scan(path) as entries: - yield iter(LinkEntry() if Path(entry.path) == link else entry for entry in entries) - - monkeypatch.setattr(execution.os, "scandir", scan) - monkeypatch.setattr(execution.paths, "canonical_path", lambda path: ( - original_canonical(target) if Path(path) == link else original_canonical(path) - )) - return root, link, target - - -def test_lease_blocks_file_parent_and_new_child_but_allows_disjoint_work(project, registry): - root, _, _ = project - with execution.input_lease([root / "src"]): - for target in (root / "src/main.txt", root, root / "src/new.txt"): - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([target]) - execution.require_mutation_allowed([root / "other.txt"]) - # Readers can share inputs; a declared writer cannot. - with execution.input_lease([root / "src/main.txt"]): - pass - with pytest.raises(execution.VerificationError, match="protected execution input"): - with execution.mutation_lease([root / "src"]): - pytest.fail("overlapping mutation acquired") - execution.require_mutation_allowed([root]) - assert json.loads((registry / "inputs.json").read_text())["leases"] == [] - assert (registry / "inputs.lock.gate").exists() - - -def test_declared_mutation_blocks_later_verify_until_it_finishes(project): - root, _, _ = project - with execution.mutation_lease([root / "src/main.txt"]): - with pytest.raises(execution.VerificationError, match="protected execution input"): - with execution.input_lease([root / "src"]): - pytest.fail("reader acquired during mutation") - with execution.input_lease([root / "other.txt"]): - pass - with execution.input_lease([root / "src"]): - pass - - -def test_file_hardlink_alias_is_protected(project): - root, _, _ = project - alias = root / "alias.txt" - os.link(root / "src/main.txt", alias) - with execution.input_lease([root / "src/main.txt"]): - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([alias]) - - -def test_directory_alias_is_protected(project): - root, _, _ = project - linked = root / "linked" - try: - linked.symlink_to(root / "src", target_is_directory=True) - except OSError: - pytest.skip("directory symlink unavailable") - with execution.input_lease([linked]): - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "src/new.txt"]) - - -@pytest.mark.parametrize("existing", [True, False]) -def test_real_file_symlink_target_matches_snapshot_and_is_protected(project, existing): - root, _, _ = project - target = root / "common.txt" - if existing: - target.write_text("example resolved input", encoding="utf-8") - try: - (root / "src/link.txt").symlink_to(target) - except OSError: - pytest.skip("file symlink unavailable") - snapshot = verification_plan.snapshot(root, ["src"]) - assert snapshot["src/link.txt"] == (runner.file_hash(target) if existing else "missing") - with execution.input_lease([root / "src"]) as lease: - assert execution.paths.canonical_path(target) in lease["aliases"] - assert "protected execution input" in guard.decide({ - "tool_name": "Write", "cwd": str(root), "tool_input": {"file_path": "common.txt"}, - }).deny - execution.require_mutation_allowed([target]) - - -def test_mocked_file_symlink_target_is_protected_without_hook_rescan(mocked_file_symlink, monkeypatch): - root, _, target = mocked_file_symlink - with execution.input_lease([root / "src"]) as lease: - assert lease["aliases"] == [execution.paths.canonical_path(target)] - - def unexpected(*args, **kwargs): - pytest.fail("known-target check rescanned symlink input tree") - - monkeypatch.setattr(execution.os, "scandir", unexpected) - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([target]) - assert "protected execution input" in guard.decide({ - "tool_name": "Write", "cwd": str(root), "tool_input": {"file_path": str(target)}, - }).deny - execution.require_mutation_allowed([root / "unrelated.txt"]) - execution.require_mutation_allowed([target]) - - -def test_file_symlink_index_cap_fails_before_lease_registration(mocked_file_symlink, registry, monkeypatch): - root, _, _ = mocked_file_symlink - monkeypatch.setattr(execution, "MAX_ALIASES", 0) - with pytest.raises(execution.VerificationError, match="execution symlink index exceeds limit"): - with execution.input_lease([root / "src"]): - pytest.fail("unbounded symlink index") - assert not (registry / "inputs.json").exists() - - -def test_alias_scan_and_registration_fence_declared_mutator_finishing_mid_scan(mocked_file_symlink, monkeypatch): - root, link, target = mocked_file_symlink - replacement = root / "replacement.txt" - replacement.write_text("example replacement target", encoding="utf-8") - state = threading.local() - original_lock = execution.locking.FileLock - original_index = execution.input_file_aliases - original_canonical = execution.paths.canonical_path - changed = [] - - class ImmediateMutatorLock(original_lock): - def __init__(self, path, label, timeout=0): - super().__init__(path, label, timeout=0 if getattr(state, "mutator", False) else timeout) - - def mutate_alias(): - state.mutator = True - try: - with execution.mutation_lease([root / "src"]): - monkeypatch.setattr(execution.paths, "canonical_path", lambda path: ( - original_canonical(replacement) if Path(path) == link else original_canonical(path) - )) - changed.append(True) - except (execution.locking.LockBusy, execution.VerificationError): - return "blocked" - return "changed" - - def index(targets): - result = original_index(targets) - if not getattr(state, "mutator", False): - with ThreadPoolExecutor(max_workers=1) as pool: - assert pool.submit(mutate_alias).result(timeout=5) == "blocked" - return result - - monkeypatch.setattr(execution.locking, "FileLock", ImmediateMutatorLock) - monkeypatch.setattr(execution, "input_file_aliases", index) - with execution.input_lease([root / "src"]) as lease: - assert lease["aliases"] == [original_canonical(target)] - assert not changed - - -def test_active_overlapping_mutation_is_rejected_before_alias_scan(project, monkeypatch): - root, _, _ = project - with execution.mutation_lease([root / "src"]): - def unexpected(*args): - pytest.fail("active overlapping mutation reached alias scan") - - monkeypatch.setattr(execution, "input_file_aliases", unexpected) - with pytest.raises(execution.VerificationError, match="protected execution input"): - with execution.input_lease([root / "src"]): - pytest.fail("active overlapping mutation allowed verify") - - -def test_directory_lease_protects_external_hardlink_without_rescanning(project, monkeypatch): - root, _, _ = project - alias = root / "outside-alias.txt" - os.link(root / "src/main.txt", alias) - with execution.input_lease([root / "src"]) as lease: - assert len(lease["hardlinks"]) == 1 - - def unexpected(*args, **kwargs): - pytest.fail("known-target check rescanned input tree") - - monkeypatch.setattr(execution.os, "scandir", unexpected) - for _ in range(2): - with pytest.raises(execution.VerificationError, match="protected execution input hardlink"): - execution.require_mutation_allowed([alias]) - assert "protected execution input hardlink" in guard.decide({ - "tool_name": "Write", "cwd": str(root), "tool_input": {"file_path": str(alias)}, - }).deny - - -def test_directory_identity_index_has_a_scan_limit(project, monkeypatch, registry): - root, _, _ = project - monkeypatch.setattr(execution, "MAX_SCAN_ENTRIES", 1) - with pytest.raises(execution.VerificationError, match="identity scan exceeds limit"): - with execution.input_lease([root / "src"]): - pytest.fail("unbounded input scan") - assert not (registry / "inputs.json").exists() - - -def test_case_sensitive_paths_remain_disjoint(project): - root, _, _ = project - other = root / "SRC" - if other.exists(): - pytest.skip("case-insensitive volume") - other.mkdir() - with execution.input_lease([root / "src"]): - execution.require_mutation_allowed([other / "new.txt"]) - - -def test_alive_owner_is_not_expired_and_dead_owner_is_removed(project, registry, monkeypatch): - root, _, _ = project - with execution.input_lease([root / "src"]): - path = registry / "inputs.json" - value = json.loads(path.read_text()) - value["leases"][0]["startedAt"] = "1900-01-01T00:00:00Z" - path.write_text(json.dumps(value)) - os.utime(path, (1, 1)) - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "src/main.txt"]) - value["leases"][0]["pid"] = 2147483647 - value["leases"][0]["processStart"] = None - path.write_text(json.dumps(value)) - real_alive = execution.locking.process_alive - monkeypatch.setattr(execution.locking, "process_alive", lambda pid: False if pid == 2147483647 else real_alive(pid)) - execution.require_mutation_allowed([root / "src/main.txt"]) - assert json.loads(path.read_text())["leases"] == [] - - -def test_reused_pid_does_not_keep_old_process_lease(project, registry, monkeypatch): - root, _, _ = project - monkeypatch.setattr(execution, "process_start", lambda pid: "first-incarnation") - with execution.input_lease([root / "src"]): - monkeypatch.setattr(execution, "process_start", lambda pid: "later-incarnation") - execution.require_mutation_allowed([root / "src/main.txt"]) - assert json.loads((registry / "inputs.json").read_text())["leases"] == [] - - -@pytest.mark.parametrize("value", ["{", "[]", "{}", '{"leases": "invalid"}', - '{"leases":[{"mode":"verify","pid":0}]}', - '{"leases":[{"mode":"verify","pid":999999999999999999999}]}']) -def test_corrupt_registry_fails_known_mutation_closed(project, registry, value): - root, _, _ = project - registry.mkdir() - (registry / "inputs.json").write_text(value) - outcome = guard.decide({"tool_name": "Write", "cwd": str(root), - "tool_input": {"file_path": "src/main.txt", "content": "new"}}) - assert "execution input protection" in outcome.deny - assert "허용 파일:" not in outcome.deny - - -def test_registry_bounds_and_permission_errors_are_explicit(project, registry, monkeypatch): - root, _, _ = project - with execution.input_lease([root / "src"]): - monkeypatch.setattr(execution, "MAX_BYTES", 1) - with pytest.raises(execution.VerificationError, match="size limit"): - execution.require_mutation_allowed([root / "src/main.txt"]) - monkeypatch.undo() - monkeypatch.setattr(execution, "registry_directory", lambda: registry) - read = execution.read_record - - def denied(path): - if Path(path).name == "inputs.json": - raise PermissionError("example denied registry") - return read(path) - - monkeypatch.setattr(execution, "read_record", denied) - outcome = guard.decide({"tool_name": "Edit", "cwd": str(root), - "tool_input": {"file_path": "src/main.txt"}}) - assert "example denied registry" in outcome.deny - monkeypatch.setattr(execution, "read_record", read) - - -def test_deep_registry_json_is_denied_by_actual_hook_main(project, registry, monkeypatch): - root, _, _ = project - registry.mkdir() - depth = sys.getrecursionlimit() + 100 - (registry / "inputs.json").write_text('{"nested":' * depth + '0' + '}' * depth) - payload = {"tool_name": "Write", "cwd": str(root), "tool_input": {"file_path": "src/main.txt"}} - output = io.StringIO() - monkeypatch.setattr(guard.sys, "stdin", SimpleNamespace(buffer=io.BytesIO(json.dumps(payload).encode()))) - monkeypatch.setattr(guard.sys, "stdout", output) - monkeypatch.setattr(guard, "log_payload", lambda payload: None) - assert guard.main() == 0 - result = json.loads(output.getvalue())["hookSpecificOutput"] - assert result["permissionDecision"] == "deny" - assert "execution registry nesting exceeds limit" in result["permissionDecisionReason"] - - -def test_registry_parser_recursion_error_is_wrapped(project, registry, monkeypatch): - registry.mkdir() - path = registry / "inputs.json" - path.write_text('{"leases": []}') - original = execution.json.loads - - def recursive(value, *args, **kwargs): - if isinstance(value, bytes): - raise RecursionError("example parser recursion") - return original(value, *args, **kwargs) - - monkeypatch.setattr(execution.json, "loads", recursive) - with pytest.raises(execution.VerificationError, match="execution registry is unreadable"): - execution.read_record(path) - - -@pytest.mark.parametrize("tool,command", [ - ("PowerShell", "Set-Content -LiteralPath 'src/[config].txt' -Value changed"), - ("PowerShell", "Set-Content -LiteralPath src/[config].txt -Value changed"), - ("Bash", "printf changed > 'src/[config].txt'"), - ("Bash", 'printf changed > "src/[config].txt"'), -]) -@pytest.mark.parametrize("existing", [True, False]) -def test_literal_brackets_are_protected_for_existing_and_missing_paths(project, tool, command, existing): - root, _, _ = project - target = root / "src/[config].txt" - if existing: - target.write_text("example", encoding="utf-8") - with execution.input_lease([target]): - assert "protected execution input" in guard.decide({ - "tool_name": tool, "cwd": str(root), "tool_input": {"command": command}, - }).deny - - -def test_static_python_missing_literal_brackets_are_protected(project): - root, _, _ = project - target = root / "src/[config].txt" - command = 'python -c "from pathlib import Path; Path(\'src/[config].txt\').write_text(\'changed\')"' - with execution.input_lease([target]): - assert "protected execution input" in guard.execution_write_reason({ - "tool_name": "Bash", "cwd": str(root), "tool_input": {"command": command}, - }) - - -def test_powershell_new_name_brackets_are_literal_without_quotes(project): - root, _, _ = project - (root / "src/old.txt").write_text("example", encoding="utf-8") - with execution.input_lease([root / "src/[new].txt"]): - assert "protected execution input" in guard.execution_write_reason({ - "tool_name": "PowerShell", "cwd": str(root), - "tool_input": {"command": "Rename-Item -LiteralPath src/old.txt -NewName [new].txt"}, - }) - - -@pytest.mark.parametrize("tool,command", [ - ("Bash", "rm src/[ab].txt"), - ("PowerShell", "Set-Content -Path 'src/[ab].txt' -Value changed"), - ("PowerShell", "Rename-Item src/*/old.txt -NewName new.txt"), -]) -def test_static_glob_uses_conservative_literal_parent_scope(project, tool, command): - root, _, _ = project - with execution.input_lease([root / "src/a.txt"]): - assert "protected execution input" in guard.execution_write_reason({ - "tool_name": tool, "cwd": str(root), "tool_input": {"command": command}, - }) - - -@pytest.mark.parametrize("tool,command", [ - ("Bash", 'python -c "from pathlib import Path; Path(\'src/[config].txt\').write_text(\'changed\')"'), - ("Bash", "printf changed > 'src/[config].txt'"), - ("PowerShell", "Set-Content -LiteralPath src/[config].txt -Value changed"), - ("PowerShell", "Rename-Item -LiteralPath src/old.txt -NewName [new].txt"), -]) -def test_proven_literal_brackets_do_not_expand_to_unrelated_siblings(project, tool, command): - root, _, _ = project - (root / "src/old.txt").write_text("example", encoding="utf-8") - with execution.input_lease([root / "src/neighbor.txt"]): - assert not guard.execution_write_reason({ - "tool_name": tool, "cwd": str(root), "tool_input": {"command": command}, - }) - - -@pytest.mark.parametrize("command", [ - "Rename-Item src/old.txt -NewName new.txt", - "Rename-Item -LiteralPath src/old.txt -NewName new.txt", - "ren src/old.txt new.txt", -]) -def test_rename_destination_is_in_source_directory(project, command): - root, _, _ = project - (root / "src/old.txt").write_text("example", encoding="utf-8") - with execution.input_lease([root / "src/new.txt"]): - assert "protected execution input" in guard.execution_write_reason({ - "tool_name": "PowerShell", "cwd": str(root), "tool_input": {"command": command}, - }) - with execution.input_lease([root / "new.txt"]): - assert not guard.execution_write_reason({ - "tool_name": "PowerShell", "cwd": str(root), "tool_input": {"command": command}, - }) - assert "protected execution input" in guard.execution_write_reason({ - "tool_name": "PowerShell", "cwd": str(root), - "tool_input": {"command": "Set-Content new.txt changed; " + command}, - }) - - -@pytest.mark.parametrize("tool,tool_input", [ - ("Write", {"file_path": "src/main.txt"}), - ("Edit", {"file_path": "src/main.txt"}), - ("apply_patch", {"patch": "*** Begin Patch\n*** Update File: src/main.txt\n*** End Patch"}), - ("Bash", {"command": "printf changed > src/main.txt"}), - ("Bash", {"command": "cd src && rm main.txt"}), - ("PowerShell", {"command": "Set-Content -LiteralPath src/main.txt -Value changed"}), - ("PowerShell", {"command": "Remove-Item -LiteralPath src -Recurse"}), -]) -def test_known_hook_mutations_block_even_subagents_without_mission(project, tool, tool_input): - root, _, _ = project - with execution.input_lease([root / "src"]): - outcome = guard.decide({"tool_name": tool, "tool_input": tool_input, - "cwd": str(root), "agent_id": "example-worker"}) - assert "protected execution input" in outcome.deny - - -def test_unknown_shell_scope_is_not_claimed_and_literal_other_target_is_allowed(project): - root, _, _ = project - with execution.input_lease([root / "src"]): - for command in ("cd $unknown; rm main.txt", "printf changed > $unknown", "printf changed > other.txt"): - assert not guard.execution_write_reason({"tool_name": "Bash", "cwd": str(root), - "tool_input": {"command": command}}) - - -@pytest.mark.parametrize("failure", ["exit", "unexpected"]) -def test_failed_run_releases_inputs_jobs_and_unit_lock(project, registry, monkeypatch, failure): - root, folder, plan = project - - def launch(*args): - execution.require_mutation_allowed([root / "other.txt"]) - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "src/main.txt"]) - if failure == "unexpected": - raise RuntimeError("example launch interrupted") - return subprocess.CompletedProcess([], 2) - - monkeypatch.setattr(runner, "execute_command", launch) - if failure == "unexpected": - with pytest.raises(RuntimeError, match="example launch interrupted"): - runner.run(root, folder, "M1", plan, lambda command: None) - else: - assert runner.run(root, folder, "M1", plan, lambda command: None)[1]["status"] == "fail" - assert json.loads((registry / "inputs.json").read_text())["leases"] == [] - assert execution.active_verification(folder, "M1") is None - with execution.unit_execution_lock(folder, "M1"): - pass - - -def test_snapshot_is_taken_after_input_lease_and_resource_lock(project, monkeypatch): - root, folder, plan = project - settings = {"resources": {"example-pass": ["example-engine"]}, "resourceDir": str(root / "locks")} - original = runner.snapshot - - def snapshot(project, inputs): - assert (root / "locks/example-engine.lock").exists() - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "src/main.txt"]) - return original(project, inputs) - - monkeypatch.setattr(runner, "snapshot", snapshot) - monkeypatch.setattr(verification_plan, "snapshot", snapshot) - assert runner.run(root, folder, "M1", plan, lambda command: None, settings=settings)[1]["status"] == "pass" - - -def test_concurrent_duplicate_references_owner_and_contract_mutation_is_blocked(project, monkeypatch): - root, folder, plan = project - entered, finish = threading.Event(), threading.Event() - calls = [] - - def launch(*args): - calls.append(1) - entered.set() - assert finish.wait(10) - return subprocess.CompletedProcess([], 0) - - monkeypatch.setattr(runner, "execute_command", launch) - with ThreadPoolExecutor(max_workers=1) as pool: - future = pool.submit(runner.run, root, folder, "M1", plan, lambda command: None) - try: - assert entered.wait(10) - original = execution.active_verification(folder, "M1") - for request in (plan, {**plan, "environment": {"target": "changed"}}): - with pytest.raises(execution.ExecutionBusy) as busy: - runner.run(root, folder, "M1", request, lambda command: None) - assert busy.value.record["token"] == original["token"] - assert busy.value.record["sameRequest"] == (request == plan) - with pytest.raises(execution.ExecutionBusy): - with execution.unit_execution_lock(folder, "M1"): - pytest.fail("contract mutation acquired during run") - assert len(calls) == 1 - finally: - finish.set() - first = future.result(timeout=10) - second = runner.run(root, folder, "M1", plan, lambda command: None) - assert second[2] and second[0] == first[0] - assert len(calls) == 1 - - -def test_review_reservation_is_idempotent_and_keyed_by_all_review_inputs(project): - _, folder, _ = project - args = (folder, "M1", "snapshot-one", "independent-review", ["a.txt", "b.txt"], [{"id": "finding-one"}]) - first = execution.reserve_review(*args) - second = execution.reserve_review(folder, "M1", "snapshot-one", "independent-review", - ["b.txt", "a.txt", "a.txt"], [{"id": "finding-one"}]) - assert first["acquired"] and not second["acquired"] - assert first["key"] == second["key"] and first["token"] == second["token"] - with pytest.raises(execution.VerificationError, match="no longer owned"): - execution.finish_job(folder, first["key"], "wrong-token", {"evidence": "review.json"}) - execution.finish_job(folder, first["key"], first["token"], {"evidence": "review.json"}) - completed = execution.reserve_review(*args) - assert completed["status"] == "completed" and not completed["acquired"] - assert completed["result"] == {"evidence": "review.json"} - for index, changed in ((1, "M2"), (2, "snapshot-two"), (3, "follow-up"), - (4, ["a.txt"]), (5, [{"id": "finding-two"}])): - altered = list(args) - altered[index] = changed - other = execution.reserve_review(*altered) - assert other["acquired"] and other["key"] != first["key"] - - -def test_dead_review_owner_replaced_and_old_token_cannot_complete(project, monkeypatch): - _, folder, _ = project - with subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE) as worker: - first = execution.reserve_review(folder, "M1", "snapshot", "review", [], [], owner_pid=worker.pid) - old = execution.read_record(execution.job_path(execution.job_directory(folder), first["key"])) - old["startedAt"] = "1900-01-01T00:00:00Z" - execution.write_record(execution.job_path(execution.job_directory(folder), first["key"]), old) - assert not execution.reserve_review(folder, "M1", "snapshot", "review", [], [])["acquired"] - worker.stdin.close() - worker.wait(timeout=5) - later = execution.reserve_review(folder, "M1", "snapshot", "review", [], []) - assert later["acquired"] and later["token"] != first["token"] - with pytest.raises(execution.VerificationError, match="no longer owned"): - execution.finish_job(folder, first["key"], first["token"], {}) - execution.finish_job(folder, later["key"], later["token"], release=True) - assert execution.reserve_review(folder, "M1", "snapshot", "review", [], [])["acquired"] - - -def test_worker_claim_transfers_pid_and_fences_delayed_old_worker(project): - _, folder, _ = project - first = execution.reserve_review(folder, "M1", "snapshot", "review", [], []) - with subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE) as worker: - transferred = execution.transfer_job(folder, first["key"], first["token"], worker.pid) - assert transferred["pid"] == worker.pid - assert transferred["processStart"] == execution.process_start(worker.pid) - with pytest.raises(execution.VerificationError, match="already been claimed"): - execution.transfer_job(folder, first["key"], first["token"], os.getpid()) - assert not execution.reserve_review(folder, "M1", "snapshot", "review", [], [])["acquired"] - worker.stdin.close() - worker.wait(timeout=5) - later = execution.reserve_review(folder, "M1", "snapshot", "review", [], []) - assert later["acquired"] - with pytest.raises(execution.VerificationError, match="no longer owned"): - execution.transfer_job(folder, first["key"], first["token"], os.getpid()) - - -def test_uncertain_launch_is_not_reclaimed_after_owner_death(project, registry, monkeypatch): - root, folder, _ = project - job = execution.reserve_review(folder, "M1", "snapshot", "review", [], []) - with execution.input_lease([root / "src"]) as lease: - with execution.unit_execution_lock(folder, "M1", owned_job=job): - execution.begin_job_launch(folder, job["key"], job["token"], lease["token"]) - inputs_path = registry / "inputs.json" - inputs = execution.read_record(inputs_path) - inputs["leases"][0].update(pid=2147483647, processStart=None) - execution.write_record(inputs_path, inputs) - job_path = execution.job_path(execution.job_directory(folder), job["key"]) - record = execution.read_record(job_path) - record.update(pid=2147483647, processStart=None) - execution.write_record(job_path, record) - real_alive = execution.locking.process_alive - monkeypatch.setattr(execution.locking, "process_alive", lambda pid: False if pid == 2147483647 else real_alive(pid)) - assert not execution.reserve_review(folder, "M1", "snapshot", "review", [], [])["acquired"] - with pytest.raises(execution.ExecutionBusy): - with execution.unit_execution_lock(folder, "M1"): - pytest.fail("uncertain launch allowed contract mutation") - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "src/main.txt"]) - with pytest.raises(execution.VerificationError, match="launch needs recovery"): - execution.finish_job(folder, job["key"], job["token"], release=True) - assert execution.read_record(inputs_path)["leases"][0]["launchPending"] - - -def test_live_child_keeps_dead_supervisor_job_inputs_and_contract_protected(project, registry, monkeypatch): - root, folder, _ = project - job = execution.reserve_review(folder, "M1", "snapshot", "review", [], []) - with execution.input_lease([root / "src"]) as lease: - with subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE) as child: - execution.begin_job_launch(folder, job["key"], job["token"], lease["token"]) - execution.register_job_child(folder, job["key"], job["token"], lease["token"], child.pid) - inputs_path = registry / "inputs.json" - inputs = execution.read_record(inputs_path) - inputs["leases"][0].update(pid=2147483647, processStart=None) - execution.write_record(inputs_path, inputs) - job_path = execution.job_path(execution.job_directory(folder), job["key"]) - record = execution.read_record(job_path) - record.update(pid=2147483647, processStart=None) - execution.write_record(job_path, record) - real_alive = execution.locking.process_alive - monkeypatch.setattr(execution.locking, "process_alive", lambda pid: False if pid == 2147483647 else real_alive(pid)) - assert not execution.reserve_review(folder, "M1", "snapshot", "review", [], [])["acquired"] - with pytest.raises(execution.ExecutionBusy): - with execution.unit_execution_lock(folder, "M1"): - pytest.fail("live child allowed contract mutation") - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "src/main.txt"]) - with pytest.raises(execution.VerificationError, match="execution child is live"): - execution.finish_job(folder, job["key"], job["token"], release=True) - child.stdin.close() - child.wait(timeout=5) - execution.require_mutation_allowed([root / "src/main.txt"]) - later = execution.reserve_review(folder, "M1", "snapshot", "review", [], []) - assert later["acquired"] and later["token"] != job["token"] - - -def test_reaped_child_can_finish_and_release_inputs(project): - root, folder, _ = project - job = execution.reserve_review(folder, "M1", "snapshot", "review", [], []) - with execution.input_lease([root / "src"]) as lease: - execution.begin_job_launch(folder, job["key"], job["token"], lease["token"]) - with subprocess.Popen([sys.executable, "-c", "pass"]) as child: - execution.register_job_child(folder, job["key"], job["token"], lease["token"], child.pid) - child.wait(timeout=5) - execution.cancel_job_launch(folder, job["key"], job["token"], lease["token"]) - execution.finish_job(folder, job["key"], job["token"], {"status": "completed"}) - execution.require_mutation_allowed([root / "src/main.txt"]) - - -def test_cancel_launch_cannot_drop_registered_live_child(project): - root, folder, _ = project - job = execution.reserve_review(folder, "M1", "snapshot", "review", [], []) - with execution.input_lease([root / "src"]) as lease: - with subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE) as child: - execution.begin_job_launch(folder, job["key"], job["token"], lease["token"]) - execution.register_job_child(folder, job["key"], job["token"], lease["token"], child.pid) - with pytest.raises(execution.VerificationError, match="execution child is still live"): - execution.cancel_job_launch(folder, job["key"], job["token"], lease["token"]) - current = execution.read_record(execution.job_path(execution.job_directory(folder), job["key"])) - assert execution.child_alive(current) - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "src/main.txt"]) - child.stdin.close() - child.wait(timeout=5) - execution.cancel_job_launch(folder, job["key"], job["token"], lease["token"]) - execution.finish_job(folder, job["key"], job["token"], {}) - - -def test_verify_parent_kill_preserves_real_child_input_unit_and_resource_ownership(project, registry): - root, folder, _ = project - source = """ -import sys -from pathlib import Path -from chef.verification import execution, runner -root, folder, registry = map(Path, sys.argv[1:]) -execution.registry_directory = lambda: registry -register = execution.register_job_child -def child_started(*args): - result = register(*args) - print(args[-1], flush=True) - return result -execution.register_job_child = child_started -plan = {'grade': 'example-pass', 'inputs': ['src'], 'environment': {'target': 'example'}, - 'commands': [{'argv': [sys.executable, '-c', 'import threading; threading.Event().wait(30)']}]} -settings = {'resourceDir': str(root / 'locks'), 'resources': {'example-pass': ['example-engine']}} -runner.run(root, folder, 'M1', plan, lambda command: None, settings=settings) -""" - environment = {**os.environ, "PYTHONPATH": str(Path(execution.__file__).resolve().parents[2])} - parent = subprocess.Popen([sys.executable, "-c", source, str(root), str(folder), str(registry)], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=environment) - child_pid = None - try: - line = parent.stdout.readline().strip() - assert line.isdigit(), parent.stderr.read() - child_pid = int(line) - parent.kill() - parent.wait(timeout=5) - current = execution.active_verification(folder, "M1") - assert current["child"]["pid"] == child_pid and execution.child_alive(current) - with pytest.raises(execution.VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "src/main.txt"]) - with pytest.raises(execution.ExecutionBusy) as busy: - with execution.unit_execution_lock(folder, "M1"): - pytest.fail("dead verify parent allowed another unit writer") - assert busy.value.record["child"]["pid"] == child_pid - with pytest.raises(execution.locking.LockBusy): - with runner.ResourceLock(root / "locks/example-engine.lock", "example-engine"): - pytest.fail("dead verify parent released a running child resource") - finally: - if parent.poll() is None: - parent.kill() - parent.wait(timeout=5) - if child_pid: - try: - os.kill(child_pid, signal.SIGTERM) - except ProcessLookupError: - pass - parent.stdout.close() - parent.stderr.close() diff --git a/tests/integration/mission/test_lab.py b/tests/integration/mission/test_lab.py deleted file mode 100644 index 20f0f29..0000000 --- a/tests/integration/mission/test_lab.py +++ /dev/null @@ -1,477 +0,0 @@ -from pathlib import Path - -from tests.paths import PLUGIN_ROOT, REPO_ROOT - -"""Synthetic coordinator and actual Linux sandbox tests; no live model providers.""" -import shutil -import subprocess -import sys -from pathlib import Path - -import pytest -from chef.mission import lab as lab - - -@pytest.fixture(autouse=True) -def isolated_environment(tmp_path, monkeypatch): - for key in ('HOME', 'USERPROFILE', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'GROK_HOME', - 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'HAN_ADAPTERS_DIR'): - monkeypatch.setenv(key, str(tmp_path / key.lower())) - for key in ('CLAUDE_PROJECT_DIR', 'HAN_REPO', 'CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR', - 'GROK_HOOK_EVENT', 'GROK_SESSION_ID'): - monkeypatch.delenv(key, raising=False) - monkeypatch.chdir(tmp_path) - - -def configuration(generations=1, budget=None): - return {'schema': 1, 'generations': generations, 'candidates': 4, - 'maxEvaluations': budget if budget is not None else generations * 8, - 'maxSeconds': 120, 'maxConcurrent': 4, 'seed': 17, - 'costPolicy': 'unknown-no-paid-launches', - 'strategies': [{'name': f'fictional-{i}', 'kind': 'fixture', 'runtime': 'fixture', - 'model': 'none', 'effort': 'none'} for i in range(4)]} - - -def fill(root, generation): - for index, name in enumerate(lab.slot_names(configuration(), generation)): - (root / 'slots' / name / 'solution.py').write_text(str(index), encoding='utf-8') - - -def scorer(path, inputs): - index = int(path.read_text(encoding='utf-8')) - # Development favors c03; holdout deliberately favors the opposite candidate. - passed = index + 1 if len(inputs) == 26 else 4 - index - return {'status': 'scored', 'passed': passed, 'total': len(inputs), 'seconds': .01} - - -def test_prepare_reuses_novcs_slots_and_separates_hidden_cases(tmp_path, monkeypatch): - def forbidden(*args, **kwargs): - pytest.fail('preparing NoVcs slots must not execute VCS/runtime commands') - monkeypatch.setattr(lab.slots.subprocess, 'run', forbidden) - root = tmp_path / 'experiment' - state = lab.prepare(root, configuration()) - assert state['phase'] == 'prepared' - assert lab.load(root)[1] == state - adapter = lab.read(root / 'adapter.json') - assert adapter['slots']['vcs'] == 'none' - hidden = lab.read(root / 'private/holdout.json') - assert lab.hashed(hidden['cases']) == state['holdoutHash'] - for name in lab.slot_names(configuration(), 1): - folder = root / 'slots' / name - assert (folder / 'TASK.md').read_text(encoding='utf-8') == lab.SPEC - public = lab.read(folder / 'public.json') - assert len(public) == 26 - assert all(row['expected'] == lab.oracle(row['input']) for row in public) - assert not (folder / 'holdout.json').exists() - assert not (folder / 'private').exists() - assert set(folder.rglob('*.json')) == {folder / 'public.json', folder / 'strategy.json', folder / '.chef' / 'binding.json'} - assert not (root / 'results/released-holdout.json').exists() - with pytest.raises(lab.LabError): - lab.prepare(root, configuration()) - - -@pytest.mark.parametrize('field,value', [ - ('schema', 2), ('schema', True), ('schema', 1.0), ('generations', 0), ('generations', 11), ('generations', True), - ('candidates', 3), ('candidates', 21), ('maxEvaluations', 7), - ('maxSeconds', 0), ('maxConcurrent', 0), ('seed', -1), ('seed', True), - ('costPolicy', 'paid'), ('strategies', []), -]) -def test_config_rejects_invalid_contract(field, value): - config = configuration() - config[field] = value - with pytest.raises(lab.LabError): - lab.config_check(config) - - -@pytest.mark.parametrize('damage', ['path', 'missing-field', 'extra-field', 'bad-kind']) -def test_strategy_metadata_is_explicit_and_safe(damage): - config = configuration() - item = config['strategies'][1] - if damage == 'path': - item['name'] = '../escape' - elif damage == 'missing-field': - item.pop('model') - elif damage == 'extra-field': - item['command'] = 'live-provider' - else: - item['kind'] = 'paid' - with pytest.raises(lab.LabError): - lab.config_check(config) - - -def test_replicated_strategies_keep_independent_candidate_identities(tmp_path): - config = configuration() - config['strategies'][1] = dict(config['strategies'][0]) - root = tmp_path / 'replicated-experiment' - lab.prepare(root, config) - names = lab.slot_names(config, 1) - assert len(set(names)) == config['candidates'] - assert lab.read(root / 'slots' / names[0] / 'strategy.json') == lab.read(root / 'slots' / names[1] / 'strategy.json') - fill(root, 1) - result = lab.evaluate(root, scorer) - assert len(result['results']) == 4 - assert len({row['id'] for row in result['results']}) == 4 - config['strategies'][1]['model'] = 'different-settings' - with pytest.raises(lab.LabError, match='identical settings'): - lab.config_check(config) - - -def test_five_generations_reproducible_and_selection_excludes_holdout(tmp_path, monkeypatch): - monkeypatch.setattr(lab.os, 'urandom', lambda length: b'x' * length) - reports = [] - for label in ('first', 'reproduction'): - root = tmp_path / label - lab.prepare(root, configuration(5)) - for generation in range(1, 6): - fill(root, generation) - if generation > 1: - for name in lab.slot_names(configuration(), generation): - assert (root / 'slots' / name / 'parent.py').read_text() == '3' - result = lab.evaluate(root, scorer) - if generation < 5: - assert all('holdout' not in row for row in result['results']) - assert not (root / 'results/released-holdout.json').exists() - assert result['phase'] == 'complete' - assert result['evaluations'] == 40 - assert result['selections'] == [f'g{generation:02d}-c03' for generation in range(1, 6)] - assert len(result['results']) == 20 - assert all(row['holdout']['passed'] == 4 - int(row['id'][-2:]) for row in result['results']) - assert lab.read(root / 'results/report.json') == result - released = lab.read(root / 'results/released-holdout.json') - assert released['seed'] == lab.load(root)[2]['seed'] - assert lab.cases(released['seed'], released['randomCases']) == lab.load(root)[2]['cases'] - assert lab.replay(root / 'results', scorer)['reproduced'] is True - assert result['cost'] is None and result['credits'] is None - # Root paths and real elapsed coordinator time are intentionally not reproducible. - result.pop('elapsedSeconds') - reports.append(result) - assert reports[0] == reports[1] - - -def test_stop_resume_and_pending_recovery_preserve_consumed_budget(tmp_path): - root = tmp_path / 'experiment' - lab.prepare(root, configuration(budget=8)) - fill(root, 1) - assert lab.control(root, 'stop')['stopped'] - with pytest.raises(lab.LabError, match='stopped'): - lab.evaluate(root, scorer) - assert lab.load(root)[1]['evaluations'] == 0 - assert not lab.control(root, 'resume')['stopped'] - def crash(*args): - raise RuntimeError('synthetic evaluator crash') - with pytest.raises(RuntimeError, match='synthetic'): - lab.evaluate(root, crash) - state = lab.load(root)[1] - assert state['evaluations'] == 1 and state['pending']['split'] == 'development' - with pytest.raises(lab.LabError, match='recover'): - lab.evaluate(root, scorer) - recovered = lab.control(root, 'recover') - assert recovered['evaluations'] == 1 - assert lab.load(root)[1]['pending'] is None - with pytest.raises(lab.LabError, match='budget'): - lab.evaluate(root, scorer) - state = lab.load(root)[1] - assert state['evaluations'] == 8 - assert state['phase'] != 'complete' - assert not (root / 'results/released-holdout.json').exists() - - -def test_holdout_crash_resume_does_not_repeat_selection_or_finished_scores(tmp_path): - root = tmp_path / 'experiment' - lab.prepare(root, configuration(budget=12)) - fill(root, 1) - calls = [] - def crash(path, inputs): - calls.append((path.name, len(inputs))) - if len(calls) == 6: - raise RuntimeError('holdout crash') - return scorer(path, inputs) - with pytest.raises(RuntimeError, match='holdout crash'): - lab.evaluate(root, crash) - before = lab.load(root)[1] - assert before['phase'] == 'holdout' and before['selections'] == ['g01-c03'] - assert 'holdout' in before['results'][0] - assert all('holdout' not in row for row in lab.report(root)['results']) - lab.control(root, 'recover') - completed = [] - def resume(path, inputs): - completed.append(path.name) - return scorer(path, inputs) - result = lab.evaluate(root, resume) - assert result['phase'] == 'complete' - assert result['selections'] == ['g01-c03'] - assert result['evaluations'] == 9 - assert completed == ['g01-c01.py', 'g01-c02.py', 'g01-c03.py'] - - -def test_candidates_frozen_before_any_scoring_and_changes_rejected_on_resume(tmp_path): - root = tmp_path / 'experiment' - lab.prepare(root, configuration(budget=12)) - fill(root, 1) - def crash(path, inputs): - assert all((root / 'snapshots' / f'{name}.py').exists() - for name in lab.slot_names(configuration(), 1)) - raise RuntimeError('crash after freeze') - with pytest.raises(RuntimeError): - lab.evaluate(root, crash) - snapshot = root / 'snapshots/g01-c03.py' - frozen = snapshot.read_bytes() - (root / 'slots/g01-c03/solution.py').write_text('999') - lab.control(root, 'recover') - with pytest.raises(lab.LabError, match='frozen'): - lab.evaluate(root, scorer) - assert snapshot.read_bytes() == frozen - - -@pytest.mark.parametrize('field,value', [('phase', 'unknown'), ('elapsedSeconds', -1), - ('elapsedSeconds', 'bad'), ('pending', []), - ('results', [None]), ('selections', ['../escape']), - ('phase', 'complete'), ('phase', 'holdout'), - ('evaluations', 999), - ('pending', {'id': '../escape', 'split': 'development', 'startedAt': 1})]) -def test_malformed_state_fails_closed_without_mutation(tmp_path, field, value): - root = tmp_path / 'experiment' - lab.prepare(root, configuration()) - path = root / 'state.json' - state = lab.read(path) - state[field] = value - lab.save(path, state) - before = path.read_bytes() - with pytest.raises(lab.LabError): - lab.load(root) - assert path.read_bytes() == before - - -def test_final_publication_crash_can_retry_without_any_rescoring(tmp_path, monkeypatch): - root = tmp_path / 'experiment' - lab.prepare(root, configuration()) - fill(root, 1) - original_save = lab.save - def interrupt(path, value): - if Path(path) == root / 'results/report.json': - raise OSError('synthetic final publication failure') - return original_save(path, value) - with monkeypatch.context() as patch: - patch.setattr(lab, 'save', interrupt) - with pytest.raises(OSError, match='publication failure'): - lab.evaluate(root, scorer) - assert lab.load(root)[1]['phase'] == 'complete' - def forbidden(*args): - pytest.fail('completed experiment must republish without scoring') - result = lab.evaluate(root, forbidden) - assert result['evaluations'] == 8 - assert lab.read(root / 'results/report.json') == result - assert (root / 'results/released-holdout.json').is_file() - - -def test_saved_candidate_hash_detects_snapshot_tampering(tmp_path): - root = tmp_path / 'experiment' - lab.prepare(root, configuration(budget=12)) - fill(root, 1) - calls = [] - def crash(path, inputs): - calls.append(path.name) - if len(calls) == 2: - raise RuntimeError('synthetic partial development crash') - return scorer(path, inputs) - with pytest.raises(RuntimeError): - lab.evaluate(root, crash) - (root / 'snapshots/g01-c00.py').write_text('999') - with pytest.raises(lab.LabError, match='integrity'): - lab.load(root) - - -@pytest.mark.parametrize('field,value', [('passed', -1), ('total', 0), ('seconds', float('nan')), - ('status', 'pass'), ('passed', True)]) -def test_invalid_scorer_result_preserves_pending_consumed_attempt(tmp_path, field, value): - root = tmp_path / 'experiment' - lab.prepare(root, configuration()) - fill(root, 1) - def invalid(path, inputs): - result = scorer(path, inputs) - result[field] = value - return result - with pytest.raises(lab.LabError, match='scorer'): - lab.evaluate(root, invalid) - state = lab.load(root)[1] - assert state['evaluations'] == 1 - assert state['pending'] is not None - assert not state['results'] - - -@pytest.fixture -def bubblewrap(): - if sys.platform != 'linux' or not shutil.which('bwrap'): - pytest.skip('Linux bubblewrap is unavailable; unsafe execution is never substituted') - probe = subprocess.run(['bwrap', '--unshare-all', '--ro-bind', '/usr', '/usr', - '--symlink', 'usr/lib', '/lib', '--symlink', 'usr/lib64', '/lib64', - '/usr/bin/true'], capture_output=True, timeout=10) - if probe.returncode: - message = probe.stderr.decode(errors='replace') - if any(reason in message.lower() for reason in ('operation not permitted', 'no permissions', - 'creating new namespace failed')): - pytest.skip('kernel/runner does not permit bubblewrap namespaces: ' + message.strip()) - pytest.fail('unexpected bubblewrap probe failure: ' + message) - - -def test_real_bubblewrap_blocks_host_holdout_environment_network_and_writes(tmp_path, monkeypatch, bubblewrap): - secret = tmp_path / 'private-host-file' - secret.write_text('synthetic secret') - hidden = tmp_path / 'private/holdout.json' - hidden.parent.mkdir() - hidden.write_text('synthetic holdout') - monkeypatch.setenv('CHEF_SYNTHETIC_SECRET', 'must not reach candidate') - code = tmp_path / 'solution.py' - code.write_text('import os, socket\n' - 'def solve(intervals):\n' - ' assert "CHEF_SYNTHETIC_SECRET" not in os.environ\n' - f' for path in ({str(secret)!r}, {str(hidden)!r}):\n' - ' try:\n' - ' open(path).read()\n' - ' except OSError:\n' - ' pass\n' - ' else:\n' - ' raise AssertionError("host file readable")\n' - ' try:\n' - ' open("/candidate/solution.py", "w").write("changed")\n' - ' except OSError:\n' - ' pass\n' - ' else:\n' - ' raise AssertionError("snapshot writable")\n' - ' with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as connection:\n' - ' try:\n' - ' connection.connect(("192.0.2.1", 9))\n' - ' except OSError:\n' - ' pass\n' - ' else:\n' - ' raise AssertionError("network route available")\n' - ' return []\n', encoding='utf-8') - before = code.read_bytes() - result = lab.isolated_score(code, [[]]) - assert result['status'] == 'scored' and result['passed'] == 1 - assert code.read_bytes() == before - assert secret.read_text() == 'synthetic secret' - - -def test_real_bubblewrap_runaway_candidate_is_bounded(tmp_path, bubblewrap): - code = tmp_path / 'solution.py' - code.write_text('def solve(intervals):\n while True:\n pass\n') - result = lab.isolated_score(code, [[]], timeout=.2) - assert result['status'] == 'timeout' and result['passed'] == 0 - assert result['seconds'] < 5 - - -def test_real_bubblewrap_scores_solution_and_rejects_input_mutation(tmp_path, bubblewrap): - code = tmp_path / 'solution.py' - implementation = ('def solve(intervals):\n' - ' result = []\n' - ' for start, end in sorted(intervals):\n' - ' if result and start <= result[-1][1]:\n' - ' result[-1][1] = max(end, result[-1][1])\n' - ' else:\n' - ' result.append([start, end])\n' - ' return result\n') - inputs = lab.cases(27, 20) - code.write_text(implementation) - result = lab.isolated_score(code, inputs) - assert result['status'] == 'scored' and result['passed'] == result['total'] == len(inputs) - # The answers still match, but mutating the supplied list disqualifies the case. - code.write_text(implementation.replace(' return result', ' intervals.clear()\n return result')) - result = lab.isolated_score(code, [[[1, 2], [2, 4]]]) - assert result['status'] == 'scored' and result['passed'] == 0 - - -def test_unsupported_sandbox_has_no_unisolated_fallback(tmp_path, monkeypatch): - monkeypatch.setattr(lab.shutil, 'which', lambda name: None) - code = tmp_path / 'solution.py' - code.write_text('raise RuntimeError("must never execute")') - with pytest.raises(lab.LabError, match='bubblewrap'): - lab.isolated_score(code, [[]]) - - -PUBLISHED = REPO_ROOT / 'examples/lab/interval-union' - - -def published_tree(root): - return {str(path.relative_to(root)): path.read_bytes() for path in root.rglob('*') if path.is_file()} - - -def test_generated_publication_replays_without_manual_assembly(tmp_path): - root = tmp_path / 'experiment' - lab.prepare(root, configuration()) - fill(root, 1) - result = lab.evaluate(root, scorer) - assert result['phase'] == 'complete' - before = published_tree(root / 'results') - assert lab.replay(root / 'results', scorer)['reproduced'] is True - assert published_tree(root / 'results') == before - - -def test_published_fixture_replay_checks_released_seed_hashes_and_is_readonly(): - before = published_tree(PUBLISHED) - published = lab.read(PUBLISHED / 'report.json') - config = lab.read(PUBLISHED / 'config.json') - released = lab.read(PUBLISHED / 'released-holdout.json') - assert published['config'] == config - assert published['configHash'] == lab.hashed(config) - inputs = lab.cases(released['seed'], 100) - assert published['holdoutHash'] == lab.hashed(inputs) - expected = {row['id']: row for row in published['results']} - seen = [] - def fake_score(path, inputs): - row = expected[path.stem] - assert inputs == lab.cases(released['seed'], 100) - assert lab.hashed(path.read_bytes()) == row['codeHash'] - seen.append(path.stem) - return {key: row['holdout'][key] for key in ('status', 'passed', 'total', 'seconds')} - replay = lab.replay(PUBLISHED, fake_score) - assert replay['reproduced'] is True - assert replay['mode'] == 'released_data_replay' - assert seen == list(expected) - assert replay['cost'] is None and replay['credits'] is None - assert published_tree(PUBLISHED) == before - - -@pytest.mark.parametrize('damage', ['seed', 'code-hash', 'traversal', 'empty-results', 'config-hash']) -def test_replay_rejects_damaged_publication_before_running_candidate(tmp_path, damage): - root = tmp_path / 'publication' - shutil.copytree(PUBLISHED, root) - report = lab.read(root / 'report.json') - if damage == 'seed': - released = lab.read(root / 'released-holdout.json') - released['seed'] += 1 - lab.save(root / 'released-holdout.json', released) - elif damage == 'code-hash': - candidate = root / 'candidates' / f"{report['results'][0]['id']}.py" - candidate.write_bytes(candidate.read_bytes() + b'\n# changed\n') - elif damage == 'traversal': - report['results'][0]['id'] = '../outside' - elif damage == 'empty-results': - report['results'] = [] - else: - report['configHash'] = 'invalid' - lab.save(root / 'report.json', report) - before = published_tree(root) - def forbidden(*args): - pytest.fail('damaged publication must fail before candidate execution') - with pytest.raises(lab.LabError): - lab.replay(root, forbidden) - assert published_tree(root) == before - - -def test_real_bubblewrap_reproduces_published_fixture_without_mutation(bubblewrap): - before = published_tree(PUBLISHED) - replay = lab.replay(PUBLISHED) - assert replay['reproduced'] is True - assert len(replay['results']) == 4 - assert all(row['matchesPublishedScore'] for row in replay['results']) - assert published_tree(PUBLISHED) == before - - -@pytest.mark.parametrize('answer', ['[[True, 2]]', '[[1, 2.0]]']) -def test_real_bubblewrap_rejects_noninteger_interval_answers(tmp_path, bubblewrap, answer): - code = tmp_path / 'solution.py' - code.write_text(f'def solve(intervals):\n return {answer}\n') - result = lab.isolated_score(code, [[[1, 2]]]) - assert result['status'] == 'scored' - assert result['passed'] == 0 diff --git a/tests/integration/mission/test_mission_flow.py b/tests/integration/mission/test_mission_flow.py new file mode 100644 index 0000000..695e4e4 --- /dev/null +++ b/tests/integration/mission/test_mission_flow.py @@ -0,0 +1,19 @@ +"""A unit cannot be completed from a passing receipt alone.""" +from chef.mission import state as mission_state + +from tests.support import open_mission, verify_mission + + +def test_open_mission_records_one_doing_unit(tmp_path, monkeypatch): + _root, folder, _plan = open_mission(tmp_path, monkeypatch) + text = (folder / "units.tsv").read_text(encoding="utf-8") + assert "M1" in text and "doing" in text + + +def test_complete_without_review_is_rejected(tmp_path, monkeypatch): + root, folder, _plan = open_mission(tmp_path, monkeypatch) + code, receipt = verify_mission(root, folder) + assert code == 0 + assert mission_state.main([ + "complete", "M1", "--receipt", str(receipt), "--done-evidence", "checked", + ]) != 0 diff --git a/tests/integration/mission/test_mission_state.py b/tests/integration/mission/test_mission_state.py deleted file mode 100644 index 3629a20..0000000 --- a/tests/integration/mission/test_mission_state.py +++ /dev/null @@ -1,1386 +0,0 @@ -import hashlib -import json -import os -import subprocess -import sys -from datetime import datetime, timedelta -from io import BytesIO -from pathlib import Path - -import pytest -from chef.mission import documents as mission_documents -from chef.mission import state as mission_state - -from tests.paths import PLUGIN_ROOT - -SCRIPT = (PLUGIN_ROOT / 'skills/mission/scripts/mission_state.py') -ADAPTER = { - "schema": 1, - "paths": {"stateDir": "state"}, - "stages": [{"id": "content"}, {"id": "poc"}, {"id": "impl"}, {"id": "review"}], - "verify": {"grades": ["editmode-pass", "pytest-pass"]}, -} -BRIEF = ["--goal", "목표", "--files", "a.cs", "--done", "테스트 1개", "--verify", "pytest", "--timebox", "60", "--forbid", "submit"] - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_inspect_standalone_without_adapter_or_active(tmp_path, monkeypatch, capsys, runtime): - plan = {"grade": "pytest-pass", "inputs": ["missing-source.py"], "environment": {"target": "fictional"}, - "commands": [{"id": "unit-tests", "argv": ["nonexistent-executable"]}]} - source = tmp_path / "plan.json" - source.write_text(json.dumps(plan), encoding="utf-8") - monkeypatch.chdir(tmp_path) - - def unexpected(*args, **kwargs): - pytest.fail("standalone inspect accessed mission infrastructure") - - monkeypatch.setattr(mission_state.infrastructure_configuration, "locate", unexpected) - monkeypatch.setattr(mission_state.infrastructure_locking, "FileLock", unexpected) - monkeypatch.setattr(mission_state.mission_guard, "read_active", unexpected) - monkeypatch.setattr(subprocess, "run", unexpected) - before = source.read_bytes() - assert mission_state.main(["inspect", "--plan", str(source)], runtime=runtime) == 0 - captured = capsys.readouterr() - result = json.loads(captured.out) - assert captured.err == "" - assert result["kind"] == "plan" and result["current_validity"] == "not_checked" - assert result["steps"]["items"] == [{"index": 0, "id": "unit-tests"}] - assert source.read_bytes() == before - assert list(tmp_path.iterdir()) == [source] - - -@pytest.mark.parametrize("content,options", [ - ("{", ["--plan"]), ("[]", ["--plan"]), ("{}", ["--receipt"]), - ('{"kind":"review","schema":1}', ["--receipt"]), - ('{"schema":99}', ["--receipt"]), ("{}", []), ("{}", ["--plan", "--receipt"]), - ("invalid-encoding", ["--receipt"]), -]) -def test_inspect_invalid_input_has_one_line_error_and_no_state(tmp_path, monkeypatch, capsys, content, options): - source = tmp_path / "invalid.json" - if content == "invalid-encoding": - source.write_bytes(b"\xff\xfe") - else: - source.write_text(content, encoding="utf-8") - args = ["inspect"] - for option in options: - args.extend([option, str(source)]) - monkeypatch.chdir(tmp_path) - before = source.read_bytes() - assert mission_state.main(args) == 1 - captured = capsys.readouterr() - assert captured.out == "" - assert captured.err.startswith("오류:") and len(captured.err.splitlines()) == 1 - assert "Traceback" not in captured.err - assert source.read_bytes() == before - assert list(tmp_path.iterdir()) == [source] - - -def test_inspect_preserves_existing_mission_files(tmp_path, monkeypatch, capsys): - state = tmp_path / "state" - state.mkdir() - (state / "ACTIVE").write_bytes(b"existing active marker") - (state / "mission.md").write_bytes(b"existing mission") - source = tmp_path / "receipt.json" - source.write_text(json.dumps({"schema": 1, "status": "fail", "unit": "M1", "grade": "unknown", - "plan": {}, "snapshot": {}, "results": {}, "log": "missing.log", "error": "bad plan"}), - encoding="utf-8") - before = {str(path.relative_to(tmp_path)): path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()} - monkeypatch.chdir(tmp_path) - assert mission_state.main(["inspect", "--receipt", str(source)]) == 0 - assert json.loads(capsys.readouterr().out)["recorded"]["error"] == "bad plan" - after = {str(path.relative_to(tmp_path)): path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()} - assert before == after - - -@pytest.mark.parametrize("option", ["--plan", "--receipt"]) -def test_inspect_empty_or_missing_path_has_no_traceback(tmp_path, monkeypatch, capsys, option): - monkeypatch.chdir(tmp_path) - for path in ("", "missing.json"): - assert mission_state.main(["inspect", option, path]) == 1 - captured = capsys.readouterr() - assert captured.out == "" - assert captured.err == "오류: inspect: 파일 읽기 실패\n" - assert list(tmp_path.iterdir()) == [] - - -def test_inspect_rejects_unrepresentable_receipt_seconds(tmp_path, monkeypatch, capsys): - source = tmp_path / "receipt.json" - source.write_text(json.dumps({"schema": 1, "status": "fail", "unit": "M1", "grade": "unknown", - "plan": {}, "snapshot": {}, "results": {}, "log": "missing.log", "error": "bad plan", - "seconds": 10 ** 400}), encoding="utf-8") - monkeypatch.chdir(tmp_path) - before = source.read_bytes() - assert mission_state.main(["inspect", "--receipt", str(source)]) == 1 - captured = capsys.readouterr() - assert captured.out == "" - assert captured.err == "오류: inspect: receipt.seconds 형식 오류\n" - assert source.read_bytes() == before - assert list(tmp_path.iterdir()) == [source] - - -class Mission: - def __init__(self, root, capsys): - self.root = root - self.capsys = capsys - self.folder = root / "state" / "m1" - adapter_dir = root / ".claude" / "orchestrator" - adapter_dir.mkdir(parents=True) - (adapter_dir / "adapter.json").write_text(json.dumps(ADAPTER), encoding="utf-8") - (root / "state").mkdir() - (root / "state" / "ACTIVE").write_text( - json.dumps({"id": "m1", "session": "s1", "openedAt": "2026-10-19T09:00:00+09:00"}), encoding="utf-8" - ) - - def run(self, *args): - self.capsys.readouterr() - code = mission_state.main(["--project", str(self.root), *args]) - captured = self.capsys.readouterr() - return code, captured.out.rstrip("\n"), captured.err.rstrip("\n") - - def ok(self, *args): - code, out, err = self.run(*args) - assert code == 0, err - return out - - def fail(self, *args): - code, out, err = self.run(*args) - assert code == 1 and out == "" and "\n" not in err, (code, out, err) - return err - - def question_record(self, name="ask-1.md", statuses=("pending",), approval="none", **changes): - record = { - "schema": 1, - "id": name.removesuffix(".md"), - "revision": 1, - "title": "질문", - "intro": "", - "items": [{"id": str(index), "title": f"선택 {index}", "body": "", "status": status, - "answer": "진행" if status == "answered" else ""} - for index, status in enumerate(statuses, start=1)], - "body": "", - "approval": {"status": approval, "reason": "전체 승인 필요" if approval == "pending" else ""}, - "answers": [], - } - record.update(changes) - return record - - def publish_question(self, *args, **kwargs): - record = self.question_record(*args, **kwargs) - if record['id'].startswith('confirm-A'): - source = mission_state.question_records.source_path(self.folder, record['id'] + '.md') - source.parent.mkdir(exist_ok=True) - source.write_text(json.dumps(record), encoding='utf-8') - return mission_state.question_records.publish_document(self.folder, record) - - def json_input(self, name, value): - path = self.root / name - path.write_text(json.dumps(value, ensure_ascii=False), encoding="utf-8") - return str(path) - - def add_unit(self, unit_id="M1", *extra): - return self.ok("unit", "add", unit_id, *BRIEF, *extra) - - def read(self, name): - return (self.folder / name).read_text(encoding="utf-8") - - def table(self, name): - return [line.split("\t") for line in self.read(name).splitlines()] - - def backdate(self, unit_id, minutes): - started = (datetime.now().astimezone() - timedelta(minutes=minutes)).isoformat(timespec="seconds") - rows = self.table("units.tsv") - for row in rows[1:]: - if row[0] == unit_id: - row[10] = started - (self.folder / "units.tsv").write_text("\n".join("\t".join(r) for r in rows) + "\n", encoding="utf-8") - - -@pytest.fixture -def mission(tmp_path, capsys, monkeypatch): - for name in ("CLAUDE_PROJECT_DIR", "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "CLAUDE_CONFIG_DIR", "CODEX_HOME"): - monkeypatch.delenv(name, raising=False) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "no-registry")) - return Mission(tmp_path / "project", capsys) - - -@pytest.fixture -def opened(mission): - mission.ok("init", "--goal", "서버 이관") - return mission - - -def test_init_requires_guard_to_be_on(mission): - (mission.root / "state" / "ACTIVE").unlink() - assert "mission_control.py open m1" in mission.fail("--mission", "m1", "init") - (mission.root / "state" / "ACTIVE").write_text(json.dumps({"id": "m1", "session": ""}), encoding="utf-8") - assert "가드 안 켜짐" in mission.fail("init") - (mission.root / "state" / "ACTIVE").write_text(json.dumps({"id": "other", "session": "s1"}), encoding="utf-8") - assert "가드 안 켜짐" in mission.fail("--mission", "m1", "init") - assert not mission.folder.exists() - - -def test_commands_need_an_id_from_active_or_flag(mission): - (mission.root / "state" / "ACTIVE").unlink() - assert "미션 id 없음" in mission.fail("status") - - -def test_init_copies_templates_fills_id_state_and_goal(mission): - out = mission.ok("init", "--goal", "서버 이관") - assert "만듦: mission.md units.tsv ledger.tsv decisions.tsv report.md" in out - text = mission.read("mission.md") - assert "# 미션 m1" in text and "" not in text - assert "상태: 진행" in text and "상태: 준비" not in text - assert "## 목표\n\n서버 이관\n\n## " in text - assert "" not in mission.read("report.md") - assert mission.read("units.tsv").startswith("id\tgoal\tfiles\tdone\tverify\ttimebox\tforbid\thuman\tafter\tunit\tstarted\tstatus") - - -def test_init_without_tier_warns_but_opens(mission): - out = mission.ok("init", "--goal", "서버 이관") - assert "--tier 없음" in out - assert "티어:" not in mission.read("mission.md") - - -def test_init_records_tier(mission): - out = mission.ok("init", "--tier", "m", "--goal", "서버 이관") - assert "경고" not in out - assert "상태: 진행\n티어: M\n현재 단계:" in mission.read("mission.md") - - -def test_init_refuses_small_tier_unless_forced(mission): - err = mission.fail("init", "--tier", "S") - assert "S 티어는 미션으로 열지 않음" in err and "mission_control.py close m1" in err - assert not mission.folder.exists() - assert "S·M·L" in mission.fail("init", "--tier", "XL") - out = mission.ok("init", "--tier", "S", "--force-tier") - assert "--force-tier" in out - assert "티어: S" in mission.read("mission.md") - - -def test_init_does_not_overwrite_existing_files(opened): - (opened.folder / "mission.md").write_text("손으로 고친 것\n", encoding="utf-8") - (opened.folder / "ledger.tsv").unlink() - out = opened.ok("init", "--goal", "다른 목표") - assert "만듦: ledger.tsv" in out and "건너뜀: mission.md" in out - assert opened.read("mission.md") == "손으로 고친 것\n" - - -def test_mission_set_changes_only_header_values(opened): - out = opened.ok("mission", "set", "--stage", "impl", "--confirm", "A=승인", "--confirm", "B=대기", "--state", "중단") - assert out == "상태 중단 | 현재 단계 impl | 확인 A 승인, B 대기, C 대기" - text = opened.read("mission.md") - assert "현재 단계: impl\n" in text and "확인 A: 승인\n" in text and "상태: 중단\n" in text - assert "## 목표\n\n서버 이관\n" in text - - -def test_mission_set_adds_missing_confirm_line_after_last_confirm(opened): - out = opened.ok("mission", "set", "--confirm", "A1=승인") - assert out.endswith("확인 A 대기, B 대기, C 대기, A1 승인") - lines = opened.read("mission.md").splitlines() - assert lines[lines.index("확인 C: 대기") + 1] == "확인 A1: 승인" - - -def test_mission_set_rejects_bad_values(opened): - before = opened.read("mission.md") - assert "허용 값" in opened.fail("mission", "set", "--stage", "nope") - assert "K=V" in opened.fail("mission", "set", "--confirm", "A승인") - assert "바꿀 값 없음" in opened.fail("mission", "set") - assert "invalid choice" in opened.fail("mission", "set", "--state", "준비") - assert opened.read("mission.md") == before - - -@pytest.mark.parametrize("mutation,operation", [ - ("markdown", "stage"), ("markdown", "confirm"), ("markdown", "resume"), ("markdown", "close"), - ("markdown", "doing"), ("markdown", "complete"), ("markdown", "share"), - ("corrupt-json", "stage"), ("missing-json", "stage"), ("missing-markdown", "stage"), ("missing-history", "stage"), -]) -def test_question_integrity_precedes_progress_completion_and_sharing(opened, mutation, operation): - opened.add_unit() - if operation == "complete": - opened.ok("unit", "set", "M1", "--status", "doing") - opened.publish_question() - if mutation == "markdown": - path = opened.folder / "ask-1.md" - path.write_text(path.read_text(encoding="utf-8") + "\nUnrecorded fictional answer\n", encoding="utf-8") - elif mutation == "corrupt-json": - (opened.folder / "questions/ask-1.json").write_text("{broken", encoding="utf-8") - else: - name = {"missing-json": "questions/ask-1.json", "missing-markdown": "ask-1.md", - "missing-history": "details/history/ask-1.md"}[mutation] - (opened.folder / name).unlink() - commands = { - "stage": ("mission", "set", "--stage", "impl"), - "confirm": ("mission", "set", "--confirm", "A=approved"), - "resume": ("mission", "set", "--state", "진행"), - "close": ("mission", "set", "--state", "닫힘"), - "doing": ("unit", "set", "M1", "--status", "doing"), - "complete": ("complete", "M1", "--receipt", "missing-receipt.json", "--review", "missing-review.json", "--done-evidence", "verified"), - "share": ("document", "share", "report.md"), - } - before = {str(path.relative_to(opened.folder)): path.read_bytes() for path in opened.folder.rglob("*") if path.is_file()} - error = opened.fail(*commands[operation]) - assert "질문 기록 확인 필요" in error and "ask-1.md" in error - after = {str(path.relative_to(opened.folder)): path.read_bytes() for path in opened.folder.rglob("*") if path.is_file()} - assert after == before - - -def test_pending_questions_allow_existing_progress_and_sharing_semantics(opened): - opened.add_unit() - opened.publish_question() - opened.ok("mission", "set", "--stage", "impl", "--confirm", "A=approved") - opened.ok("unit", "set", "M1", "--status", "doing") - opened.ok("document", "share", "report.md") - assert "ask-1.md 답 없음" in opened.ok("status") - - -def test_bad_question_integrity_keeps_pause_reads_and_repair_available(opened): - opened.add_unit() - opened.publish_question() - path = opened.folder / "ask-1.md" - path.write_text(path.read_text(encoding="utf-8") + "\nUnrecorded fictional answer\n", encoding="utf-8") - assert "기록 확인 필요" in opened.ok("status") - assert "기록 확인 필요" in opened.ok("context") - opened.ok("unit", "list") - opened.ok("mission", "set", "--state", "중단") - opened.ok("question", "render", "ask-1.md") - opened.ok("question", "check") - opened.ok("mission", "set", "--state", "진행") - opened.ok("unit", "set", "M1", "--status", "doing") - - -def make_poc(mission, name="x"): - poc = mission.root / "Wiki" / "design" / "prototypes" / name / "index.html" - poc.parent.mkdir(parents=True) - poc.write_text("", encoding="utf-8") - return poc - - -def test_mission_set_poc_stores_root_relative_path_for_relative_and_absolute_input(opened): - poc = make_poc(opened) - assert opened.ok("mission", "set", "--poc", "Wiki\\design\\prototypes\\x\\index.html").startswith("상태 진행") - assert "PoC: Wiki/design/prototypes/x/index.html\n" in opened.read("mission.md") - opened.ok("mission", "set", "--poc", "Wiki/design/../design/prototypes/x/index.html") - assert opened.read("mission.md").count("PoC: Wiki/design/prototypes/x/index.html\n") == 1 - other = make_poc(opened, "y") - opened.ok("mission", "set", "--poc", str(other)) - assert "PoC: Wiki/design/prototypes/y/index.html\n" in opened.read("mission.md") - assert str(poc) not in opened.read("mission.md") - - -def test_mission_set_poc_rejects_missing_file_and_paths_outside_workspace(opened): - make_poc(opened) - before = opened.read("mission.md") - assert "파일 없음" in opened.fail("mission", "set", "--poc", "Wiki/design/prototypes/none/index.html") - assert "파일 없음" in opened.fail("mission", "set", "--poc", "Wiki") - outside = opened.root.parent / "outside.html" - outside.write_text("x", encoding="utf-8") - assert "밖" in opened.fail("mission", "set", "--poc", str(outside)) - assert "밖" in opened.fail("mission", "set", "--poc", "../outside.html") - assert "비어 있음" in opened.fail("mission", "set", "--poc", " ") - assert opened.read("mission.md") == before - - -def test_mission_set_poc_inserts_after_last_confirm_or_stage_line(opened): - make_poc(opened) - opened.ok("mission", "set", "--poc", "Wiki/design/prototypes/x/index.html") - lines = opened.read("mission.md").splitlines() - assert lines[lines.index("확인 C: 대기") + 1] == "PoC: Wiki/design/prototypes/x/index.html" - stripped = [line for line in lines if not line.startswith(("PoC:", "확인 "))] - (opened.folder / "mission.md").write_text("\n".join(stripped) + "\n", encoding="utf-8") - opened.ok("mission", "set", "--poc", "Wiki/design/prototypes/x/index.html") - lines = opened.read("mission.md").splitlines() - assert lines[lines.index("현재 단계: content") + 1] == "PoC: Wiki/design/prototypes/x/index.html" - - -def test_mission_set_poc_works_with_other_values_and_new_confirm_stays_before_it(opened): - make_poc(opened) - opened.ok("mission", "set", "--stage", "impl", "--poc", "Wiki/design/prototypes/x/index.html", "--confirm", "A1=승인") - lines = opened.read("mission.md").splitlines() - assert "현재 단계: impl" in lines and "확인 A1: 승인" in lines - assert lines.index("확인 A1: 승인") < lines.index("PoC: Wiki/design/prototypes/x/index.html") - assert mission_state.header_fields(lines)["PoC"] == "Wiki/design/prototypes/x/index.html" - - -def test_unit_add_writes_todo_row_with_defaults(opened): - assert opened.add_unit("M1") == "M1 추가 (todo, timebox 60분, after -)" - assert opened.table("units.tsv")[1] == ["M1", "목표", "a.cs", "테스트 1개", "pytest", "60", "submit", "-", "-", "?", "", "todo"] - - -def test_unit_add_flattens_tabs_and_newlines(opened): - opened.ok("unit", "add", "M1", "--goal", "한 줄\n두 줄\t탭", *BRIEF[2:]) - row = opened.table("units.tsv")[1] - assert len(row) == 12 and row[1] == "한 줄 두 줄 탭" - - -def test_unit_add_rejects_empty_brief_fields(opened): - err = opened.fail("unit", "add", "M1", "--goal", "목표", "--timebox", "60") - assert "브리프 빈 칸: files, done, verify, forbid" in err - assert "no units written" in err - assert len(opened.table("units.tsv")) == 1 - - -def test_unit_add_rejects_duplicate_bad_timebox_and_unknown_after(opened): - opened.add_unit("M1") - assert "이미 있음" in opened.fail("unit", "add", "M1", *BRIEF) - for bad in ("0", "-5", "1.5", "abc"): - assert "양의 정수" in opened.fail("unit", "add", "M2", *BRIEF[:8], "--timebox", bad, *BRIEF[10:]) - assert "M9" in opened.fail("unit", "add", "M2", *BRIEF, "--after", "M9") - opened.ok("unit", "add", "M2", *BRIEF, "--after", "M1, M1", "--human", "화면 확인") - assert opened.table("units.tsv")[2][7:9] == ["화면 확인", "M1"] - - -def test_usage_errors_are_one_line_with_exit_code_1(opened): - assert "required" in opened.fail("ledger", "record", "M1", "--status", "pass") - assert "required" in opened.fail("unit") - assert "invalid choice" in opened.fail("nope") - assert "invalid choice" in opened.fail("unit", "set", "M1", "--status", "bogus") - assert opened.run("-h")[0] == 0 - - -def test_unit_set_doing_needs_finished_after_and_stamps_started(opened): - opened.add_unit("M1") - opened.add_unit("M2", "--after", "M1") - assert "M1(todo)" in opened.fail("unit", "set", "M2", "--status", "doing") - opened.ok("unit", "set", "M1", "--status", "doing", "--unit", "CL123") - row = opened.table("units.tsv")[1] - assert row[9] == "CL123" and row[11] == "doing" - assert datetime.fromisoformat(row[10]).tzinfo is not None - - -def test_legacy_ledger_pass_cannot_bypass_verified_complete(opened): - opened.add_unit("M1") - assert "complete" in opened.fail("unit", "set", "M1", "--status", "done") - opened.ok("ledger", "record", "M1", "--status", "pass", "--grade", "pytest-pass", "--evidence", "3 passed") - opened.ok("ledger", "record", "M1", "--status", "fail", "--grade", "pytest-pass", "--evidence", "1 failed") - assert "complete" in opened.fail("unit", "set", "M1", "--status", "done") - opened.ok("ledger", "record", "M1", "--status", "pass", "--grade", "pytest-pass", "--evidence", "4 passed") - assert "complete" in opened.fail("unit", "set", "M1", "--status", "done") - assert opened.table("units.tsv")[1][11] == "todo" - - -def test_unit_set_edits_brief_but_never_blanks_it(opened): - opened.add_unit("M1") - assert opened.ok("unit", "set", "M1", "--goal", "새 목표", "--timebox", "30") == "M1 갱신: goal, timebox" - assert opened.table("units.tsv")[1][1:6:4] == ["새 목표", "30"] - assert "빈 값" in opened.fail("unit", "set", "M1", "--done", " ") - assert "빈 값" in opened.fail("unit", "set", "M1", "--after", "") - assert "바꿀 칸 없음" in opened.fail("unit", "set", "M1") - assert "없음" in opened.fail("unit", "set", "M7", "--goal", "x") - - -def test_unit_list_shows_progress_and_overrun(opened): - opened.add_unit("M1") - opened.add_unit("M2") - opened.ok("unit", "set", "M1", "--status", "doing", "--unit", "CL123") - opened.backdate("M1", 12) - assert opened.ok("unit", "list").splitlines() == ["M1 doing 12/60분 CL123 목표", "M2 todo -/60분 ? 목표"] - opened.backdate("M1", 75) - assert opened.ok("unit", "list", "--status", "doing") == "M1 doing 75/60분 넘김 CL123 목표" - assert opened.ok("unit", "list", "--status", "held") == "마일스톤 없음" - - -def test_ledger_record_appends_row_with_adapter_grade(opened): - opened.add_unit("M1") - assert opened.ok("ledger", "record", "M1", "--status", "pass", "--grade", "needs-human", "--evidence", "화면") == "ledger M1 pass needs-human" - opened.ok("ledger", "record", "M1", "--status", "retry", "--grade", "editmode-pass", "--evidence", "run 7", "--files", "a.cs,b.cs") - rows = opened.table("ledger.tsv") - assert rows[0] == ["at", "unit", "status", "grade", "evidence", "files"] - assert rows[1][1:] == ["M1", "pass", "needs-human", "화면", "-"] - assert rows[2][1:] == ["M1", "retry", "editmode-pass", "run 7", "a.cs,b.cs"] - assert datetime.fromisoformat(rows[1][0]).tzinfo is not None - - -def test_ledger_record_rejects_unknown_unit_grade_and_blank_evidence(opened): - opened.add_unit("M1") - assert "M9 없음" in opened.fail("ledger", "record", "M9", "--status", "pass", "--grade", "pytest-pass", "--evidence", "x") - err = opened.fail("ledger", "record", "M1", "--status", "pass", "--grade", "magic", "--evidence", "x") - assert "editmode-pass, pytest-pass, needs-human" in err - assert "--evidence" in opened.fail("ledger", "record", "M1", "--status", "pass", "--grade", "pytest-pass") - assert len(opened.table("ledger.tsv")) == 1 - - -def test_decision_add_numbers_ids_and_keeps_old_rows_byte_for_byte(opened): - assert opened.ok("decision", "add", "--what", "범위", "--chosen", "좁게", "--why", "되돌리기 쉬움", "--affects", "M1") == "D1 추가" - opened.ok("decision", "add", "--what", "순서", "--chosen", "A 먼저", "--why", "의존", "--affects", "M2") - before = opened.read("decisions.tsv") - assert opened.ok("decision", "add", "--what", "다시 판단", "--chosen", "B 먼저", "--why", "새 근거", "--affects", "M2", "--fixes", "D2") == "D3 추가 (D2 정정)" - after = opened.read("decisions.tsv") - assert after.startswith(before) - last = after.splitlines()[-1].split("\t") - assert last[1:] == ["D3", "D2 정정: 다시 판단", "B 먼저", "새 근거", "M2"] - - -def test_decision_add_rejects_unknown_fix_and_blank_fields(opened): - assert "D3" in opened.fail("decision", "add", "--what", "a", "--chosen", "b", "--why", "c", "--affects", "d", "--fixes", "D3") - assert "--why" in opened.fail("decision", "add", "--what", "a", "--chosen", "b", "--affects", "d") - assert len(opened.table("decisions.tsv")) == 1 - - -def test_malformed_table_is_reported_with_line_number(opened): - (opened.folder / "units.tsv").write_text(opened.read("units.tsv") + "M1\t목표\n", encoding="utf-8") - assert "2행 칸 수 2" in opened.fail("unit", "list") - - -def test_status_prints_three_lines(opened): - for number in range(1, 7): - opened.add_unit(f"M{number}") - opened.ok("ledger", "record", f"M{number}", "--status", "pass", "--grade", "pytest-pass", "--evidence", "ok") - rows = mission_state.read_table(str(opened.folder / "units.tsv"), mission_state.UNIT_HEADER) - rows[-1]["status"] = "done" - mission_state.write_table(str(opened.folder / "units.tsv"), mission_state.UNIT_HEADER, rows) - opened.add_unit("M7") - opened.ok("unit", "set", "M7", "--status", "doing") - opened.backdate("M7", 90) - opened.ok("mission", "set", "--stage", "impl", "--confirm", "A=승인") - opened.publish_question("confirm-B.md", approval="pending") - opened.publish_question("confirm-A.md", ("answered",), "complete") - opened.publish_question("ask-1.md") - opened.publish_question("ask-2.md") - opened.ok("document", "share", "confirm-B.md", "ask-1.md", "ask-2.md") - lines = opened.ok("status").splitlines() - assert lines[0] == "마일스톤 todo 0, doing 1, done 6, held 0 | 현재 단계 impl | 확인 A 승인, B 대기, C 대기" - assert lines[1] == "판정: M3 pass pytest-pass, M4 pass pytest-pass, M5 pass pytest-pass, M6 pass pytest-pass 외 2개" - assert lines[2] == "걸린 것: M7 timebox 넘김(90/60분), ask-1.md 답 없음, ask-2.md 답 없음, confirm-B.md 답 없음" - - -def test_status_with_nothing_stuck(opened): - lines = opened.ok("status").splitlines() - assert lines[1:] == ["판정: 없음", "걸린 것: 없음"] - - -def test_unanswered_questions_uses_item_states_without_interpreting_prose(opened): - record = opened.publish_question("ask-3.md", ("answered", "pending"), body="2026-10-22 답변 완료") - opened.ok("document", "share", "ask-3.md") - assert mission_state.unanswered_questions(str(opened.folder), {}) == ["ask-3.md"] - mission_state.question_records.answer_document(opened.folder, "ask-3.md", { - "schema": 1, "id": "reply-1", "revision": record["revision"], "at": "2026-10-26", "text": "2번 권장", - "updates": [{"id": "2", "status": "answered", "answer": "권장"}], - }) - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - opened.ok("document", "share", "ask-3.md") - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - - -@pytest.mark.parametrize( - "name,state,answer,fields,pending,statuses,count_known", - [ - ("ask-1.md", "질문 1 답변 · 질문 2 대기", "2026-10-22 1번 보류", {}, True, ["answered", "pending"], True), - ("ask-1.md", "답변 대기", "2026-10-22 1번 보류", {}, False, ["unknown", "unknown"], False), - ("ask-1.md", "답변 대기", "", {}, True, ["pending", "pending"], True), - ("ask-1.md", "답변 접수", "2026-10-22 답변 접수", {}, True, ["unknown", "unknown"], False), - ("ask-1.md", "답변 대기 · 부분 답변", "2026-10-22 일부만 답변", {}, True, ["unknown", "unknown"], False), - ("ask-1.md", "질문 1 답변", "2026-10-22 일부만 답변", {}, True, ["answered", "unknown"], False), - ("confirm-A3.md", "질문 1 답변 접수 · 질문 2 답변 전달", "2026-10-22 답변 접수", {}, True, ["unknown", "unknown"], False), - ("confirm-A3.md", "질문 1 답변 · 질문 2 답변 완료", "", {"확인 A3": "대기"}, False, ["answered", "answered"], True), - ("confirm-A3.md", "답변 완료", "", {"확인 A3": "대기"}, False, ["answered", "answered"], True), - ("confirm-A3.md", "답변 완료 · 승인 대기", "", {"확인 A3": "대기"}, True, ["answered", "answered"], True), - ("confirm-A3.md", "답변 완료 · 전체 승인 확인 대기", "", {"확인 A3": "대기"}, True, ["answered", "answered"], True), - ("confirm-A3.md", "답변 완료 · 승인 대기", "", {"확인 A3": "승인"}, False, ["answered", "answered"], True), - ("confirm-A3.md", "답변 대기", "", {"확인 A3": "승인"}, False, ["answered", "answered"], True), - ], -) -def test_summarize_question_document_uses_only_supplied_snapshot(name, state, answer, fields, pending, statuses, count_known, monkeypatch): - text = f"# 제출할 CL\n\n{state}\n\n## 결정할 것\n\n### 1. 제출할까요?\n\n### 2. 선행을 풀까요?\n\n## 답\n\n{answer}\n" - - def forbidden_read(*args, **kwargs): - raise AssertionError("문서 snapshot 판정은 파일을 읽을 수 없음") - - monkeypatch.setattr(mission_documents, "open", forbidden_read, raising=False) - result = mission_state.summarize_question_document(name, text, fields) - assert result.name == name and result.title == "제출할 CL" - assert result.pending == pending and result.count_known == count_known - assert result.total_known - assert [item.status for item in result.items] == statuses - - -def test_unanswered_confirm_uses_explicit_approval_independently_of_headers(opened): - record = opened.publish_question("confirm-A3.md", ("answered",), "pending") - opened.ok("document", "share", "confirm-A3.md") - assert mission_state.unanswered_questions(str(opened.folder), {}) == ["confirm-A3.md"] - assert mission_state.unanswered_questions(str(opened.folder), {"확인 A3": "승인"}) == ["confirm-A3.md"] - assert mission_state.unanswered_questions(str(opened.folder), {"확인 A": "생략"}) == ["confirm-A3.md"] - mission_state.question_records.answer_document(opened.folder, "confirm-A3.md", { - "schema": 1, "id": "reply-1", "revision": record["revision"], "at": "2026-10-26", "text": "전체 승인", - "updates": [], "approval": {"status": "complete", "reason": "사용자 승인"}, - }) - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - - -def test_legacy_question_is_a_record_issue_without_prose_fallback(opened): - (opened.folder / "ask-1.md").write_text("# 질문\n\n## 답\n\n2026-10-22 권장\n", encoding="utf-8") - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - assert opened.ok("status").endswith("걸린 것: ask-1.md 기록 확인 필요") - assert "기록 확인 필요" in opened.fail("document", "share", "ask-1.md") - - -@pytest.mark.parametrize("answer_heading", ["## 답", "### 답 (2026-10-23)", "## **답변** ###"]) -def test_historical_summary_uses_real_answer_after_similar_heading(opened, answer_heading): - text = ( - "# 작업 범위\n\n답변 대기\n\n## 결정할 것\n\n### 1. 다음 작업을 할까요?\n\n" - "## 답 없이 진행 중인 정리\n\n아직 결정 전\n\n" - f"{answer_heading}\n\n2026-10-23 사용자: 진행해주세요\n" - ) - result = mission_state.summarize_question_document("ask-1.md", text, {}) - assert not result.pending and result.total_known and not result.count_known - - -def test_similar_answer_heading_alone_cannot_clear_waiting(opened): - text = ( - "# 작업 범위\n\n답변 대기\n\n## 결정할 것\n\n### 1. 다음 작업을 할까요?\n\n" - "## 답 없이 진행 중인 정리\n\n2026-10-23 아직 결정 전\n" - ) - result = mission_state.summarize_question_document("ask-1.md", text, {}) - assert result.pending and result.total_known and result.count_known - assert result.pending_count == 1 - - -def test_unanswered_questions_reads_unshared_sources_and_reports_changed_documents(opened): - for name in ("ask-1.md", "ask-2.md"): - opened.publish_question(name) - opened.ok("document", "share", "ask-1.md") - (opened.folder / "ask-1.md").write_text("# 변경된 질문\n", encoding="utf-8") - assert mission_state.unanswered_questions(str(opened.folder), {}) == ["ask-2.md"] - assert opened.ok("status").endswith("걸린 것: ask-1.md 기록 확인 필요, ask-2.md 답 없음") - - -def test_unanswered_questions_parse_a_single_current_snapshot(opened, monkeypatch): - question = opened.folder / "ask-1.md" - opened.publish_question(statuses=("answered",)) - original = question.read_text(encoding="utf-8") - changed = original + "\n답변 대기\n" - opened.ok("document", "share", "ask-1.md") - original_open = open - - def swapping_open(path, mode="r", *args, **kwargs): - stream = original_open(path, mode, *args, **kwargs) - if Path(path) != question or mode != "rb": - return stream - with stream: - snapshot = stream.read() - question.write_text(changed, encoding="utf-8") - return BytesIO(snapshot) - - monkeypatch.setattr(mission_documents, "open", swapping_open, raising=False) - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - assert question.read_text(encoding="utf-8") == changed - - -def test_questions_remain_visible_after_edits_hiding_and_markdown_deletion(opened): - question = opened.folder / "ask-1.md" - opened.publish_question() - assert mission_state.shared_documents(str(opened.folder)) == set() - assert opened.ok("status").endswith("걸린 것: ask-1.md 답 없음") - assert opened.ok("document", "list") == "공유 중: 없음\n자동 표시: ask-1.md, details/history/ask-1.md" - assert opened.ok("document", "share", "ask-1.md") == "공유함: ask-1.md" - assert opened.ok("document", "list") == "공유 중: ask-1.md\n자동 표시: ask-1.md, details/history/ask-1.md" - question.write_text("# 질문 수정\n", encoding="utf-8") - assert mission_state.shared_documents(str(opened.folder)) == set() - assert opened.ok("status").endswith("걸린 것: ask-1.md 기록 확인 필요") - assert "기록 확인 필요" in opened.fail("document", "share", "ask-1.md") - opened.ok("question", "render", "ask-1.md") - opened.ok("document", "share", "ask-1.md") - assert opened.ok("document", "hide", "ask-1.md") == "숨김: 변경 없음\n자동 표시 유지: ask-1.md" - assert mission_state.shared_documents(str(opened.folder)) == set() - assert opened.ok("status").endswith("걸린 것: ask-1.md 답 없음") - question.unlink() - assert opened.ok("status").endswith("걸린 것: ask-1.md 기록 확인 필요") - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - opened.ok("question", "render", "ask-1.md") - assert opened.ok("status").endswith("걸린 것: ask-1.md 답 없음") - - -def test_document_share_validates_all_paths_before_writing_manifest(opened): - opened.publish_question() - before = opened.folder / mission_state.SHARED_DOCUMENTS_FILE - assert "파일을 읽을 수 없음" in opened.fail("document", "share", "ask-1.md", "missing.md") - assert not before.exists() - outside = opened.root.parent / "outside.md" - outside.write_text("outside", encoding="utf-8") - for name in ("../outside.md", str(outside), ".secret.md", "details/.secret.md", "mission.md", "units.tsv", "ledger.tsv", "decisions.tsv", "sessions.tsv", mission_state.SHARED_DOCUMENTS_FILE): - assert opened.fail("document", "share", name) - assert not before.exists() - nested = opened.folder / "details" / "ask-1.md" - nested.parent.mkdir(exist_ok=True) - nested.write_text("nested", encoding="utf-8") - assert opened.ok("document", "share", "ask-1.md", "details/ask-1.md") == "공유함: ask-1.md, details/ask-1.md" - assert mission_state.shared_documents(str(opened.folder)) == {"ask-1.md", "details/ask-1.md"} - - -def test_expected_document_hash_mismatch_preserves_manifest(opened): - question = opened.folder / "note.md" - previous_content = b"previous" - question.write_bytes(previous_content) - mission_state.share_documents(str(opened.folder), ["note.md"]) - manifest = opened.folder / mission_state.SHARED_DOCUMENTS_FILE - before = manifest.read_bytes() - current_content = b"current" - question.write_bytes(current_content) - with pytest.raises(mission_state.StateError, match="문서가 바뀌었습니다"): - mission_state.share_documents( - str(opened.folder), - ["note.md"], - expected_hashes={"note.md": hashlib.sha256(previous_content).hexdigest()}, - ) - assert manifest.read_bytes() == before - assert mission_state.shared_documents(str(opened.folder)) == set() - mission_state.share_documents( - str(opened.folder), - ["note.md"], - expected_hashes={"note.md": hashlib.sha256(current_content).hexdigest()}, - ) - assert mission_state.shared_documents(str(opened.folder)) == {"note.md"} - - -def test_document_manifest_corruption_fails_closed_and_missing_entries_are_stale(opened): - opened.publish_question() - manifest = opened.folder / mission_state.SHARED_DOCUMENTS_FILE - manifest.write_text("wrong\theader\n", encoding="utf-8") - listed = opened.ok("document", "list") - assert "헤더가 다름" in listed and "자동 표시: ask-1.md" in listed - assert opened.ok("status").endswith("걸린 것: ask-1.md 답 없음") - manifest.write_text("path\tsha256\tat\nmissing.md\t" + "0" * 64 + "\t2026-10-22T00:00:00+09:00\n", encoding="utf-8") - assert mission_state.shared_documents(str(opened.folder)) == set() - assert opened.ok("document", "list") == "공유 중: 없음\n자동 표시: ask-1.md, details/history/ask-1.md" - - -def test_auto_questions_include_only_root_documents_and_matching_details(opened): - files = ["ask-1.md", "confirm-B.md", "details/ask-1.md", "details/confirm-B.md", "details/history/ask-1.md", "details/history/confirm-B.md", "details/history/ask-orphan.md", "details/history/notes.md", "questions/history/ask-1/1.json", "details/ask-orphan.md", "nested/ask-private.md", "ask-folder/private.md", ".ask-hidden.md"] - for name in files: - path = opened.folder / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text("# 질문\n", encoding="utf-8") - expected = {"ask-1.md", "confirm-B.md", "details/ask-1.md", "details/confirm-B.md", "details/history/ask-1.md", "details/history/confirm-B.md"} - assert mission_state.auto_question_documents(str(opened.folder)) == expected - for name in files: - assert mission_state.auto_question_document(str(opened.folder), name) == (name in expected) - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - assert opened.ok("status").endswith("걸린 것: ask-1.md 기록 확인 필요, confirm-B.md 기록 확인 필요") - - -def test_hiding_question_details_uses_canonical_names_and_preserves_visibility(opened): - opened.publish_question() - details = opened.folder / "details" / "ask-1.md" - details.parent.mkdir(exist_ok=True) - details.write_text("# 근거\n", encoding="utf-8") - opened.ok("document", "share", "details/ask-1.md") - assert opened.ok("document", "hide", "details\\ask-1.md") == "숨김: 변경 없음\n자동 표시 유지: details/ask-1.md" - assert mission_state.shared_documents(str(opened.folder)) == set() - assert mission_state.auto_question_documents(str(opened.folder)) == {"ask-1.md", "details/ask-1.md", "details/history/ask-1.md"} - - -def test_auto_questions_reject_private_symlink_aliases_and_escapes(opened): - private = opened.folder / "private.md" - private.write_text("private", encoding="utf-8") - hidden = opened.folder / ".private.md" - hidden.write_text("hidden", encoding="utf-8") - outside = opened.root.parent / "outside.md" - outside.write_text("outside", encoding="utf-8") - try: - for number, target in enumerate((private, hidden, outside), start=1): - (opened.folder / f"ask-{number}.md").symlink_to(target) - except OSError: - pytest.skip("symbolic links are unavailable") - assert mission_state.auto_question_documents(str(opened.folder)) == set() - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - - -def test_document_share_rejects_symlink_escape(opened): - outside = opened.root.parent / "outside.md" - outside.write_text("outside", encoding="utf-8") - hidden_dir = opened.folder / ".dashboard-answers" - hidden_dir.mkdir() - hidden_file = hidden_dir / "secret.json" - hidden_file.write_text("secret", encoding="utf-8") - hidden_alias = opened.folder / "hidden-alias.md" - system_alias = opened.folder / "system-alias.md" - link = opened.folder / "linked.md" - try: - hidden_alias.symlink_to(hidden_file) - system_alias.symlink_to(opened.folder / "mission.md") - link.symlink_to(outside) - except OSError: - pytest.skip("symbolic links are unavailable") - assert "숨김 경로" in opened.fail("document", "share", "hidden-alias.md") - assert "시스템 파일" in opened.fail("document", "share", "system-alias.md") - assert "밖" in opened.fail("document", "share", "linked.md") - manifest = opened.folder / mission_state.SHARED_DOCUMENTS_FILE - assert not manifest.exists() - manifest.symlink_to(outside) - assert "경로가 잘못됨" in opened.fail("document", "list") - - -@pytest.fixture -def home(tmp_path, monkeypatch): - folder = tmp_path / "home" - folder.mkdir() - monkeypatch.setenv("HOME", str(folder)) - monkeypatch.setenv("USERPROFILE", str(folder)) - return folder - - -def write_sessions(mission, *rows): - lines = ["at\taction\tsession\ttranscript"] + [f"2026-10-19T09:00:00+09:00\t{a}\t{s}\t{t}" for a, s, t in rows] - (mission.folder / "sessions.tsv").write_text("\n".join(lines) + "\n", encoding="utf-8") - - -def test_transcripts_prefers_recorded_path_then_searches_by_session(opened, home): - recorded = home / "elsewhere.jsonl" - recorded.write_text("{}", encoding="utf-8") - claude = home / ".claude" / "projects" / "D--proj" - (claude / "aaaa-1111" / "subagents").mkdir(parents=True) - (claude / "aaaa-1111.jsonl").write_text("{}", encoding="utf-8") - (claude / "aaaa-1111" / "subagents" / "agent-1.jsonl").write_text("{}", encoding="utf-8") - write_sessions(opened, ("open", "s-rec", str(recorded)), ("open", "aaaa-1111", ""), ("resume", "aaaa-1111", "")) - lines = opened.ok("transcripts").splitlines() - assert lines[0] == f"s-rec {recorded}" - assert lines[1] == f"aaaa-1111 {claude / 'aaaa-1111.jsonl'}" - assert lines[2] == f" {claude / 'aaaa-1111' / 'subagents' / 'agent-1.jsonl'}" - assert len(lines) == 3 - - -def test_transcripts_finds_codex_rollout_by_exact_session_suffix(opened, home): - day = home / ".codex" / "sessions" / "2026" / "10" / "19" - day.mkdir(parents=True) - wanted = day / "rollout-2026-10-19T09-00-00-0199-aaaa.jsonl" - wanted.write_text("{}", encoding="utf-8") - (day / "rollout-2026-10-19T09-00-00-0199-aaaa-extra.jsonl").write_text("{}", encoding="utf-8") - write_sessions(opened, ("open", "0199-aaaa", "")) - assert opened.ok("transcripts") == f"0199-aaaa {wanted}" - - -def test_transcripts_reports_missing_and_never_globs_odd_ids(opened, home): - (home / ".claude" / "projects" / "p").mkdir(parents=True) - (home / ".claude" / "projects" / "p" / "secret.jsonl").write_text("{}", encoding="utf-8") - write_sessions(opened, ("open", "gone-1", "C:/nope.jsonl"), ("open", "*", ""), ("open", "../p/secret", "")) - assert opened.ok("transcripts").splitlines() == ["없음: gone-1", "없음: *", "없음: ../p/secret"] - - -def test_transcripts_without_sessions_file(opened): - assert opened.ok("transcripts").startswith("세션 기록 없음") - - -def test_transcripts_finds_grok_session_and_ignores_claude_subagent_layout(opened, home, monkeypatch): - base = home / "custom-grok" - monkeypatch.setenv("GROK_HOME", str(base)) - folder = base / "sessions/encoded/sample-session" - folder.mkdir(parents=True) - transcript = folder / "updates.jsonl" - transcript.write_text(json.dumps({"timestamp": 1800000000, "params": {"sessionId": "sample-session", - "update": {"sessionUpdate": "turn_completed"}}}) + "\n", encoding="utf-8") - fake_subagents = folder / "updates/subagents" - fake_subagents.mkdir(parents=True) - (fake_subagents / "agent.jsonl").write_text("{}", encoding="utf-8") - write_sessions(opened, ("open", "sample-session", "stale-path.jsonl")) - assert opened.ok("transcripts") == f"sample-session {transcript}" - - -def test_transcripts_prefers_grok_store_for_grok_runtime(opened, home, monkeypatch): - monkeypatch.setenv("GROK_HOME", str(home / ".grok")) - grok = home / ".grok/sessions/encoded/sample-session/updates.jsonl" - grok.parent.mkdir(parents=True) - grok.write_text(json.dumps({"params": {"sessionId": "sample-session", "update": {"sessionUpdate": "turn_completed"}}}), encoding="utf-8") - claude = home / ".claude/projects/encoded/sample-session.jsonl" - claude.parent.mkdir(parents=True) - claude.write_text("{}", encoding="utf-8") - write_sessions(opened, ("open", "sample-session", "")) - ctx = mission_state.Context(ADAPTER, str(opened.root / "state"), "m1", "grok", str(opened.root)) - assert mission_state.cmd_transcripts(ctx, object()) == [f"sample-session {grok}"] - - -def test_cli_error_is_one_stderr_line_with_exit_code_1(tmp_path): - result = subprocess.run( - [sys.executable, "-B", str(SCRIPT), "--project", str(tmp_path), "status"], - capture_output=True, - cwd=tmp_path, - timeout=20, - env={**os.environ, "HAN_ADAPTERS_DIR": str(tmp_path / "none")}, - ) - assert result.returncode == 1 - assert result.stdout == b"" - assert result.stderr.decode("utf-8").count("\n") == 1 - - -def test_question_preview_show_and_check_are_readonly(opened, monkeypatch): - record = opened.question_record() - draft = opened.json_input("draft.json", record) - before = {str(path.relative_to(opened.folder)): path.read_bytes() for path in opened.folder.rglob("*") if path.is_file()} - - def forbidden_lock(*args, **kwargs): - raise AssertionError("읽기 전용 명령은 미션 잠금을 만들 수 없음") - - monkeypatch.setattr(mission_state.infrastructure_locking, "FileLock", forbidden_lock) - assert opened.ok("question", "preview", "--input", draft) == mission_state.question_records.render_document(record).rstrip("\n") - assert opened.ok("question", "check") == "질문 기록 정상: 0개" - after = {str(path.relative_to(opened.folder)): path.read_bytes() for path in opened.folder.rglob("*") if path.is_file()} - assert after == before - opened.publish_question() - assert json.loads(opened.ok("question", "show", "ask-1.md")) == record - assert opened.ok("question", "check") == "질문 기록 정상: 1개" - - -@pytest.mark.parametrize("editorial", [False, True]) -def test_question_patch_is_standalone_and_never_loads_or_writes_mission_state(opened, monkeypatch, editorial): - record = opened.question_record(statuses=("answered",)) - draft = opened.json_input("draft-patch.json", record) - change_input = {"set": {"title": "Fictional wording", "revision": 2}} - expected = {**record, "title": "Fictional wording", "revision": 2} - if editorial: - definition = {key: value for key, value in record["items"][0].items() if key not in ("status", "answer")} - definition["body"] = "Reworded fictional choice." - change_input["upsert_items"] = [definition] - expected["items"] = [{**record["items"][0], "body": definition["body"]}] - changes = opened.json_input("changes-patch.json", change_input) - before = {str(path): path.read_bytes() for path in opened.root.rglob("*") if path.is_file()} - - def forbidden(*args, **kwargs): - raise AssertionError("pure patch must not access mission infrastructure") - - monkeypatch.setattr(mission_state.infrastructure_configuration, "locate", forbidden) - monkeypatch.setattr(mission_state.infrastructure_locking, "FileLock", forbidden) - monkeypatch.setattr(mission_state.mission_guard, "read_active", forbidden) - options = ["--editorial"] if editorial else [] - result = json.loads(opened.ok("question", "patch", "--input", draft, "--changes", changes, *options)) - assert result == expected - assert before == {str(path): path.read_bytes() for path in opened.root.rglob("*") if path.is_file()} - - -def test_question_preflight_flags_only_pending_workload_and_keeps_existing_contract(opened): - record = opened.question_record() - item = record["items"][0] - record["items"] = [{**item, "id": str(index), "title": f"Choice {index}"} for index in range(1, 7)] - record["items"][-1].update(status="withdrawn", answer="Deferred.") - draft = opened.json_input("decision-review.json", record) - assert "답변 부담 확인" not in opened.ok("question", "preflight", "--input", draft) - record["items"][-1].update(status="pending", answer="") - draft = opened.json_input("decision-review.json", record) - report = opened.ok("question", "preflight", "--input", draft) - assert "검사 통과" in report and "미답 6문항" in report - assert "미답 6문항" in opened.ok("question", "publish", "--input", draft) - - -def test_question_preflight_matches_publish_checks_without_lock_or_side_effects(opened, monkeypatch): - saved = opened.publish_question(statuses=("answered",)) - revised = {**saved, "revision": 2, "body": "Reworded fictional contract."} - draft = opened.json_input("preflight.json", revised) - before = {str(path): (path.read_bytes(), path.stat().st_mtime_ns) for path in opened.root.rglob("*") if path.is_file()} - - def forbidden(*args, **kwargs): - raise AssertionError("read-only preflight must not create a lock") - - monkeypatch.setattr(mission_state.infrastructure_locking, "FileLock", forbidden) - assert "approval" in opened.fail("question", "preflight", "--input", draft, "--expect-revision", "1") - assert "검사 통과" in opened.ok("question", "preflight", "--input", draft, "--expect-revision", "1", "--editorial") - assert before == {str(path): (path.read_bytes(), path.stat().st_mtime_ns) for path in opened.root.rglob("*") if path.is_file()} - - -def test_question_cli_publish_answer_and_render_preserve_verbatim_answer_and_headers(opened, monkeypatch): - record = opened.question_record("confirm-A.md", approval="pending") - record.update(schema=2, blocks=[{'id': 'scope', 'type': 'list', 'title': 'Scope', - 'items': [{'id': 'books', 'label': 'Books', 'text': 'Saved books.'}]}]) - draft = opened.json_input("draft.json", record) - header = (opened.folder / "mission.md").read_bytes() - locks = [] - original_lock = mission_state.infrastructure_locking.FileLock - - def tracked_lock(path, *args, **kwargs): - locks.append(Path(path).name) - return original_lock(path, *args, **kwargs) - - monkeypatch.setattr(mission_state.infrastructure_locking, "FileLock", tracked_lock) - assert "revision 1" in opened.ok("question", "publish", "--input", draft) - answer = {"schema": 1, "id": "reply-1", "revision": 1, "at": "2026-10-26", "text": "권장\n원문 유지", - "updates": [{"id": "1", "status": "answered", "answer": "권장"}], - "approval": {"status": "complete", "reason": "사용자 승인"}} - reply = opened.json_input("reply.json", answer) - assert "답변 저장" in opened.ok("question", "answer", "confirm-A.md", "--input", reply) - saved = mission_state.question_records.read_document(opened.folder, "confirm-A.md") - assert saved["answers"] == [answer] - assert saved["items"][0]["status"] == "answered" and saved["items"][0]["answer"] == "권장" - assert (opened.folder / "mission.md").read_bytes() == header - assert opened.ok("status").endswith("걸린 것: 없음") - markdown = opened.folder / "confirm-A.md" - expected = markdown.read_bytes() - markdown.write_text("# 외부 편집\n", encoding="utf-8") - assert "질문 문서 생성" in opened.ok("question", "render", "confirm-A.md") - assert markdown.read_bytes() == expected - assert locks == ["m1.lock", "m1.lock", "m1.lock"] - assert json.loads(opened.ok("question", "show", "confirm-A.md")) == saved - - -def test_question_cli_check_reports_missing_invalid_and_changed_records_with_actions(opened): - (opened.folder / "ask-legacy.md").write_text("# 예전 질문\n", encoding="utf-8") - opened.publish_question("ask-missing.md", ("answered",)) - (opened.folder / "ask-missing.md").unlink() - opened.publish_question("ask-corrupt.md") - (opened.folder / "questions" / "ask-corrupt.json").write_text("{broken", encoding="utf-8") - opened.publish_question("ask-edited.md") - (opened.folder / "ask-edited.md").write_text("# 직접 편집\n", encoding="utf-8") - code, out, err = opened.run("question", "check") - assert code == 1 and not err - for name in ("ask-legacy", "ask-missing", "ask-corrupt", "ask-edited"): - line = next(line for line in out.splitlines() if line.startswith(f"{name}.md 기록 확인 필요")) - assert str(opened.folder / "questions" / f"{name}.json") in line - assert "question publish --input " in line and f"question render {name}.md" in line - assert mission_state.unanswered_questions(str(opened.folder), {}) == [] - status = opened.ok("context") - assert "기록 확인 필요" in status and "답 없음" not in status - - -def test_question_cli_restore_uses_mission_lock_and_preserves_headers(opened, monkeypatch): - record = opened.publish_question("ask-library.md", title="Library filters") - source = opened.folder / "questions" / "ask-library.json" - digest = hashlib.sha256(source.read_bytes()).hexdigest() - markdown = opened.folder / "ask-library.md" - markdown.write_bytes(b"# Library filters\r\n\r\nKeep the author filter.\r\n") - original = opened.root / "saved-original.md" - original.write_bytes(markdown.read_bytes()) - record["items"][0].update(status="answered", answer="Author filter retained.") - record["answers"].append({"schema": 1, "id": "library-choice", "revision": 1, "at": "2041-02-03", - "text": "Keep the author filter.", - "updates": [{"id": "1", "status": "answered", "answer": "Author filter retained."}]}) - draft = opened.json_input("reviewed-library.json", record) - headers = {name: (opened.folder / name).read_bytes() for name in ("mission.md",)} - active = (opened.root / "state" / "ACTIVE").read_bytes() - locks = [] - original_lock = mission_state.infrastructure_locking.FileLock - - def tracked_lock(path, *args, **kwargs): - locks.append(Path(path).name) - return original_lock(path, *args, **kwargs) - - monkeypatch.setattr(mission_state.infrastructure_locking, "FileLock", tracked_lock) - command = ("question", "restore", "--input", draft, "--source", str(original), - "--expect-revision", "1", "--expect-sha256", digest) - assert "질문 기록 복구" in opened.ok(*command) - assert locks == ["m1.lock"] - assert opened.ok("question", "check") == "질문 기록 정상: 1개" - assert mission_state.question_records.read_document(opened.folder, "ask-library.md") == record - assert (opened.root / "state" / "ACTIVE").read_bytes() == active - assert all((opened.folder / name).read_bytes() == content for name, content in headers.items()) - saved = source.read_bytes(), markdown.read_bytes() - assert "expected_sha256" in opened.fail(*command) - assert (source.read_bytes(), markdown.read_bytes()) == saved - - -def test_question_cli_revision_and_duplicate_reply_conflicts_preserve_files(opened): - record = opened.publish_question() - record["revision"] = 2 - record["title"] = "개정 질문" - draft = opened.json_input("draft.json", record) - before = {str(path): path.read_bytes() for path in opened.folder.rglob("*") if path.is_file()} - assert opened.fail("question", "publish", "--input", draft) - assert {str(path): path.read_bytes() for path in opened.folder.rglob("*") if path.is_file()} == before - assert "revision 2" in opened.ok("question", "publish", "--input", draft, "--expect-revision", "1") - answer = {"schema": 1, "id": "reply-1", "revision": 2, "at": "2026-10-26", "text": "권장", - "updates": [{"id": "1", "status": "answered", "answer": "권장"}]} - reply = opened.json_input("reply.json", answer) - opened.ok("question", "answer", "ask-1.md", "--input", reply) - saved = (opened.folder / "questions" / "ask-1.json").read_bytes() - (opened.folder / "ask-1.md").write_text("# 손상\n", encoding="utf-8") - opened.ok("question", "answer", "ask-1.md", "--input", reply) - assert (opened.folder / "questions" / "ask-1.json").read_bytes() == saved - answer["text"] = "다른 답" - opened.json_input("reply.json", answer) - markdown = (opened.folder / "ask-1.md").read_bytes() - assert opened.fail("question", "answer", "ask-1.md", "--input", reply) - assert (opened.folder / "questions" / "ask-1.json").read_bytes() == saved - assert (opened.folder / "ask-1.md").read_bytes() == markdown - - -@pytest.mark.parametrize("value", [[], {"schema": 1}, {"schema": 99}]) -def test_question_cli_rejects_invalid_input_before_creating_records(opened, value): - draft = opened.json_input("draft.json", value) - assert opened.fail("question", "publish", "--input", draft) - assert not (opened.folder / "questions").exists() - assert not list(opened.folder.glob("ask-*.md")) - - -def test_question_cli_reports_json_input_and_parser_errors(opened): - invalid = opened.root / "invalid.json" - invalid.write_text("{broken", encoding="utf-8") - assert "JSON 읽기 실패" in opened.fail("question", "publish", "--input", str(invalid)) - assert "JSON 읽기 실패" in opened.fail("question", "answer", "ask-1.md", "--input", str(opened.root / "missing.json")) - assert "--input" in opened.fail("question", "publish") - assert "--expect-revision" in opened.fail("question", "publish", "--input", str(invalid), "--expect-revision", "wrong") - assert "형식 오류" in opened.fail("question", "show", "../ask-1.md") - - -def test_question_share_validates_all_records_before_changing_existing_manifest(opened): - opened.publish_question("ask-1.md") - opened.publish_question("ask-2.md") - opened.ok("document", "share", "ask-1.md") - manifest = opened.folder / mission_state.SHARED_DOCUMENTS_FILE - before = manifest.read_bytes() - (opened.folder / "ask-2.md").write_text("# 직접 편집\n", encoding="utf-8") - assert "기록 확인 필요" in opened.fail("document", "share", "ask-1.md", "ask-2.md") - assert manifest.read_bytes() == before - - -def test_question_store_shape_issue_remains_visible_in_status_and_check(opened): - (opened.folder / "questions").write_text("잘못된 저장소", encoding="utf-8") - assert opened.ok("status").endswith("걸린 것: questions 기록 확인 필요") - code, out, err = opened.run("question", "check") - assert code == 1 and not err - assert str(opened.folder / "questions") in out and "폴더와 JSON 파일 이름을 확인" in out - - -def test_question_cli_editorial_requires_explicit_flag_and_preserves_answer_state(opened): - record = opened.publish_question(statuses=("answered",)) - record["revision"] = 2 - record["title"] = "표현을 다듬은 질문" - record["items"][0]["title"] = "선택 표현 정리" - record["intro"] = "문체 수정" - draft = opened.json_input("draft.json", record) - source = opened.folder / "questions" / "ask-1.json" - before = source.read_bytes() - assert opened.fail("question", "publish", "--input", draft, "--expect-revision", "1") - assert source.read_bytes() == before - assert "revision 2" in opened.ok("question", "publish", "--input", draft, "--expect-revision", "1", "--editorial") - saved = mission_state.question_records.read_document(opened.folder, "ask-1.md") - assert saved == record and saved["items"][0]["answer"] == "진행" - assert opened.ok("status").endswith("걸린 것: 없음") - record["revision"] = 3 - record["items"][0].update(status="pending", answer="") - opened.json_input("draft.json", record) - before = source.read_bytes() - assert opened.fail("question", "publish", "--input", draft, "--expect-revision", "2", "--editorial") - assert source.read_bytes() == before - - -def test_runtime_grok_reads_grok_adapter(tmp_path, capsys, monkeypatch): - for name in ("HAN_ADAPTERS_DIR", "HAN_REPO", "CLAUDE_PROJECT_DIR", "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR"): - monkeypatch.delenv(name, raising=False) - root = tmp_path / "game" - (root / ".grok" / "orchestrator").mkdir(parents=True) - (root / ".grok" / "orchestrator" / "adapter.json").write_text(json.dumps(ADAPTER), encoding="utf-8") - (root / "state").mkdir() - code = mission_state.main(["--runtime", "grok", "--project", str(root), "active"]) - captured = capsys.readouterr() - assert code == 0, captured.err - assert "ACTIVE 없음" in captured.out - - -def project_contents(root): - return {str(path.relative_to(root)): path.read_bytes() for path in root.rglob("*") if path.is_file()} - - -def test_schema_uses_adapter_enums_without_active(mission): - (mission.root / "state" / "ACTIVE").unlink() - before = project_contents(mission.root) - schema = json.loads(mission.ok("schema")) - assert schema["stages"] == ["content", "poc", "impl", "review"] - assert schema["grades"] == ["editmode-pass", "pytest-pass"] - assert schema["unitStatuses"] == list(mission_state.UNIT_STATUSES) - assert schema["questionApprovalStatuses"] == ["none", "pending", "complete"] - assert project_contents(mission.root) == before - - -def test_reference_cli_without_active_records_pointers_and_reports_drift(mission): - (mission.root / "state" / "ACTIVE").unlink() - source = mission.root / "guidance.md" - source.write_text("Use the selected format\n") - result = json.loads(mission.ok("reference", "snapshot", "--source", "guidance.md", "--output", "runtime/ref.json", - "--revision", "r3", "--section", "Style")) - assert result["sources"][0]["revision"] == "r3" - before = project_contents(mission.root) - assert json.loads(mission.ok("reference", "show", "--input", "runtime/ref.json"))["schema"] == 1 - assert json.loads(mission.ok("reference", "check", "--input", "runtime/ref.json"))["status"] == "pass" - assert project_contents(mission.root) == before - source.write_text("Changed format\n") - code, out, err = mission.run("reference", "check", "--input", "runtime/ref.json") - assert code == 1 and not err and json.loads(out)["changed"] == ["guidance.md"] - source.unlink() - code, out, err = mission.run("reference", "check", "--input", "runtime/ref.json") - assert code == 1 and not err and json.loads(out)["missing"] == ["guidance.md"] - - -def test_brief_returns_fixed_fields_and_approval_sources_without_writing(opened): - opened.add_unit() - opened.publish_question("confirm-A.md", statuses=("answered",), approval="complete") - guide = opened.root / "guidance.md" - guide.write_text("Read the current contract\n") - opened.ok("reference", "snapshot", "--source", "guidance.md", "--output", "runtime/ref.json") - before = project_contents(opened.root) - brief = json.loads(opened.ok("brief", "M1", "--references", "runtime/ref.json")) - assert brief["unit"] == "M1" and brief["goal"] == "목표" - assert all(field in brief for field in mission_state.EDITABLE_FIELDS) - assert str(opened.folder / "questions" / "confirm-A.json") in brief["approvalSources"] - assert brief["references"][0]["path"] == "guidance.md" - assert project_contents(opened.root) == before - guide.write_text("Changed contract\n") - assert "변경/누락" in opened.fail("brief", "M1", "--references", "runtime/ref.json") - - -def test_handoff_preserves_detail_evidence_and_state(opened): - opened.add_unit() - detail = opened.root / "detail.md" - evidence = opened.root / "evidence.json" - detail.write_text("Full original detail\nLine two\n") - evidence.write_text('{"checks": 4}\n') - before = project_contents(opened.root) - result = json.loads(opened.ok("handoff", "M1", "--summary", "Implemented and checked", "--detail", "detail.md", - "--evidence", "evidence.json")) - assert result["summary"] == "Implemented and checked" - assert result["detail"]["sha256"] == hashlib.sha256(detail.read_bytes()).hexdigest() - assert result["evidence"][0]["path"] == "evidence.json" - assert project_contents(opened.root) == before - assert "상세를 --detail" in opened.fail("handoff", "M1", "--summary", "long", "--detail", "detail.md", "--max-summary-chars", "3") - assert json.loads(opened.ok("handoff", "M1", "--summary", "long", "--detail", "detail.md", "--max-summary-chars", "4"))["summary"] == "long" - assert "한 줄" in opened.fail("handoff", "M1", "--summary", "bad\nsummary", "--detail", "detail.md") - assert "파일 없음" in opened.fail("handoff", "M1", "--summary", "ready", "--detail", "missing.md") - assert "path 형식" in opened.fail("handoff", "M1", "--summary", "ready", "--detail", "../detail.md") - assert "파일 없음" in opened.fail("handoff", "M1", "--summary", "ready", "--detail", "detail.md", "--evidence", "missing.json") - assert project_contents(opened.root) == before - - -def verification_input(mission, **changes): - (mission.root / "input.txt").write_text("Fixed input\n") - plan = {"grade": "pytest-pass", "commands": [{"argv": [sys.executable, "-c", "print('checked')"]}], - "inputs": ["input.txt"], "environment": {"target": "fixture"}} - plan.update(changes) - return mission.json_input("plan.json", plan) - - -@pytest.mark.parametrize("status", ["pass", "fail"]) -def test_preflight_passes_settings_and_guard_without_state_or_receipts(opened, monkeypatch, status): - opened.add_unit() - plan_path = verification_input(opened) - seen = [] - def preflight(project, plan, guard, settings=None, require_matches=False): - assert require_matches is True - seen.append((project, plan, settings)) - guard("python -V") - return {"status": status, "grade": plan["grade"], "commandCount": 1, "readinessCount": 0, "resources": []} - monkeypatch.setattr(mission_state.verification, "preflight", preflight) - before = project_contents(opened.root) - code, out, err = opened.run("preflight", "M1", "--plan", plan_path) - expected_code = 1 - if status == "pass": - expected_code = 0 - assert code == expected_code and not err - assert json.loads(out)["status"] == status - assert seen[0][2] == ADAPTER["verify"] - assert seen[0][1]["unitBrief"]["goal"] == "목표" - assert project_contents(opened.root) == before - - -def test_reference_bundle_drift_prevents_preflight_and_verify_execution(opened, monkeypatch): - opened.add_unit() - guide = opened.root / "guidance.md" - guide.write_text("Current reference\n") - opened.ok("reference", "snapshot", "--source", "guidance.md", "--output", "runtime/ref.json") - plan_path = verification_input(opened, referenceBundle="runtime/ref.json") - def unexpected(*args, **kwargs): - pytest.fail("changed reference reached verification execution") - monkeypatch.setattr(mission_state.verification, "preflight", unexpected) - monkeypatch.setattr(mission_state.verification, "run", unexpected) - guide.write_text("Changed reference\n") - before = project_contents(opened.root) - assert "변경/누락" in opened.fail("preflight", "M1", "--plan", plan_path) - assert project_contents(opened.root) == before - assert "변경/누락" in opened.fail("verify", "M1", "--plan", plan_path) - - -def test_verify_passes_adapter_settings(opened, monkeypatch): - opened.add_unit() - plan_path = verification_input(opened) - settings_seen = [] - def run(project, folder, unit, plan, guard, force, settings=None, *, unit_lock_held=False): - assert unit_lock_held is True - settings_seen.append(settings) - guard("python -V") - return "receipt.json", {"status": "pass", "grade": "pytest-pass", "log": "output.log", "error": ""}, False - monkeypatch.setattr(mission_state.verification, "run", run) - assert "검증 pass" in opened.ok("verify", "M1", "--plan", plan_path) - assert settings_seen == [ADAPTER["verify"]] - - -def test_preflight_actual_runner_does_not_launch_commands_or_write_receipts(opened): - opened.add_unit() - command = {"argv": [sys.executable, "-c", "from pathlib import Path; Path('launched.txt').write_text('ran')"]} - plan_path = verification_input(opened, commands=[command]) - before = project_contents(opened.root) - result = json.loads(opened.ok("preflight", "M1", "--plan", plan_path)) - assert result["status"] == "pass" and result["commandCount"] == 1 - assert project_contents(opened.root) == before - - -def test_reference_cli_refresh_uses_snapshot_output_hash(opened): - (opened.root / "guidance.md").write_text("Current guidance\n") - initial = json.loads(opened.ok("reference", "snapshot", "--source", "guidance.md", "--output", "runtime/ref.json")) - assert initial["output"]["path"] == "runtime/ref.json" - before = (opened.root / "runtime/ref.json").read_bytes() - assert "expect-sha256" in opened.fail("reference", "snapshot", "--source", "guidance.md", "--output", "runtime/ref.json") - assert (opened.root / "runtime/ref.json").read_bytes() == before - updated = json.loads(opened.ok("reference", "snapshot", "--source", "guidance.md", "--output", "runtime/ref.json", - "--expect-sha256", initial["output"]["sha256"], "--revision", "r2")) - assert updated["output"]["sha256"] != initial["output"]["sha256"] - assert updated["sources"][0]["revision"] == "r2" - - -def completion_with_policy(mission): - mission.add_unit() - mission.ok("unit", "set", "M1", "--status", "doing") - (mission.root / "machine-state").write_text("ready", encoding="utf-8") - (mission.root / "readiness.py").write_text( - "from pathlib import Path\nPath('observations').open('a').write('x')\n" - "raise SystemExit(int(Path('machine-state').read_text() != 'ready'))\n", encoding="utf-8", - ) - adapter_path = mission.root / ".claude/orchestrator/adapter.json" - adapter = json.loads(adapter_path.read_text(encoding="utf-8")) - adapter["verify"].update( - resourceDir=str(mission.root / "resources"), resources={"pytest-pass": ["engine"]}, - readiness={"pytest-pass": [{"argv": [sys.executable, "readiness.py"]}]}, - ) - adapter_path.write_text(json.dumps(adapter), encoding="utf-8") - plan = verification_input(mission, commands=[{"argv": [sys.executable, "-c", - "from pathlib import Path; Path('validation-runs').open('a').write('x')"], "reusable": True, "outputs": []}]) - mission.ok("verify", "M1", "--plan", plan) - receipt = json.loads((mission.folder / "verification/M1.latest.json").read_text(encoding="utf-8"))["receipt"] - report = mission.root / "review.md" - report.write_text("Fictional independent review", encoding="utf-8") - review_args = ["review", "M1", "--receipt", receipt, "--evidence", str(report), "--reviewer", "independent", - "--kind", "unit", "--status", "clean"] - mission.ok(*review_args) - review = json.loads((mission.folder / "verification/M1.review.latest.json").read_text(encoding="utf-8"))["review"] - return adapter_path, adapter, plan, receipt, review, review_args - - -@pytest.mark.parametrize("change", ["resources", "resourceDir", "readiness-command", "readiness-script", "remove"]) -def test_changed_policy_and_readiness_tools_block_review_complete_and_reuse(opened, change): - adapter_path, adapter, plan, receipt, review, review_args = completion_with_policy(opened) - if change == "resources": - adapter["verify"]["resources"]["pytest-pass"] = ["other-engine"] - elif change == "resourceDir": - adapter["verify"]["resourceDir"] = str(opened.root / "other-resources") - elif change == "readiness-command": - adapter["verify"]["readiness"]["pytest-pass"][0]["argv"].append("extra") - elif change == "readiness-script": - (opened.root / "readiness.py").write_text("raise SystemExit(0)\n", encoding="utf-8") - else: - adapter["verify"] = {"grades": ["pytest-pass", "editmode-pass"]} - adapter_path.write_text(json.dumps(adapter), encoding="utf-8") - units_before = (opened.folder / "units.tsv").read_bytes() - ledger_before = (opened.folder / "ledger.tsv").read_bytes() - assert "검증" in opened.fail(*review_args) - assert "검증" in opened.fail("complete", "M1", "--receipt", receipt, "--review", review, "--done-evidence", "verified") - assert (opened.folder / "units.tsv").read_bytes() == units_before - assert (opened.folder / "ledger.tsv").read_bytes() == ledger_before - assert "input.txt" in opened.ok("review-scope", "M1", "--plan", plan) - opened.ok("verify", "M1", "--plan", plan) - latest_path = json.loads((opened.folder / "verification/M1.latest.json").read_text(encoding="utf-8"))["receipt"] - latest = json.loads(Path(latest_path).read_text(encoding="utf-8")) - assert latest_path != receipt and latest["executionCounts"] == {"executed": 1, "reused": 0} - assert (opened.root / "validation-runs").read_text(encoding="utf-8") == "xx" - - -def test_cleanup_observation_changes_allow_review_and_completion_without_readiness(opened, monkeypatch): - _, _, _, receipt, _, review_args = completion_with_policy(opened) - (opened.root / "machine-state").write_text("closed", encoding="utf-8") - def unexpected(*args, **kwargs): - pytest.fail("review or complete reran a readiness observation") - monkeypatch.setattr(mission_state.verification, "execute_command", unexpected) - opened.ok(*review_args) - review = json.loads((opened.folder / "verification/M1.review.latest.json").read_text(encoding="utf-8"))["review"] - assert "완료" in opened.ok("complete", "M1", "--receipt", receipt, "--review", review, "--done-evidence", "verified") - assert (opened.root / "observations").read_text(encoding="utf-8") == "x" diff --git a/tests/integration/mission/test_observatory.py b/tests/integration/mission/test_observatory.py deleted file mode 100644 index 8db64cc..0000000 --- a/tests/integration/mission/test_observatory.py +++ /dev/null @@ -1,223 +0,0 @@ -import json -from pathlib import Path - -import pytest -from chef.mission import observatory as obs - -from tests.paths import PLUGIN_ROOT - - -def test_malformed_identity_and_nested_model_cannot_export_raw_content(tmp_path): - item = source(tmp_path, 'claude', [{'type': 'assistant', 'sessionId': {'raw': 'PRIVATE BODY'}, - 'agentId': [], 'requestId': [], 'timestamp': '2026-01-01T00:00:00Z', - 'message': {'id': {}, 'model': {'raw': 'PRIVATE BODY'}, - 'usage': {'iterations': 8, 'input_tokens': 2}}}]) - report = obs.collect_report([item]) - exported = obs.serialize_report(report) - assert 'PRIVATE BODY' not in exported - assert report['records'][0]['model'] == 'unknown' - assert report['diagnostics']['invalid_advisor_iterations'] == 1 - item = source(tmp_path, 'codex', [{'type': 'turn_context', 'payload': {'model': {'raw': 'PRIVATE BODY'}}}, - token_row({'input_tokens': 2})]) - assert 'PRIVATE BODY' not in obs.serialize_report(obs.collect_report([item])) - - -def test_invalid_utf8_source_is_diagnostic_not_raw_export(tmp_path): - path = tmp_path / 'broken.jsonl' - path.write_bytes(b'\xff\xfeprivate') - report = obs.collect_report([{'runtime': 'claude', 'path': path}]) - assert report['diagnostics']['unreadable_sources'] == 1 - assert report['records'] == [] - - -def test_execution_failure_rate_uses_explicit_outcomes_only(tmp_path): - item = source(tmp_path, 'manual', [{'schema': 1, 'kind': 'runtime_metadata', 'outcome': outcome} - for outcome in ('success', 'failure', 'interrupted', 'unknown', 'invalid')]) - report = obs.collect_report([item]) - assert len(report['records']) == 4 - assert report['total'][0]['failureRate'] == .5 - assert report['total'][0]['outcomes'] == {'success': 1, 'failure': 1, 'interrupted': 1, 'unknown': 1} - assert report['diagnostics']['invalid_metadata'] == 1 - - -def source(tmp_path, runtime, rows): - path = tmp_path / (runtime + '.jsonl') - path.write_text(''.join(json.dumps(row) + '\n' for row in rows), encoding='utf-8') - return {'runtime': runtime, 'path': path} - - -def token_row(total, at='2026-01-01T00:00:00Z'): - return {'type': 'event_msg', 'timestamp': at, 'payload': {'type': 'token_count', 'info': {'total_token_usage': total}}} - - -def test_codex_cumulative_duplicates_partial_reset_and_time_filter(tmp_path): - item = source(tmp_path, 'codex', [ - {'type': 'session_meta', 'payload': {'id': 's'}}, - {'type': 'turn_context', 'payload': {'model': 'observed', 'effort': 'high'}}, - token_row({'input_tokens': 10, 'output_tokens': 2}), - token_row({'input_tokens': 10, 'output_tokens': 2}), - token_row({'input_tokens': 15}, '2026-01-01T00:01:00Z'), - token_row({'input_tokens': 18, 'output_tokens': 4}, '2026-01-01T00:02:00Z'), - token_row({'input_tokens': 3, 'output_tokens': 1}, '2026-01-01T00:03:00Z')]) - report = obs.collect_report([item], start='2026-01-01T00:01:00Z') - assert [row['tokens']['input_tokens'] for row in report['records']] == [5, 3, 3] - assert report['total'][0]['tokens']['output_tokens'] == 3 - assert report['total'][0]['coverage']['output_tokens'] == {'known': 2, 'unknown': 1} - assert report['diagnostics']['duplicate_cumulative_records'] == 1 - assert report['diagnostics']['cumulative_resets'] == 1 - assert report['records'][0]['model'] == 'observed' - assert report['records'][0]['requestedModel'] == 'unknown' - - -def test_claude_stream_maximum_unknown_and_no_content_export(tmp_path): - def row(output): - return {'type': 'assistant', 'timestamp': '2026-01-01T00:00:00Z', 'requestId': 'r', - 'sessionId': 's', 'message': {'id': 'm', 'model': 'observed', 'content': 'PRIVATE BODY', - 'usage': {'input_tokens': 10, 'output_tokens': output}}} - item = source(tmp_path, 'claude', [row(1), row(3)]) - report = obs.collect_report([item, item]) - assert len(report['records']) == 1 - assert report['total'][0]['tokens']['output_tokens'] == 3 - assert report['total'][0]['tokens']['cache_creation_input_tokens'] is None - output = tmp_path / 'report.json' - obs.export_report(report, output) - text = output.read_text() - assert 'PRIVATE BODY' not in text and str(item['path']) not in text - assert report['diagnostics']['duplicate_sources'] == 1 - - -def test_grok_unknown_does_not_claim_zero_usage(tmp_path): - item = source(tmp_path, 'grok', [{'timestamp': '2026-01-01T00:00:00Z', 'params': { - 'sessionId': 'g', 'update': {'sessionUpdate': 'turn_completed'}}}]) - report = obs.collect_report([item]) - assert report['total'][0]['tokens']['input_tokens'] is None - assert report['cost'] is None and report['credits'] is None - assert report['records'][0]['model'] == 'unknown' - - -def test_manual_strict_metadata_and_malformed_tail(tmp_path): - item = source(tmp_path, 'manual', [ - {'schema': 1, 'kind': 'runtime_metadata', 'runtime': 'codex', 'role': 'review', - 'mission': 'm', 'tokens': {'input_tokens': 5}, 'durationSeconds': 2, 'retries': 1}, - {'schema': 1, 'kind': 'runtime_metadata', 'tokens': {'output_tokens': True}}, - {'schema': 1, 'kind': 'runtime_metadata', 'raw': 'PRIVATE'}, - {'schema': 1, 'kind': 'runtime_metadata', 'durationSeconds': float('inf')}]) - with item['path'].open('a') as stream: - stream.write('{partial') - report = obs.collect_report([item]) - assert len(report['records']) == 1 - assert report['byMission'][0]['mission'] == 'm' - assert report['byRole'][0]['retries'] == 1 - assert report['diagnostics']['invalid_metadata'] == 3 - assert report['diagnostics']['malformed_records'] == 1 - csv = tmp_path / 'report.csv' - obs.export_report(report, csv, 'csv') - assert 'input_tokens' in csv.read_text() and 'PRIVATE' not in csv.read_text() - - -def test_schema_versions_and_imported_raw_fields_rejected(tmp_path): - migrated = obs.normalize_report({'schema': 1, 'total': {'usage': {'input_tokens': 1}}, 'source': 'PRIVATE'}) - assert migrated['schema'] == 2 and migrated['total'][0]['tokens']['input_tokens'] == 1 - assert migrated['diagnostics']['legacy_aggregate_only'] == 1 - with pytest.raises(ValueError): - obs.normalize_report({'schema': 999}) - row = obs.empty_record('codex') - row['source'] = 'PRIVATE' - with pytest.raises(ValueError): - obs.export_report({'schema': 2, 'records': [row]}, tmp_path / 'bad.json') - - -def test_explicit_activity_mapping_preserves_unknown_without_guess(tmp_path): - item = source(tmp_path, 'manual', [{'schema': 1, 'kind': 'runtime_metadata', 'sessionId': 's', - 'timestamp': '2026-01-01T00:00:00Z', 'role': 'code-reviewer'}]) - report = obs.collect_report([item]) - assert report['records'][0]['taskKind'] == 'unknown' - mapping = tmp_path / 'map.json' - mapping.write_text(json.dumps({'schema': 1, 'activities': [{'sessionId': 's', 'taskKind': 'review', 'mission': 'm'}]})) - mapped = obs.collect_report([item], activities=obs.legacy.load_activity_map(mapping)) - assert mapped['records'][0]['mission'] == 'm' - assert mapped['records'][0]['activityStatus'] == 'assigned' - - -def test_quality_export_sanitized_and_summary_preserved(tmp_path): - report = obs.collect_report([], quality=[{'project': 'synthetic', 'verificationAttempts': [ - {'status': 'pass', 'source': '/private/log', 'seconds': 2}, {'status': 'fail'}], - 'reviews': [{'findingsCount': 2}], 'recordedRetries': [{'unit': 'u'}], 'raw': 'PRIVATE'}]) - path = tmp_path / 'quality.json' - obs.export_report(report, path) - exported = json.loads(path.read_text()) - assert exported['qualitySummary']['passRate'] == .5 - assert exported['qualitySummary']['roundFindings'] == 2 - assert 'PRIVATE' not in path.read_text() and '/private/log' not in path.read_text() - obs.export_report(report, path, 'csv') - assert 'quality' in path.read_text() and 'PRIVATE' not in path.read_text() - - -def test_strict_normalization_recomputes_aggregates(tmp_path): - row = obs.empty_record('manual') - row['tokens']['input_tokens'] = 3 - report = obs.normalize_report({'schema': 2, 'records': [row], 'total': {'raw': 'PRIVATE'}, 'raw': 'PRIVATE'}) - assert report['total'][0]['tokens']['input_tokens'] == 3 - assert 'raw' not in report - del row['phase'] - with pytest.raises(ValueError): - obs.normalize_report({'schema': 2, 'records': [row]}) - - -@pytest.mark.parametrize('attempt', [{'raw': 'PRIVATE BODY'}, [], True, -1, '', 'x' * 257]) -def test_attempt_cannot_export_structures_or_unbounded_metadata(tmp_path, attempt): - row = obs.empty_record('manual') - row['attempt'] = attempt - with pytest.raises(ValueError): - obs.export_report({'schema': 2, 'records': [row]}, tmp_path / 'report.json') - - -@pytest.mark.parametrize('quality', [ - [1], [{'reviews': [None]}], [{'verificationAttempts': [1]}], - [{'verificationAttempts': [{'executionCounts': {'executed': {'raw': 'PRIVATE BODY'}}}]}], - [{'reviews': [{'findingsCount': 'PRIVATE BODY'}]}], - [{'verificationAttempts': [{'seconds': float('nan')}]}], - [{'verificationSummary': {'failed': float('inf')}}], -]) -def test_quality_corruption_fails_with_value_error(quality): - with pytest.raises(ValueError): - obs.normalize_report({'schema': 2, 'records': [], 'quality': quality}) - - -@pytest.mark.parametrize('generated', [None, {}, 123, 'PRIVATE BODY', '2026-01-01T00:00:00']) -def test_generated_at_is_validated(generated): - with pytest.raises(ValueError): - obs.normalize_report({'schema': 2, 'records': [], 'generatedAt': generated}) - - -def test_legacy_totals_preserve_values_without_claiming_observed_coverage(tmp_path): - report = obs.normalize_report({'schema': 1, 'total': {'usage': {'input_tokens': 0, 'output_tokens': 7}}}) - total = report['total'][0] - assert total['tokens']['input_tokens'] == 0 and total['tokens']['output_tokens'] == 7 - assert total['records'] == 0 and total['aggregateRecords'] == 1 - assert total['coverageBasis'] == 'aggregate_unknown' - assert total['coverage']['input_tokens'] == {'known': None, 'unknown': None} - assert report['diagnostics']['legacy_missingness_unknown'] == 1 - target = tmp_path / 'migration.json' - obs.export_report(report, target) - assert json.loads(target.read_text())['total'][0]['records'] == 0 - - -@pytest.mark.parametrize('value', ['=SUM(1,2)', '+1+2', '-1+2', '@SUM(A1)', '\t=1+1', ' =1+1']) -def test_csv_formula_metadata_is_escaped(tmp_path, value): - import csv - row = obs.empty_record('manual') - row['project'] = value - target = tmp_path / 'report.csv' - obs.export_report({'schema': 2, 'records': [row]}, target, 'csv') - with target.open() as stream: - exported = list(csv.DictReader(stream)) - assert exported[0]['project'] == "'" + value - - -def test_pure_serialization_reuses_validated_csv_and_json(): - row = obs.empty_record('manual') - row['project'] = '=1+1' - report = {'schema': 2, 'records': [row]} - assert json.loads(obs.serialize_report(report))['records'][0]['project'] == '=1+1' - assert "'=1+1" in obs.serialize_report(report, 'csv') diff --git a/tests/integration/mission/test_p4c_close_stale.py b/tests/integration/mission/test_p4c_close_stale.py deleted file mode 100644 index 72d5ef6..0000000 --- a/tests/integration/mission/test_p4c_close_stale.py +++ /dev/null @@ -1,113 +0,0 @@ -import json -import os -import sys -import time -from pathlib import Path - -import pytest -from chef.cli import p4c as p4c -from chef.mission import state as mission_state - -from tests.paths import PLUGIN_ROOT - -DAY = 24 * 3600 -ADAPTER = {"schema": 1, "paths": {"stateDir": "state"}, "stages": [{"id": "impl"}]} -MISSION_MD = "# m1\n\n상태: 진행\n현재 단계: impl\n\n## 목표\nx\n" - - -@pytest.fixture -def project(tmp_path, monkeypatch): - for name in ("CLAUDE_PROJECT_DIR", "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "HAN_STALE_HOURS"): - monkeypatch.delenv(name, raising=False) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "no-registry")) - root = tmp_path / "project" - (root / ".claude" / "orchestrator").mkdir(parents=True) - (root / ".claude" / "orchestrator" / "adapter.json").write_text(json.dumps(ADAPTER), encoding="utf-8") - folder = root / "state" / "m1" - folder.mkdir(parents=True) - (folder / "mission.md").write_text(MISSION_MD, encoding="utf-8") - (root / "state" / "ACTIVE").write_text( - json.dumps({"id": "m1", "session": "s1", "openedAt": "2026-10-19T09:00:00+09:00"}), encoding="utf-8" - ) - return root - - -def age(root, seconds): - moment = time.time() - seconds - for path in [root / "state" / "ACTIVE", *(root / "state" / "m1").rglob("*")]: - os.utime(path, (moment, moment)) - - -def run(capsys, root, *args): - capsys.readouterr() - code = mission_state.main(["--project", str(root), *args]) - captured = capsys.readouterr() - return code, captured.out, captured.err - - -def test_active_reports_live_and_stale(project, capsys): - code, out, _ = run(capsys, project, "active") - assert code == 0 and "ACTIVE m1" in out and "살아 있음" in out - age(project, 2 * DAY) - code, out, _ = run(capsys, project, "active") - assert code == 0 and "끊김 의심" in out - - -def test_active_without_active_file(project, capsys): - (project / "state" / "ACTIVE").unlink() - code, out, _ = run(capsys, project, "active") - assert code == 0 and "ACTIVE 없음" in out - - -def test_close_stale_refuses_live_mission(project, capsys): - code, _, err = run(capsys, project, "close-stale", "--force-close-stale") - assert code == 1 and "끊김 아님" in err - assert (project / "state" / "ACTIVE").exists() - - -def test_close_stale_preview_without_flag(project, capsys): - age(project, 2 * DAY) - code, out, _ = run(capsys, project, "close-stale") - assert code == 1 and "미리보기" in out - assert (project / "state" / "ACTIVE").exists() - assert "상태: 진행" in (project / "state" / "m1" / "mission.md").read_text(encoding="utf-8") - - -def test_close_stale_with_flag(project, capsys): - age(project, 2 * DAY) - code, out, _ = run(capsys, project, "close-stale", "--force-close-stale", "--reason", "좀비") - assert code == 0, out - assert not (project / "state" / "ACTIVE").exists() - folder = project / "state" / "m1" - assert "상태: 중단" in (folder / "mission.md").read_text(encoding="utf-8") - log = (folder / "force-close.log").read_text(encoding="utf-8") - assert "session=s1" in log and "reason=좀비" in log - - -def test_close_stale_keep_state_and_hours(project, capsys): - age(project, 3 * 3600) - code, _, _ = run(capsys, project, "close-stale", "--force-close-stale") - assert code == 1 - code, _, _ = run(capsys, project, "close-stale", "--force-close-stale", "--hours", "2", "--keep-state") - assert code == 0 - assert "상태: 진행" in (project / "state" / "m1" / "mission.md").read_text(encoding="utf-8") - - -def test_p4c_dry_run_pins_client(project, capsys): - (project / ".p4config").write_text("P4CLIENT=ws_cfg\n", encoding="utf-8") - assert p4c.main(["--project", str(project), "--which"]) == 0 - assert capsys.readouterr().out.strip() == "ws_cfg" - assert p4c.main(["--project", str(project), "--dry-run", "edit", "-c", "12", "a.cs"]) == 0 - assert capsys.readouterr().out.strip() == "p4 -c ws_cfg edit -c 12 a.cs" - - -def test_p4c_refuses_mismatch_and_double_client(project, capsys): - (project / ".p4config").write_text("P4CLIENT=ws_cfg\n", encoding="utf-8") - assert p4c.main(["--project", str(project), "--client", "ws_other", "sync"]) == 2 - assert p4c.main(["--project", str(project), "-c", "ws_cfg", "sync"]) == 2 - assert p4c.main(["--project", str(project), "-cws_cfg", "sync"]) == 2 - - -def test_p4c_without_client_fails(project, capsys): - assert p4c.main(["--project", str(project), "sync"]) == 2 - assert "작업 공간" in capsys.readouterr().err diff --git a/tests/integration/mission/test_plan_policy.py b/tests/integration/mission/test_plan_policy.py deleted file mode 100644 index fd02182..0000000 --- a/tests/integration/mission/test_plan_policy.py +++ /dev/null @@ -1,401 +0,0 @@ -"""Opt-in direct checks use fictional tools and fail closed to the verifier.""" - -import copy -import os -import subprocess -import sys - -import pytest - -from chef.verification import plan as verification_plan -from chef.verification import plan_policy, runner - - -@pytest.fixture -def trusted_check(tmp_path): - (tmp_path / "tools").mkdir() - (tmp_path / "src").mkdir() - (tmp_path / "src" / "sample.txt").write_text("fictional input\n", encoding="utf-8") - (tmp_path / "tools" / "lint.py").write_text("print('fictional lint passed')\n", encoding="utf-8") - executable = tmp_path / ("python-fictional.exe" if os.name == "nt" else "python-fictional") - executable.write_bytes(b"fictional executable identity; never launched") - executable.chmod(0o700) - command = { - "id": "lint", "argv": [str(executable), "tools/lint.py", "--check"], "cwd": ".", - "reusable": True, "inputs": ["src/sample.txt", "tools/lint.py"], "outputs": [], - } - plan = { - "grade": "doc-only", "inputs": ["src/sample.txt", "tools/lint.py"], - "environment": {"target": "fictional-local"}, "commands": [command], "results": [], - } - spec = { - "argv": list(command["argv"]), "cwd": ".", - "tools": verification_plan.command_runtime(tmp_path, command)["tools"], - } - settings = {"grades": ["doc-only"], "coordinatorChecks": [{"grade": "doc-only", "commands": [spec]}]} - return tmp_path, plan, settings - - -def reason_codes(result): - return {item["code"] for item in result["reasons"]} - - -def test_explicit_pinned_lint_is_eligible_without_execution_or_writes(trusted_check, monkeypatch): - root, plan, settings = trusted_check - original = copy.deepcopy((plan, settings)) - before = {str(path): path.read_bytes() for path in root.rglob("*") if path.is_file()} - - def unexpected(*args, **kwargs): - pytest.fail("classification must not launch a process") - - monkeypatch.setattr(subprocess, "run", unexpected) - expected = {"eligible": True, "route": "coordinator", "reasons": []} - assert verification_plan.coordinator_eligibility(root, plan, settings) == expected - assert verification_plan.require_coordinator_eligible(root, plan, settings) == expected - checked = verification_plan.preflight(root, plan, lambda command: None, settings) - assert checked["status"] == "pass" and checked["warnings"] == [] - assert checked["executionPolicy"] == expected - assert (plan, settings) == original - assert {str(path): path.read_bytes() for path in root.rglob("*") if path.is_file()} == before - - -def test_legacy_plan_still_passes_with_structured_advisories(trusted_check): - root, plan, _ = trusted_check - command = plan["commands"][0] - for field in ("reusable", "inputs", "outputs"): - del command[field] - checked = verification_plan.preflight(root, plan, lambda command: None) - assert checked["status"] == "pass" - assert checked["executionPolicy"]["route"] == "verifier" - assert {warning["code"] for warning in checked["warnings"]} == { - "reuse_policy_missing", "command_inputs_missing", "command_outputs_missing", - } - assert all(warning["commandIndex"] == 0 and warning["field"] for warning in checked["warnings"]) - - -@pytest.mark.parametrize("timeout", [1, 3600]) -def test_deadline_neither_estimates_duration_nor_grants_trust(trusted_check, timeout): - root, plan, settings = trusted_check - plan["commands"][0]["timeoutSeconds"] = timeout - assert verification_plan.coordinator_eligibility(root, plan, settings)["eligible"] - assert verification_plan.coordinator_eligibility(root, plan)["route"] == "verifier" - - -@pytest.mark.parametrize("argv", [ - ["sh", "-c", "echo fictional"], - ["pwsh", "-Command", "Write-Output fictional"], - [sys.executable, "tools/build.py"], - [sys.executable, "-m", "pytest", "-q"], - [sys.executable, "tools/lint.py", "--fix"], -]) -def test_untrusted_shell_build_test_or_altered_argv_stays_with_verifier(trusted_check, argv): - root, plan, settings = trusted_check - (root / "tools" / "build.py").write_text("print('fictional build')\n", encoding="utf-8") - plan["commands"][0].update(argv=argv, timeoutSeconds=1, outputs=[]) - checked = verification_plan.coordinator_eligibility(root, plan, settings) - assert not checked["eligible"] and checked["route"] == "verifier" - - -def test_edited_script_and_replaced_executable_invalidate_trust(trusted_check, monkeypatch): - root, plan, settings = trusted_check - script = root / "tools" / "lint.py" - script.write_text("print('changed fictional tool')\n", encoding="utf-8") - assert reason_codes(verification_plan.coordinator_eligibility(root, plan, settings)) == {"command_identity_mismatch"} - settings["coordinatorChecks"][0]["commands"][0]["tools"] = verification_plan.command_runtime(root, plan["commands"][0])["tools"] - original = verification_plan.command_runtime - - def replaced(project, command): - runtime = original(project, command) - runtime["tools"][runtime["executable"]] = "0" * 64 - return runtime - - monkeypatch.setattr(verification_plan, "command_runtime", replaced) - assert reason_codes(verification_plan.coordinator_eligibility(root, plan, settings)) == {"command_identity_mismatch"} - - -@pytest.mark.parametrize("change", ["append", "remove", "cwd", "order", "split-policy"]) -def test_allowlist_matches_entire_ordered_plan(trusted_check, change): - root, plan, settings = trusted_check - if change == "remove": - settings["coordinatorChecks"][0]["commands"].append(copy.deepcopy(settings["coordinatorChecks"][0]["commands"][0])) - elif change == "cwd": - plan["commands"][0]["cwd"] = "src" - else: - second = copy.deepcopy(plan["commands"][0]) - second.update(id="second", argv=[second["argv"][0], "tools/lint.py", "--strict"]) - plan["commands"].append(second) - if change in ("order", "split-policy"): - spec = copy.deepcopy(settings["coordinatorChecks"][0]["commands"][0]) - spec["argv"] = list(second["argv"]) - if change == "order": - settings["coordinatorChecks"][0]["commands"].insert(0, spec) - else: - settings["coordinatorChecks"].append({"grade": "doc-only", "commands": [spec]}) - checked = verification_plan.coordinator_eligibility(root, plan, settings) - assert checked["route"] == "verifier" - assert reason_codes(checked) <= {"command_identity_mismatch", "launcher_unpinned"} - - -def test_matching_full_multicommand_plan_is_eligible(trusted_check): - root, plan, settings = trusted_check - second = copy.deepcopy(plan["commands"][0]) - second.update(id="second", argv=[second["argv"][0], "tools/lint.py", "--strict"]) - plan["commands"].append(second) - spec = copy.deepcopy(settings["coordinatorChecks"][0]["commands"][0]) - spec["argv"] = list(second["argv"]) - settings["coordinatorChecks"][0]["commands"].append(spec) - assert verification_plan.coordinator_eligibility(root, plan, settings)["eligible"] - - -@pytest.mark.parametrize("change", [ - "no-grades", "wrong-grade", "missing-tools", "missing-script-pin", "changed-extra-pin", "bad-pin", - "policy-option", "command-option", "empty-policy", "wrong-policy-type", "missing-cwd", -]) -def test_missing_or_unsupported_configuration_defaults_to_verifier(trusted_check, change): - root, plan, settings = trusted_check - spec = settings["coordinatorChecks"][0]["commands"][0] - if change == "no-grades": - del settings["grades"] - elif change == "wrong-grade": - settings["grades"] = ["compile-only"] - elif change == "missing-tools": - del spec["tools"] - elif change == "missing-script-pin": - del spec["tools"][str((root / "tools" / "lint.py").resolve())] - elif change == "changed-extra-pin": - spec["tools"]["src/sample.txt"] = "0" * 64 - elif change == "bad-pin": - spec["tools"][sys.executable] = "not-a-sha256" - elif change == "policy-option": - settings["coordinatorChecks"][0]["allowShell"] = True - elif change == "command-option": - spec["timeoutSeconds"] = 1 - elif change == "empty-policy": - settings["coordinatorChecks"] = [] - elif change == "wrong-policy-type": - settings["coordinatorChecks"] = {"grade": "doc-only"} - else: - del spec["cwd"] - assert verification_plan.coordinator_eligibility(root, plan, settings)["route"] == "verifier" - - -def test_relative_tool_pin_and_resolved_cwd_match(trusted_check): - root, plan, settings = trusted_check - spec = settings["coordinatorChecks"][0]["commands"][0] - script_hash = spec["tools"].pop(str((root / "tools" / "lint.py").resolve())) - spec["tools"]["tools/lint.py"] = script_hash - spec["cwd"] = "src/.." - assert verification_plan.coordinator_eligibility(root, plan, settings)["eligible"] - - -def test_additional_pinned_dependency_changes_invalidate_trust(trusted_check): - root, plan, settings = trusted_check - helper = root / "tools" / "helper.py" - helper.write_text("value = 'fictional helper'\n", encoding="utf-8") - settings["coordinatorChecks"][0]["commands"][0]["tools"]["tools/helper.py"] = verification_plan.file_hash(helper) - assert verification_plan.coordinator_eligibility(root, plan, settings)["eligible"] - helper.write_text("value = 'changed fictional helper'\n", encoding="utf-8") - assert verification_plan.coordinator_eligibility(root, plan, settings)["route"] == "verifier" - helper.unlink() - assert verification_plan.coordinator_eligibility(root, plan, settings)["route"] == "verifier" - - -def test_policy_and_dependency_changes_reject_receipt_and_prevent_reuse(trusted_check, monkeypatch): - root, plan, settings = trusted_check - helper = root / "tools" / "helper.py" - helper.write_text("value = 'fictional helper'\n", encoding="utf-8") - pins = settings["coordinatorChecks"][0]["commands"][0]["tools"] - pins["tools/helper.py"] = verification_plan.file_hash(helper) - assert "tools/helper.py" not in plan["inputs"] - executions = [] - - def execute(project, command, identity, log): - executions.append(command["id"]) - log.write(b"fictional check completed\n") - return subprocess.CompletedProcess(command["argv"], 0) - - monkeypatch.setattr(runner, "execute_command", execute) - folder = root / "mission" - folder.mkdir() - _, receipt, reused = runner.run(root, folder, "M1", plan, lambda command: None, settings=settings) - assert receipt["status"] == "pass" and not reused - runner.validate_receipt(root, folder, "M1", receipt, settings=settings) - original_runtime = verification_plan.runtime_key(root, plan, settings) - helper.write_text("value = 'changed fictional helper'\n", encoding="utf-8") - assert verification_plan.runtime_key(root, plan, settings) != original_runtime - with pytest.raises(verification_plan.VerificationError): - runner.validate_receipt(root, folder, "M1", receipt, settings=settings) - pins["tools/helper.py"] = verification_plan.file_hash(helper) - assert verification_plan.coordinator_eligibility(root, plan, settings)["eligible"] - with pytest.raises(verification_plan.VerificationError): - runner.validate_receipt(root, folder, "M1", receipt, settings=settings) - _, fresh, reused = runner.run(root, folder, "M1", plan, lambda command: None, settings=settings) - assert fresh["status"] == "pass" and not reused and executions == ["lint", "lint"] - - -def test_missing_policy_preserves_existing_runtime_policy_identity(trusted_check): - root, plan, _ = trusted_check - assert verification_plan.policy_settings(root, plan) == {} - assert verification_plan.policy_settings(root, plan, {"grades": ["doc-only"]}) == {} - assert verification_plan.policy_runtime(root, plan) == {} - - -def test_unreadable_trusted_tool_fails_closed(trusted_check, monkeypatch): - root, plan, settings = trusted_check - - def unreadable(path): - raise OSError("fictional unreadable tool") - - monkeypatch.setattr(plan_policy, "file_hash", unreadable) - assert verification_plan.coordinator_eligibility(root, plan, settings)["route"] == "verifier" - - -@pytest.mark.parametrize("arguments", [["-m", "fictional_lint"], ["-c", "print('fictional')"]]) -def test_even_allowlisted_scriptless_interpreter_stays_with_verifier(trusted_check, arguments): - root, plan, settings = trusted_check - command = plan["commands"][0] - command["argv"] = [command["argv"][0], *arguments] - spec = settings["coordinatorChecks"][0]["commands"][0] - spec.update(argv=command["argv"], tools=verification_plan.command_runtime(root, command)["tools"]) - assert reason_codes(verification_plan.coordinator_eligibility(root, plan, settings)) == {"launcher_unpinned"} - - -@pytest.mark.parametrize("name,arguments", [("fictional.cmd", []), ("fictional.bat", [])]) -def test_even_allowlisted_shell_inline_and_batch_wrappers_stay_with_verifier(trusted_check, name, arguments): - root, plan, settings = trusted_check - executable = root / name - executable.write_bytes(b"fictional launcher; never launched") - executable.chmod(0o700) - command = plan["commands"][0] - command["argv"] = [str(executable), *arguments] - spec = settings["coordinatorChecks"][0]["commands"][0] - spec.update(argv=command["argv"], tools=verification_plan.command_runtime(root, command)["tools"]) - assert reason_codes(verification_plan.coordinator_eligibility(root, plan, settings)) == {"launcher_unpinned"} - - -@pytest.mark.parametrize("name,options", [ - ("bash", ["-lc"]), ("bash", ["-cl"]), ("bash", ["-o", "nounset", "-c"]), - ("BASH.exe", ["-lc"]), ("sh", ["-c"]), ("zsh", ["-c"]), ("dash", ["-c"]), - ("ash", ["-c"]), ("ksh", ["-c"]), ("csh", ["-c"]), ("tcsh", ["-c"]), ("fish", ["-c"]), - ("pwsh", ["-c"]), ("pwsh", ["-Co"]), ("pwsh", ["-CommandWithArgs"]), ("pwsh", ["-File"]), - ("powershell", ["-C"]), ("powershell", ["-Command"]), - ("powershell.exe", ["-NoProfile", "-File"]), ("cmd", ["/c"]), -]) -def test_allowlisted_shells_cannot_gain_direct_route_from_existing_file_argument(trusted_check, monkeypatch, name, options): - root, plan, settings = trusted_check - executable = root / name - executable.write_bytes(b"fictional shell identity; never launched") - executable.chmod(0o700) - command = plan["commands"][0] - command["argv"] = [str(executable), *options, "tools/lint.py"] - runtime = verification_plan.command_runtime(root, command) - if (name, options) in [("bash", ["-lc"]), ("pwsh", ["-c"]), ("pwsh", ["-File"])]: - assert len(runtime["tools"]) == 2 - spec = settings["coordinatorChecks"][0]["commands"][0] - spec.update(argv=command["argv"], tools=runtime["tools"]) - - def unexpected(*args, **kwargs): - pytest.fail("shell preflight must not execute a command") - - monkeypatch.setattr(subprocess, "run", unexpected) - before = {str(path): path.read_bytes() for path in root.rglob("*") if path.is_file()} - checked = verification_plan.preflight(root, plan, lambda command: None, settings) - assert checked["status"] == "pass" - assert checked["executionPolicy"]["route"] == "verifier" - assert reason_codes(checked["executionPolicy"]) == {"shell_requires_verifier"} - with pytest.raises(verification_plan.VerificationError) as error: - verification_plan.require_coordinator_eligible(root, plan, settings) - assert error.value.category == "coordinator_ineligible" - assert {str(path): path.read_bytes() for path in root.rglob("*") if path.is_file()} == before - - -def test_pinned_native_checker_keeps_direct_route(trusted_check): - root, plan, settings = trusted_check - executable = root / "fictional-lint.exe" - executable.write_bytes(b"fictional native checker identity; never launched") - executable.chmod(0o700) - command = plan["commands"][0] - command["argv"] = [str(executable), "--check"] - spec = settings["coordinatorChecks"][0]["commands"][0] - spec.update(argv=command["argv"], tools=verification_plan.command_runtime(root, command)["tools"]) - assert verification_plan.require_coordinator_eligible(root, plan, settings)["route"] == "coordinator" - - -@pytest.mark.parametrize("preparation", ["readiness", "resources"]) -def test_preparation_keeps_verifier_route(trusted_check, preparation): - root, plan, settings = trusted_check - if preparation == "readiness": - settings["readiness"] = {"doc-only": [{"argv": [sys.executable, "-c", "pass"]}]} - else: - settings.update(resourceDir="locks", resources={"doc-only": ["fictional-resource"]}) - checked = verification_plan.preflight(root, plan, lambda command: None, settings) - assert checked["status"] == "pass" - assert reason_codes(checked["executionPolicy"]) == {"preparation_required"} - assert not (root / "locks").exists() - - -@pytest.mark.parametrize("field", ["reusable", "inputs", "outputs"]) -def test_direct_execution_requires_explicit_step_declarations(trusted_check, field): - root, plan, settings = trusted_check - if field == "outputs": - plan["commands"][0]["reusable"] = False - del plan["commands"][0][field] - assert verification_plan.coordinator_eligibility(root, plan, settings)["route"] == "verifier" - - -def test_explicit_nonreusable_readonly_check_is_supported(trusted_check): - root, plan, settings = trusted_check - plan["commands"][0]["reusable"] = False - assert verification_plan.coordinator_eligibility(root, plan, settings)["eligible"] - - -@pytest.mark.parametrize("scope", ["plan-inputs", "command-inputs", "command-outputs"]) -def test_whole_project_scopes_are_advisory_and_not_direct(trusted_check, scope): - root, plan, settings = trusted_check - plan["inputs"] = ["."] - if scope == "command-inputs": - plan["commands"][0]["inputs"] = ["**/*"] - elif scope == "command-outputs": - plan["commands"][0]["outputs"] = ["."] - checked = verification_plan.preflight(root, plan, lambda command: None, settings) - assert checked["status"] == "pass" and checked["warnings"] - assert checked["executionPolicy"]["route"] == "verifier" - - -def test_nonempty_outputs_and_result_artifacts_keep_verifier(trusted_check): - root, plan, settings = trusted_check - plan["commands"][0]["outputs"] = ["lint-result.json"] - assert reason_codes(verification_plan.coordinator_eligibility(root, plan, settings)) == {"outputs_declared"} - plan["results"] = [{"path": "lint-result.json", "command": "lint", "equals": {"status": "passed"}}] - assert reason_codes(verification_plan.coordinator_eligibility(root, plan, settings)) == {"result_artifacts"} - - -def test_eligibility_does_not_bypass_existing_plan_grade_result_validation(trusted_check): - root, plan, settings = trusted_check - plan["grade"] = "editmode-pass" - settings["grades"].append("editmode-pass") - settings["coordinatorChecks"][0]["grade"] = "editmode-pass" - checked = verification_plan.preflight(root, plan, lambda command: None, settings) - assert checked["status"] == "fail" and checked["failure"]["category"] == "plan_invalid" - with pytest.raises(verification_plan.VerificationError) as error: - verification_plan.require_coordinator_eligible(root, plan, settings) - assert error.value.category == "coordinator_ineligible" - - -def test_allowlist_does_not_bypass_guard(trusted_check): - root, plan, settings = trusted_check - - def guard(command): - raise RuntimeError("fictional guard denied this command") - - checked = verification_plan.preflight(root, plan, guard, settings) - assert checked["status"] == "fail" and checked["failure"]["category"] == "guard_rejected" - assert not checked["executionPolicy"]["eligible"] - - -def test_invalid_optional_policy_does_not_break_old_verifier_plan(trusted_check): - root, plan, settings = trusted_check - settings["coordinatorChecks"] = {"unsupported": True} - checked = verification_plan.preflight(root, plan, lambda command: None, settings) - assert checked["status"] == "pass" - assert reason_codes(checked["executionPolicy"]) == {"policy_invalid"} diff --git a/tests/integration/mission/test_portable_verification.py b/tests/integration/mission/test_portable_verification.py deleted file mode 100644 index c4811ed..0000000 --- a/tests/integration/mission/test_portable_verification.py +++ /dev/null @@ -1,221 +0,0 @@ -"""Portable process, path, and policy behavior with fictional local inputs.""" - -import base64 -import io -import json -import os -import shutil -import subprocess -import sys -from pathlib import Path -from types import SimpleNamespace -from urllib.parse import unquote - -import pytest - -from chef.dashboard.models import raw_url -from chef.guards import mission -from chef.mission import state, supervisor, usage -from chef.verification import plan, runner - - -def adapter(): - return {"guard": {"deny": [{"pattern": "^dangerous-operation$", "reason": "fictional blocked operation"}]}} - - -def test_verification_argv_data_is_not_reinterpreted_as_shell(tmp_path): - context = SimpleNamespace(adapter=adapter(), project=str(tmp_path)) - command = {"argv": [sys.executable, "-c", "import sys; print(sys.argv[1])", "$(dangerous-operation)"], "cwd": "."} - identity = plan.guarded_runtime(str(tmp_path), command, state.verification_guard(context)) - with (tmp_path / "result.log").open("wb") as log: - result = runner.execute_command(str(tmp_path), command, identity, log) - assert result.returncode == 0 - assert (tmp_path / "result.log").read_text(encoding="utf-8").strip() == "$(dangerous-operation)" - - -@pytest.mark.parametrize("argv", [ - ["p4", "submit"], - ["p4", "-p", 'fictional-host"quoted', "submit"], - ["env", "LABEL=literal;data", "p4", "submit"], - ["env", "-u", "LABEL", "p4", "submit"], - ["sudo", "-u", "fictional-user", "p4", "submit"], - ["nohup", "p4", "submit"], - ["timeout", "-s", "TERM", "5", "p4", "submit"], - ["xargs", "-n", "1", "p4", "submit"], - ["bash", "-o", "nounset", "-c", "p4 submit"], - ["bash", "-c", "--", "p4 submit"], - ["bash", "+c", "p4 submit"], - ["bash", "-lc", "--", "p4 submit"], - ["sh", "-c", "--", "p4 submit"], - ["bash", "-c", "-x", "p4 submit"], - ["bash", "-c", "+x", "p4 submit"], - ["bash", "-c", "-o", "nounset", "p4 submit"], - ["bash", "-co", "nounset", "p4 submit"], - ["bash", "-oc", "nounset", "p4 submit"], - ["env", "bash", "-lc", "p4 submit"], - ["pwsh", "-Command", "p4 submit"], - ["pwsh", "-EncodedCommand", base64.b64encode("p4 submit".encode("utf-16-le")).decode("ascii")], - ["python3", "p4c.py", "--client", "fictional-client", "submit"], - [sys.executable, "--check-hash-based-pycs", "never", "p4c.py", "submit"], -]) -def test_structured_argv_preserves_p4_policy_through_explicit_wrappers(argv): - policy = {"guard": {"p4Deny": [{"commands": ["submit"], "reason": "fictional submit restriction"}]}} - assert mission.judge_argv(policy, argv).kind == "rule" - - -def test_direct_p4_argv_still_checks_client_even_when_allow_pattern_matches(tmp_path): - (tmp_path / ".p4config").write_text("P4CLIENT=fictional-garden\n", encoding="utf-8") - policy = {"guard": {"allow": [".*"], "p4Client": {"require": True}}} - assert mission.judge_argv(policy, ["p4", "edit", "source.py"], project=str(tmp_path)).kind == "rule" - assert mission.judge_argv(policy, ["p4", "-c", "fictional-other", "edit", "source.py"], project=str(tmp_path)).kind == "rule" - assert mission.judge_argv(policy, ["p4", "-c", "fictional-garden", "edit", "source.py"], project=str(tmp_path)).kind == "allow" - nested = tmp_path / "nested" - nested.mkdir() - context = SimpleNamespace(adapter=policy, project=str(tmp_path)) - with pytest.raises(state.StateError, match="fictional-other"): - state.verification_guard(context).argv(["p4", "-c", "fictional-other", "edit", "source.py"], str(nested)) - for literal in ("fictional-$other", "fictional-{other}"): - assert mission.judge_argv(policy, ["p4", "-c", literal, "edit", "source.py"], project=str(tmp_path)).kind == "rule" - - -def test_p4c_explicit_project_cannot_redirect_protected_operations(tmp_path): - own, foreign = tmp_path / "own", tmp_path / "foreign" - for folder in (own, foreign): - folder.mkdir() - (folder / ".p4config").write_text("P4CLIENT=fictional-" + folder.name + "\n", encoding="utf-8") - policy = {"guard": {"allow": [".*"], "p4Client": {"require": True}}} - argv = ["python3", "p4c.py", "--project", str(foreign), "sync"] - assert mission.judge_argv(policy, argv, project=str(own)).kind == "rule" - from chef.guards.argv import render - assert mission.judge_command(policy, render(argv), "Bash", project=str(own)).kind == "rule" - argv[3] = str(own) - assert mission.judge_argv(policy, argv, project=str(own)).kind == "allow" - nested = own / "nested" - nested.mkdir() - (nested / ".p4config").write_text("P4CLIENT=fictional-nested\n", encoding="utf-8") - context = SimpleNamespace(adapter=policy, project=str(own)) - with pytest.raises(state.StateError, match="cwd"): - state.verification_guard(context).argv(["python3", "p4c.py", "sync"], str(nested)) - state.verification_guard(context).argv(argv, str(nested)) - assert mission.judge_command(policy, "python3 p4c.py sync", "Bash", project=str(own), cwd=str(nested)).kind == "rule" - - -@pytest.mark.parametrize("argv", [["env", "-C", "foreign", "p4", "sync"], ["sudo", "-D", "foreign", "p4", "sync"]]) -def test_scope_changing_wrappers_fail_closed_in_both_guard_paths(argv): - from chef.guards.argv import render - - assert mission.judge_argv({}, argv).kind == "rule" - assert mission.judge_command({}, render(argv), "Bash").kind == "rule" - - -def test_regex_case_option_preserves_default_and_allows_explicit_case_sensitive_paths(): - rule = {"pattern": "^python Trusted/run.py$"} - policy = {"guard": {"allow": [rule], "deny": [{"pattern": "^python", "reason": "restricted"}]}} - assert mission.judge_argv(policy, ["python", "trusted/run.py"]).kind == "allow" - rule["caseSensitive"] = True - assert mission.judge_argv(policy, ["python", "Trusted/run.py"]).kind == "allow" - assert mission.judge_argv(policy, ["python", "trusted/run.py"]).kind == "rule" - rule["caseSensitive"] = "invalid" - problems = [] - mission.judge_argv(policy, ["python", "trusted/run.py"], problems) - assert problems and "caseSensitive" in problems[0] - - -def test_explicit_shell_script_is_inspected_but_its_positional_data_is_not(): - assert mission.judge_argv(adapter(), ["bash", "-c", "dangerous-operation"]).kind == "rule" - assert mission.judge_argv(adapter(), ["bash", "-c", 'printf "%s" "$1"', "shell", "$(dangerous-operation)"]).kind == "allow" - assert mission.judge_argv(adapter(), ["pwsh", "-CommandWithArgs", "Write-Output $args[0]", "$(dangerous-operation)"]).kind == "allow" - - -@pytest.mark.parametrize("shell", ["bash", "sh", "zsh", "dash", "ksh"]) -@pytest.mark.parametrize("options", [["-c", "--"], ["-lc", "--"], ["-c", "-x"], ["-c", "-o", "nounset"], ["+c"]]) -def test_shell_command_operand_matches_actual_local_option_parsing(shell, options, tmp_path): - from chef.guards.argv import describe - - executable = shutil.which(shell) - if os.name == "nt" and shell == "bash": - # The Windows bash launcher enters WSL, whose paths and startup are not - # those of this local-process test. Prefer Git for Windows' native shell. - git = shutil.which("git.exe") - if git: - root = Path(git).resolve().parent.parent - executable = next((str(path) for folder in ("bin", "usr/bin") - if (path := root / folder / f"{shell}.exe").is_file()), executable) - if executable: - windows = os.environ.get("SystemRoot") - if windows and Path(executable).resolve().parent in { - Path(windows) / folder for folder in ("System32", "Sysnative", "SysWOW64") - }: - executable = None - if not executable: - pytest.skip("native local shell unavailable") - script = "printf CHEF_SCRIPT_PROBE" - argv = [executable, *options, script] - assert describe(argv).script == script - home = tmp_path / "home" - home.mkdir() - environment = {key: value for key, value in os.environ.items() if key not in ("BASH_ENV", "ENV")} - environment.update(HOME=str(home), ZDOTDIR=str(home), PWD=str(tmp_path)) - result = subprocess.run(argv, capture_output=True, text=True, timeout=10, env=environment, cwd=tmp_path) - assert result.returncode == 0 and result.stdout == "CHEF_SCRIPT_PROBE" - - -def test_shell_option_delimiter_is_consumed_only_once(): - from chef.guards.argv import describe - - assert describe(["bash", "-c", "--", "--", "p4 submit"]).script == "--" - - -def test_command_child_environment_uses_actual_cwd_without_global_chdir(tmp_path, monkeypatch): - directory = tmp_path / "nested" - directory.mkdir() - monkeypatch.setenv("PWD", str(tmp_path / "unrelated")) - previous = os.getcwd() - command = {"argv": [sys.executable, "-c", "import json,os; print(json.dumps([os.getcwd(),os.environ['PWD']]))"], "cwd": "nested"} - with (tmp_path / "cwd.log").open("wb") as log: - result = runner.execute_command(str(tmp_path), command, {"executable": sys.executable}, log) - actual, environment = json.loads((tmp_path / "cwd.log").read_text(encoding="utf-8")) - assert result.returncode == 0 and os.path.samefile(actual, environment) - assert os.path.samefile(actual, directory) - assert os.getcwd() == previous and os.environ["PWD"] == str(tmp_path / "unrelated") - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX literal backslash filename") -def test_input_snapshot_and_dashboard_raw_url_preserve_literal_backslash(tmp_path): - target = tmp_path / "data\\leaf.txt" - target.write_text("fictional input", encoding="utf-8") - files = plan.snapshot(str(tmp_path), [target.name]) - command = {"inputs": [target.name]} - assert plan.step_inputs(str(tmp_path), command, files) == files - from chef.dashboard.contracts import RAW_PREFIX - assert unquote(raw_url(str(target))[len(RAW_PREFIX):]) == str(target) - - -def test_supervisor_detects_alias_and_filesystem_case_overlap(tmp_path): - project = tmp_path / "Garden" - project.mkdir() - alias = tmp_path / "shortcut" - try: - alias.symlink_to(project, target_is_directory=True) - except OSError: - pytest.skip("directory symlinks unavailable") - assert supervisor.overlaps(str(project), str(alias)) - assert supervisor.overlaps(str(project), str(alias / "future")) - spelling = tmp_path / "garden" - assert supervisor.overlaps(str(project), str(spelling)) == spelling.exists() - - -def test_usage_report_accepts_distinct_case_projects_and_rejects_aliases(tmp_path): - first, second = tmp_path / "Garden", tmp_path / "garden" - first.mkdir() - if second.exists(): - pytest.skip("volume does not distinguish path case") - second.mkdir() - report = tmp_path / "report.json" - args = ["--project", f"first={first}", "--project", f"second={second}", - "--claude-home", str(tmp_path / "empty-home"), "--start", "2026-01-01T00:00:00Z", - "--end", "2026-01-02T00:00:00Z", "--output", str(report)] - assert usage.main(args) == 0 and report.is_file() - args[3] = f"second={first}" - with pytest.raises(SystemExit): - usage.main(args) diff --git a/tests/integration/mission/test_question_authoring.py b/tests/integration/mission/test_question_authoring.py deleted file mode 100644 index 52b3eee..0000000 --- a/tests/integration/mission/test_question_authoring.py +++ /dev/null @@ -1,255 +0,0 @@ -"""Bounded authoring through normal draft, publish, answer and render entry points.""" - -import copy -import json -import re -import os -import subprocess -import sys - -import pytest - -from chef.questions import records as questions -from chef.questions.authored import render_authored_block -from tests.paths import PLUGIN_ROOT - - -def draft(): - return { - "schema": 2, "id": "confirm-A2", "revision": 1, - "title": "Reading list design", "intro": "Approve the reading list contract.", - "items": [{"id": "storage", "title": "Save reading state?", "body": "Choose the storage scope.", - "status": "pending", "answer": "", "options": [ - {"id": "account", "label": "Account", "description": "Share state.", "impact": "All devices use it."}, - {"id": "device", "label": "Device", "description": "Keep local state."}]}], - "body": "", "blocks": [ - {"id": "rules", "type": "rules", "title": "Validation", "items": [ - {"id": "unique", "label": "Unique ID", "result": "Reject duplicates."}, - {"id": "root", "label": "Root", "when": "Parent is blank", "result": "Create a root."}]}, - {"id": "save", "type": "steps", "title": "Save", "items": [ - {"id": "read", "label": "Read", "text": "Load the list."}, - {"id": "write", "label": "Write", "text": "Save the list.", "failure": "Roll back."}]}, - {"id": "scope", "type": "list", "title": "Scope", "items": [ - {"id": "books", "label": "Books", "text": "Apply to saved books."}]}, - {"id": "book", "type": "fields", "title": "Book", "fields": [ - {"name": "Id", "type": "string", "description": "Stable ID."}]}, - {"id": "cost", "type": "table", "title": "Costs", "columns": ["Action", "Reads"], - "rows": [["Open", "1"]], "row_ids": ["open"]}], - "approval": {"status": "pending", "reason": "Approve the complete contract."}, "answers": [], - } - - -def snapshot(folder): - return {str(path.relative_to(folder)): path.read_bytes() for path in folder.rglob("*") if path.is_file()} - - -def test_structured_input_publishes_and_renders_separate_choices_and_steps(tmp_path): - record = draft() - before = copy.deepcopy(record) - assert questions.preflight_document(tmp_path, record) == record - assert snapshot(tmp_path) == {} - questions.publish_document(tmp_path, record) - text = (tmp_path / "confirm-A2.md").read_text(encoding="utf-8") - assert 'id="rules.unique"' in text and 'id="cost.open"' in text - assert '1. invalid"}, "upsert_entries": [ - {"block": "rules", "entry": {"id": "unique", "label": "Unique", "result": "
invalid
"}}]} - with pytest.raises(questions.QuestionRecordError) as error: - questions.patch_document(record, changes) - assert "intro" in str(error.value) and "blocks[0].items[0].result" in str(error.value) - assert record == draft() - changes["set"]["intro"] = "Revised." - changes["upsert_entries"][0]["entry"]["result"] = "Reject repeated IDs." - patched = questions.patch_document(record, changes) - assert patched["blocks"][0]["items"][1] == record["blocks"][0]["items"][1] - questions.publish_document(tmp_path, patched) - - -@pytest.mark.parametrize("mode", ["all", "any"]) -def test_conditions_exceptions_priority_and_references(mode): - record = draft() - rules = record["blocks"][0] - rules["items"][0]["conditions"] = {"mode": mode, "items": ["First condition", "Second condition"]} - rules["items"][1]["exception_of"] = "rules.unique" - rules["items"][1]["refs"] = ["cost.open", "book.Id"] - rules["priority"] = ["root", "unique"] - text = questions.render_document(record) - assert text.index('id="rules.root"') < text.index('id="rules.unique"') - assert "(#cost.open)" in text and "(#book.Id)" in text - rules["items"][0]["exception_of"] = "rules.root" - with pytest.raises(questions.QuestionRecordError, match="순환"): - questions.validate_document(record) - - -@pytest.mark.parametrize("value", ["missing", "rules.unique", "book.Id", []]) -def test_invalid_exception_target_or_cycle_is_rejected(value): - record = draft() - record["blocks"][0]["items"][0].update(when="Special case", exception_of=value) - with pytest.raises(questions.QuestionRecordError): - questions.validate_document(record) - - -def test_long_user_answer_and_conditional_approval_are_preserved_and_linked(tmp_path): - questions.publish_document(tmp_path, draft()) - raw = "A long answer.\n" * 300 - payload = {"schema": 1, "id": "reply", "revision": 1, "at": "2041-02-08", - "text": raw, "updates": [{"id": "storage", "status": "answered", "answer": raw, "selected": "account"}], - "approval": {"status": "pending", "reason": raw}} - saved = questions.answer_document(tmp_path, "confirm-A2.md", payload) - assert saved["answers"] == [payload] and saved["approval"]["reason"] == raw - text = questions.render_document(saved) - assert raw not in text and "현재 승인 조건 원문" in text and "승인 대기" in text - assert raw in questions.history_path(tmp_path, "confirm-A2.md").read_text(encoding="utf-8") - assert questions.answer_document(tmp_path, "confirm-A2.md", payload) == saved - changed = copy.deepcopy(saved) - changed["revision"] += 1 - changed["approval"]["reason"] = "Changed " + raw - with pytest.raises(questions.QuestionRecordError): - questions.publish_document(tmp_path, changed, 1) - - -def test_legacy_reads_answers_and_explicit_editorial_upgrade_with_history(tmp_path): - legacy = draft() - legacy["schema"] = 1 - legacy["blocks"] = [{"id": "scope", "type": "paragraph", "text": "Old prose. " * 100}] - (tmp_path / "questions").mkdir() - questions.source_path(tmp_path, "confirm-A2.md").write_text(json.dumps(legacy), encoding="utf-8") - questions.render_saved_document(tmp_path, "confirm-A2.md") - assert questions.read_document(tmp_path, "confirm-A2.md") == legacy - upgraded = questions.patch_document(legacy, {"set": {"schema": 2, "revision": 2}, - "upsert_blocks": draft()["blocks"][:3]}, editorial=True) - questions.publish_document(tmp_path, upgraded, 1, editorial=True) - assert json.loads((tmp_path / "questions/history/confirm-A2/1.json").read_text(encoding="utf-8")) == legacy - downgraded = copy.deepcopy(legacy) - downgraded["revision"] = 3 - with pytest.raises(questions.QuestionRecordError, match="되돌릴"): - questions.publish_document(tmp_path, downgraded, 2) - with pytest.raises(questions.QuestionRecordError, match="되돌릴"): - questions.patch_document(upgraded, {"set": {"schema": 1}}) - - -def test_new_confirmations_cannot_use_legacy_schema(tmp_path): - legacy = draft() - legacy["schema"] = 1 - legacy["blocks"] = [{"id": "scope", "type": "paragraph", "text": "Old prose."}] - for operation in (questions.preflight_document, questions.publish_document): - with pytest.raises(questions.QuestionRecordError, match="schema 2"): - operation(tmp_path, legacy) - assert snapshot(tmp_path) == {} - - -def test_initial_document_cannot_forge_answer_evidence_to_bypass_authoring_limits(tmp_path): - record = draft() - raw = "long answer" * 100 - record["approval"] = {"status": "pending", "reason": raw} - record["answers"] = [{"schema": 1, "id": "forged", "revision": 1, "at": "2041-02-08", - "text": raw, "updates": [], "approval": copy.deepcopy(record["approval"])}] - for operation in (questions.preflight_document, questions.publish_document): - with pytest.raises(questions.QuestionRecordError, match="answer"): - operation(tmp_path, record) - assert snapshot(tmp_path) == {} - - -@pytest.mark.parametrize("format,value", [("identifier", "A" * 500), ("formula", "a + b * c"), - ("code", "if (x < 2) {\n return x;\n}"), ("link", "https://example.org/" + "a" * 500)]) -def test_technical_literals_preserve_value_and_escape_markup(format, value): - record = draft() - block = {"id": "literal", "type": "literal", "title": "Reference", "format": format, "value": value} - record["blocks"].append(block) - questions.validate_document(record) - rendered = render_authored_block(block) - assert record["blocks"][-1]["value"] == value - assert "< 2" not in rendered - if format != "link": - assert "pre-wrap" in rendered - - -@pytest.mark.parametrize("value", ["javascript:alert(1)", "//example.org", "https://", "https://example.org/\nnext"]) -def test_unsafe_literal_links_are_rejected(value): - record = draft() - record["blocks"].append({"id": "link", "type": "literal", "title": "Link", "format": "link", "value": value}) - with pytest.raises(questions.QuestionRecordError): - questions.validate_document(record) - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_runtime_cli_previews_the_same_template_and_batch_errors(tmp_path, runtime): - adapter = tmp_path / ".claude/orchestrator" - adapter.mkdir(parents=True) - (adapter / "adapter.json").write_text(json.dumps({"schema": 1, "paths": {"stateDir": "state"}}), encoding="utf-8") - source = tmp_path / "draft.json" - source.write_text(json.dumps(draft()), encoding="utf-8") - environment = dict(os.environ, HAN_ADAPTERS_DIR=str(tmp_path / "no-registry"), PYTHONUTF8="1") - for name in ("CLAUDE_PROJECT_DIR", "CLAUDE_PLUGIN_OPTION_ADAPTERS_DIR", "CLAUDE_CONFIG_DIR", "CODEX_HOME"): - environment.pop(name, None) - script = PLUGIN_ROOT / "skills/mission/scripts/mission_state.py" - if runtime == "codex": - script = PLUGIN_ROOT / "codex/skills/chef-mission/scripts/mission_state.py" - argv = [sys.executable, str(script), "--project", str(tmp_path), "--runtime", runtime, - "--mission", "fictional", "question", "preview", "--input", str(source)] - result = subprocess.run(argv, cwd=tmp_path, env=environment, capture_output=True, encoding="utf-8", timeout=30) - assert result.returncode == 0 and result.stderr == "", result.stderr - assert 'id="rules.unique"' in result.stdout and "All devices use it." in result.stdout - bad = draft() - bad["intro"] = "
invalid
" - bad["blocks"][0]["items"][0]["result"] = "
invalid
" - source.write_text(json.dumps(bad), encoding="utf-8") - result = subprocess.run(argv, cwd=tmp_path, env=environment, capture_output=True, encoding="utf-8", timeout=30) - assert result.stdout == "" and "intro" in result.stderr and "blocks[0].items[0].result" in result.stderr - assert not (tmp_path / "state").exists() - - -def test_field_types_keep_generic_syntax_and_protected_tables_survive_editorial_updates(tmp_path): - record = draft() - record["blocks"][3]["fields"][0]["type"] = "List" - questions.publish_document(tmp_path, record) - assert "List<string>" in questions.render_document(record) - changed = questions.patch_document(record, {"set": {"revision": 2}, "upsert_entries": [ - {"block": "rules", "entry": {"id": "unique", "label": "Unique ID", "result": "Reject duplicate IDs."}}]}, editorial=True) - questions.publish_document(tmp_path, changed, 1, editorial=True) - stale = copy.deepcopy(changed) - stale["revision"] = 3 - before = snapshot(tmp_path) - with pytest.raises(questions.QuestionRecordError, match="expected_revision"): - questions.publish_document(tmp_path, stale, 1) - assert snapshot(tmp_path) == before - stale["blocks"][3]["fields"][0]["type"] = "int" - with pytest.raises(questions.QuestionRecordError, match="editorial"): - questions.publish_document(tmp_path, stale, 2, editorial=True) - assert snapshot(tmp_path) == before - - -@pytest.mark.parametrize("template", ["question.json", "question-structured.json", "design-confirm.json"]) -def test_shipped_templates_are_valid_without_rewriting(template): - source = PLUGIN_ROOT / "skills/mission/references/templates" / template - record = json.loads(source.read_text(encoding="utf-8")) - assert record["schema"] == 2 - assert questions.validate_document(record) == record - assert questions.render_document(record) diff --git a/tests/integration/mission/test_question_blocks.py b/tests/integration/mission/test_question_blocks.py deleted file mode 100644 index 6628a53..0000000 --- a/tests/integration/mission/test_question_blocks.py +++ /dev/null @@ -1,486 +0,0 @@ -from pathlib import Path - -from tests.paths import PLUGIN_ROOT - -"""Guard structured draft publication against wrong answers and partial saves.""" - -import copy -import hashlib -import json -import os -import sys - -import pytest -from chef.questions import records as questions - - -def draft(): - return { - "schema": 1, "id": "ask-palette", "revision": 1, "title": "Palette", "intro": "Choose a palette.", - "items": [{"id": "color", "title": "Color", "body": "Choose one.", "status": "pending", "answer": "", - "options": [{"id": "blue", "label": "Blue", "description": "Cool", "impact": "Low contrast"}, - {"id": "amber", "label": "Amber"}]}], - "body": "", "blocks": [ - {"id": "scope", "type": "paragraph", "text": "A fictional palette."}, - {"id": "values", "type": "table", "title": "Values", "columns": ["Name", "Note"], "rows": [["A|B", "line 1\nline 2"]]}, - {"id": "palette", "type": "fields", "fields": [{"name": "Id", "type": "string", "key": "primary"}, - {"name": "Parent", "type": "string", "ref": "palette.Id", "description": "Optional"}]}, - ], "detail_blocks": [{"id": "evidence", "type": "paragraph", "text": "Fictional display measurements."}], - "approval": {"status": "none", "reason": ""}, "answers": [], - } - - -def reply(selected="blue"): - update = {"id": "color", "status": "answered", "answer": "Use the cool palette."} - if selected is not None: - update["selected"] = selected - return {"schema": 1, "id": "reply-color", "revision": 1, "at": "2041-02-08", "text": "Blue, please.\nKeep this exact text.", "updates": [update]} - - -def files(folder): - return {str(path.relative_to(folder)): path.read_bytes() for path in folder.rglob("*") if path.is_file()} - - -def test_structured_blocks_and_explicit_selected_render_without_body_rewriting(tmp_path): - original = questions.publish_document(tmp_path, draft()) - current = (tmp_path / "ask-palette.md").read_text(encoding="utf-8") - assert "| A\\|B | line 1
line 2 |" in current - assert "| Parent | string | | palette.Id | Optional |" in current - assert "### 1. Color" in current - assert "- Blue \n 설명 · Cool \n 영향 · Low contrast" in current - assert "- Amber" in current - assert "| id | 선택 |" not in current - saved = questions.answer_document(tmp_path, "ask-palette.md", reply()) - rendered = questions.render_document(saved) - assert "## 현재 선택\n\n### Color\n\n- Blue \n 설명 · Cool \n 영향 · Low contrast" in rendered - assert "| 문항 | 선택 id |" not in rendered - assert "amber" not in rendered and saved["blocks"] == original["blocks"] and saved["body"] == "" - assert reply()["text"] not in rendered and saved["answers"] == [reply()] - assert reply()["text"] in (tmp_path / "details/history/ask-palette.md").read_text(encoding="utf-8") - assert not questions.inspect_document(tmp_path, "ask-palette.md", rendered)[1] - - -def test_current_render_elides_exact_option_repeat_and_retains_distinct_context(): - record = draft() - item = record["items"][0] - item["options"][0].update(label="권장: Blue", description="Cool\ncolor", impact="Cool color") - item["body"] = "- 권장: Blue — Cool color\n\nUse the alternate palette outdoors." - current = questions.render_document(record) - assert current.count("- 권장: Blue — Cool color") == 1 - assert "Use the alternate palette outdoors." in current - assert "- Amber" in current - assert "본문과 options" in questions.decision_review_notes(record)[0] - - -def test_existing_option_table_is_valid_until_current_document_is_regenerated(tmp_path): - questions.publish_document(tmp_path, draft()) - record = questions.answer_document(tmp_path, "ask-palette.md", reply()) - name = "ask-palette.md" - original = files(tmp_path) - old = questions.render_document(record, tabular_choices=True) - assert "| Color | blue | Blue | Cool | Low contrast |" in old - (tmp_path / name).write_bytes(old.encode("utf-8")) - assert not questions.inspect_document(tmp_path, name, old)[1] - assert questions.inspect_document(tmp_path, name, old.replace("Low contrast", "High contrast"))[1] - questions.render_saved_document(tmp_path, name) - assert files(tmp_path) == original - - -@pytest.mark.parametrize("change", [ - lambda d: d.update(body="Duplicated contract"), - lambda d: d.update(blocks={}), - lambda d: d["blocks"][0].update(type="script"), - lambda d: d["blocks"][0].update(path="outside.md"), - lambda d: d["blocks"][0].update(id="../outside"), - lambda d: d["detail_blocks"][0].update(id="scope"), - lambda d: d["blocks"][1].update(rows=[["wrong width"]]), - lambda d: d["blocks"][1].update(rows=[["Name", 42]]), - lambda d: d["blocks"][2]["fields"][1].update(ref="missing.Id"), - lambda d: d["blocks"][2]["fields"][1].update(name="Id"), - lambda d: d["items"][0]["options"][1].update(id="blue"), - lambda d: d["items"][0]["options"][0].update(label=1), - lambda d: d["items"][0]["options"][0].update(unknown="hidden"), - lambda d: d["items"][0].update(selected="blue"), - lambda d: d["items"][0].update(status="answered", answer="Chosen", selected="missing"), -]) -def test_invalid_structured_values_never_create_records(tmp_path, change): - record = draft() - change(record) - with pytest.raises(questions.QuestionRecordError): - questions.publish_document(tmp_path, record) - assert files(tmp_path) == {} - - -def test_invalid_selection_is_rejected_and_free_answers_never_infer_it(tmp_path): - questions.publish_document(tmp_path, draft()) - before = files(tmp_path) - for payload in (reply("missing"), {**reply(), "updates": [{**reply()["updates"][0], "status": "withdrawn"}]}): - with pytest.raises(questions.QuestionRecordError): - questions.answer_document(tmp_path, "ask-palette.md", payload) - assert files(tmp_path) == before - saved = questions.answer_document(tmp_path, "ask-palette.md", reply(None)) - assert "selected" not in saved["items"][0] and "## 현재 선택" not in questions.render_document(saved) - - -def test_initial_publication_cannot_install_selected_without_an_answer_operation(tmp_path): - record = draft() - record["items"][0].update(status="answered", answer="Preselected", selected="blue") - for operation in (questions.preflight_document, questions.publish_document): - with pytest.raises(questions.QuestionRecordError, match="selected.*answer"): - operation(tmp_path, record) - assert list(tmp_path.iterdir()) == [] - record["items"][0].pop("selected") - saved = questions.publish_document(tmp_path, record) - assert saved["items"][0]["status"] == "answered" and saved["answers"] == [] - selected = questions.answer_document(tmp_path, "ask-palette.md", reply()) - before = files(tmp_path) - assert questions.preflight_document(tmp_path, selected) == selected - assert questions.publish_document(tmp_path, selected) == selected - assert questions.answer_document(tmp_path, "ask-palette.md", reply()) == selected - assert files(tmp_path) == before and selected["items"][0]["selected"] == "blue" - - -@pytest.mark.parametrize("field", ["title", "options"]) -def test_changed_withdrawn_definition_requires_explicit_reopen_and_keeps_history(tmp_path, field): - questions.publish_document(tmp_path, draft()) - payload = reply(None) - payload["updates"][0].update(status="withdrawn", answer="Exclude the original color choice.") - saved = questions.answer_document(tmp_path, "ask-palette.md", payload) - definition = copy.deepcopy({key: value for key, value in saved["items"][0].items() if key not in ("status", "answer")}) - if field == "title": - definition["title"] = "New color decision" - else: - definition["options"][0]["label"] = "New meaning" - changes = {"set": {"revision": 2}, "upsert_items": [definition]} - with pytest.raises(questions.QuestionRecordError, match="reopen_items"): - questions.patch_document(saved, changes) - changed = copy.deepcopy(saved) - changed["revision"] = 2 - changed["items"][0].update(definition) - before = files(tmp_path) - for operation in (questions.preflight_document, questions.publish_document): - with pytest.raises(questions.QuestionRecordError, match="pending.*answer"): - operation(tmp_path, changed, 1) - assert files(tmp_path) == before - changes["reopen_items"] = ["color"] - reopened = questions.patch_document(saved, changes) - questions.publish_document(tmp_path, reopened, 1) - assert reopened["items"][0]["status"] == "pending" and reopened["items"][0]["answer"] == "" - assert "selected" not in reopened["items"][0] and reopened["answers"] == [payload] - assert questions.summarize_document(reopened).pending - - -@pytest.mark.parametrize("outcome", ["withdrawn", "selected"]) -def test_revision_cannot_hide_answer_changes_behind_an_item_definition_edit(tmp_path, outcome): - questions.publish_document(tmp_path, draft()) - payload = reply() - if outcome == "withdrawn": - payload = reply(None) - payload["updates"][0].update(status="withdrawn", answer="Original withdrawal.") - saved = questions.answer_document(tmp_path, "ask-palette.md", payload) - changed = copy.deepcopy(saved) - changed["revision"] = 2 - changed["items"][0]["title"] = "Different decision" - if outcome == "withdrawn": - changed["items"][0]["answer"] = "Different withdrawal." - else: - changed["items"][0]["selected"] = "amber" - before = files(tmp_path) - for operation in (questions.preflight_document, questions.publish_document): - with pytest.raises(questions.QuestionRecordError, match="pending.*answer"): - operation(tmp_path, changed, 1) - assert files(tmp_path) == before - - -@pytest.mark.parametrize("field", ["title", "options"]) -def test_pending_definition_patch_requires_explicit_reopen_without_mutating_inputs(field): - record = draft() - definition = copy.deepcopy({key: value for key, value in record["items"][0].items() if key not in ("status", "answer")}) - if field == "title": - definition["title"] = "New pending question" - else: - definition["options"][0]["label"] = "New pending option" - changes = {"upsert_items": [definition]} - original = copy.deepcopy(record) - original_changes = copy.deepcopy(changes) - with pytest.raises(questions.QuestionRecordError, match="reopen_items"): - questions.patch_document(record, changes) - assert record == original and changes == original_changes - changes["reopen_items"] = ["color"] - explicit_changes = copy.deepcopy(changes) - patched = questions.patch_document(record, changes) - assert record == original and changes == explicit_changes - assert patched["items"][0] == {**definition, "status": "pending", "answer": ""} - - -@pytest.mark.parametrize("new_item", [False, True]) -def test_same_definition_upsert_and_new_item_do_not_require_reopen(new_item): - record = draft() - original = copy.deepcopy(record) - definition = copy.deepcopy({key: value for key, value in record["items"][0].items() if key not in ("status", "answer")}) - if new_item: - definition["id"] = "new-color" - changes = {"upsert_items": [definition]} - original_changes = copy.deepcopy(changes) - patched = questions.patch_document(record, changes) - assert record == original and changes == original_changes - if new_item: - assert len(patched["items"]) == 2 and patched["items"][-1] == {**definition, "status": "pending", "answer": ""} - else: - assert patched == record - - -def test_patch_editorial_keeps_selected_and_reopen_requires_explicit_operation(tmp_path): - questions.publish_document(tmp_path, draft()) - saved = questions.answer_document(tmp_path, "ask-palette.md", reply()) - definition = copy.deepcopy({key: value for key, value in saved["items"][0].items() if key not in ("status", "answer", "selected")}) - definition["body"] = "Choose a color." - changes = {"set": {"revision": 2}, "upsert_items": [definition]} - original = copy.deepcopy(saved) - original_changes = copy.deepcopy(changes) - with pytest.raises(questions.QuestionRecordError, match="reopen_items"): - questions.patch_document(saved, changes) - patched = questions.patch_document(saved, changes, editorial=True) - assert saved == original and changes == original_changes - assert patched["items"][0]["selected"] == "blue" and patched["answers"] == saved["answers"] - with pytest.raises(questions.QuestionRecordError, match="pending"): - questions.preflight_document(tmp_path, patched, 1) - questions.publish_document(tmp_path, patched, 1, editorial=True) - definition["options"][0]["label"] = "Different meaning" - with pytest.raises(questions.QuestionRecordError, match="options"): - questions.patch_document(patched, {"set": {"revision": 3}, "upsert_items": [definition]}, editorial=True) - reopened = questions.patch_document(patched, {"set": {"revision": 3}, "upsert_items": [definition], "reopen_items": ["color"]}) - assert reopened["items"][0]["status"] == "pending" and reopened["items"][0]["answer"] == "" - assert "selected" not in reopened["items"][0] and reopened["answers"] == saved["answers"] - questions.publish_document(tmp_path, reopened, 2) - assert questions.read_document(tmp_path, "ask-palette.md")["answers"] == [reply()] - - -@pytest.mark.parametrize("operation", ["options", "reopen", "new-item", "remove-item", "state", "approval", "table"]) -def test_editorial_patch_reuses_publication_protections_and_keeps_failed_inputs(tmp_path, operation): - questions.publish_document(tmp_path, draft()) - saved = questions.answer_document(tmp_path, "ask-palette.md", reply()) - definition = copy.deepcopy({key: value for key, value in saved["items"][0].items() if key not in ("status", "answer", "selected")}) - if operation == "options": - definition["options"][0]["label"] = "Different meaning" - changes = {"upsert_items": [definition]} - elif operation == "reopen": - changes = {"reopen_items": ["color"]} - elif operation == "new-item": - definition["id"] = "new-color" - changes = {"upsert_items": [definition]} - elif operation == "remove-item": - changes = {"remove_items": ["color"]} - elif operation == "state": - definition["status"] = "pending" - changes = {"upsert_items": [definition]} - elif operation == "approval": - changes = {"request_approval": {"reason": "A new approval request."}} - else: - changes = {"upsert_blocks": [{"id": "values", "type": "table", "columns": ["Value"], "rows": [["Changed contract"]]}]} - original = copy.deepcopy(saved) - original_changes = copy.deepcopy(changes) - before_files = files(tmp_path) - with pytest.raises(questions.QuestionRecordError): - questions.patch_document(saved, changes, editorial=True) - assert saved == original and changes == original_changes and files(tmp_path) == before_files - - -@pytest.mark.parametrize("changes", [ - {"set": {"answers": []}}, {"set": {"approval": {"status": "complete", "reason": ""}}}, - {"set": {"id": "ask-other"}}, {"set": {"legacy_markdown": "overwrite"}}, - {"upsert_items": [{"id": "color", "title": "Color", "body": "", "status": "answered", "answer": "Changed"}]}, - {"upsert_items": [{"id": "color", "title": "Color", "body": "", "selected": "amber"}]}, - {"request_approval": {"reason": "", "status": "complete"}}, {"request_approval": {"reason": ""}}, - {"remove_blocks": ["missing"]}, {"reopen_items": ["missing"]}, - {"upsert_blocks": [{"id": "scope", "type": "paragraph", "text": "Changed"}], "remove_blocks": ["scope"]}, -]) -def test_patch_cannot_bypass_protected_fields_or_execute_unknown_operations(changes): - record = draft() - before = copy.deepcopy(record) - with pytest.raises(questions.QuestionRecordError): - questions.patch_document(record, changes) - assert record == before - - -def test_patch_uses_explicit_revision_and_request_approval_without_mutating_input(tmp_path): - questions.publish_document(tmp_path, draft()) - saved = questions.answer_document(tmp_path, "ask-palette.md", reply()) - changes = {"set": {"revision": 2}, "upsert_blocks": [{"id": "scope", "type": "paragraph", "text": "A larger scope."}]} - patched = questions.patch_document(saved, changes) - with pytest.raises(questions.QuestionRecordError, match="approval"): - questions.preflight_document(tmp_path, patched, 1) - changes["request_approval"] = {"reason": "Confirm the larger scope separately."} - requested = questions.patch_document(saved, changes) - assert requested["approval"] == {"status": "pending", "reason": changes["request_approval"]["reason"]} - assert saved["revision"] == 1 and saved["approval"]["status"] == "none" - assert questions.patch_document(saved, {}) == saved - assert questions.preflight_document(tmp_path, requested, 1) == requested - assert requested["answers"] == saved["answers"] - - -@pytest.mark.parametrize("field", ["blocks", "detail_blocks"]) -def test_structured_table_changes_cannot_use_editorial_to_keep_old_approval(tmp_path, field): - record = draft() - record[field].append({"id": "contract", "type": "table", "columns": ["Value"], "rows": [["before"]]}) - questions.publish_document(tmp_path, record) - saved = questions.answer_document(tmp_path, "ask-palette.md", reply()) - revised = copy.deepcopy(saved) - revised["revision"] = 2 - revised[field][-1]["rows"] = [["after"]] - for editorial, message in ((True, "table/fields"), (False, "approval")): - with pytest.raises(questions.QuestionRecordError, match=message): - questions.preflight_document(tmp_path, revised, 1, editorial=editorial) - revised["approval"] = {"status": "pending", "reason": "Confirm changed value."} - questions.publish_document(tmp_path, revised, 1) - - -def test_changed_option_id_requires_reopen_and_old_selected_remains_only_in_history(tmp_path): - questions.publish_document(tmp_path, draft()) - saved = questions.answer_document(tmp_path, "ask-palette.md", reply()) - definition = copy.deepcopy({key: value for key, value in saved["items"][0].items() if key not in ("status", "answer", "selected")}) - definition["options"][0]["id"] = "green" - changes = {"set": {"revision": 2}, "upsert_items": [definition]} - with pytest.raises(questions.QuestionRecordError, match="reopen_items"): - questions.patch_document(saved, changes) - changes["reopen_items"] = ["color"] - reopened = questions.patch_document(saved, changes) - questions.publish_document(tmp_path, reopened, 1) - assert reopened["answers"][0]["updates"][0]["selected"] == "blue" - assert "selected" not in reopened["items"][0] - - -def test_preflight_matches_publish_validation_without_any_writes(tmp_path): - record = draft() - before = files(tmp_path) - assert questions.preflight_document(tmp_path, record) == record - assert list(tmp_path.iterdir()) == [] and files(tmp_path) == before - questions.publish_document(tmp_path, record) - revised = questions.patch_document(record, {"set": {"revision": 2, "title": "Palette wording"}}) - before = {str(p): (p.read_bytes(), p.stat().st_mtime_ns) for p in tmp_path.rglob("*") if p.is_file()} - assert questions.preflight_document(tmp_path, revised, 1, editorial=True) == revised - for operation in (questions.preflight_document, questions.publish_document): - with pytest.raises(questions.QuestionRecordError, match="expected_revision"): - operation(tmp_path, revised, 99, editorial=True) - assert before == {str(p): (p.read_bytes(), p.stat().st_mtime_ns) for p in tmp_path.rglob("*") if p.is_file()} - questions.publish_document(tmp_path, revised, 1, editorial=True) - - -def test_render_and_identical_republish_preserve_original_json_bytes(tmp_path): - saved = questions.publish_document(tmp_path, draft()) - source = tmp_path / "questions/ask-palette.json" - original = b"\xef\xbb\xbf" + json.dumps(saved, ensure_ascii=False).encode("utf-8") + b"\r\n" - source.write_bytes(original) - questions.render_saved_document(tmp_path, "ask-palette.md") - questions.publish_document(tmp_path, saved) - assert source.read_bytes() == original - - -@pytest.mark.parametrize("content", ["Handwritten detail", "\nForged ownership"]) -def test_manual_detail_never_overwritten_even_with_generated_marker(tmp_path, content): - detail = tmp_path / "details/ask-palette.md" - detail.parent.mkdir() - detail.write_text(content, encoding="utf-8") - before = files(tmp_path) - for operation in (questions.preflight_document, questions.publish_document): - with pytest.raises(questions.QuestionRecordError, match="수동 상세"): - operation(tmp_path, draft()) - assert files(tmp_path) == before - - -def test_edited_generated_detail_requires_manual_resolution_and_missing_detail_can_regenerate(tmp_path): - saved = questions.publish_document(tmp_path, draft()) - detail = tmp_path / "details/ask-palette.md" - detail.write_text(detail.read_text(encoding="utf-8") + "Manual note", encoding="utf-8") - before = files(tmp_path) - assert questions.inspect_document(tmp_path, "ask-palette.md", questions.render_document(saved))[1] - with pytest.raises(questions.QuestionRecordError, match="수동 상세"): - questions.render_saved_document(tmp_path, "ask-palette.md") - assert files(tmp_path) == before - detail.unlink() - questions.render_saved_document(tmp_path, "ask-palette.md") - assert detail.read_bytes() == questions.render_detail_document(saved).encode("utf-8") - - -def test_detail_failure_rolls_back_revision_snapshot_json_current_and_history(tmp_path, monkeypatch): - saved = questions.publish_document(tmp_path, draft()) - revised = questions.patch_document(saved, {"set": {"revision": 2, "title": "New title"}, - "upsert_detail_blocks": [{"id": "evidence", "type": "paragraph", "text": "New detail"}]}) - before = files(tmp_path) - original = questions.write_text - - def fail_detail(path, value): - if path == tmp_path / "details/ask-palette.md": - original(path, value) - raise OSError("detail storage unavailable") - original(path, value) - - monkeypatch.setattr(questions, "write_text", fail_detail) - with pytest.raises(questions.QuestionRecordError, match="detail storage"): - questions.publish_document(tmp_path, revised, 1, editorial=True) - assert files(tmp_path) == before - assert not (tmp_path / "questions/history/ask-palette/1.json").exists() - - -def test_removing_owned_details_is_transactional_and_leaves_manual_detail_alone(tmp_path): - saved = questions.publish_document(tmp_path, draft()) - revised = questions.patch_document(saved, {"set": {"revision": 2}, "remove_detail_blocks": ["evidence"]}) - questions.publish_document(tmp_path, revised, 1, editorial=True) - assert not (tmp_path / "details/ask-palette.md").exists() - assert "Fictional display measurements" in (tmp_path / "details/history/ask-palette.md").read_text(encoding="utf-8") - - -def test_transaction_preserves_external_change_and_reports_rollback_gap(tmp_path, monkeypatch): - saved = questions.publish_document(tmp_path, draft()) - revised = questions.patch_document(saved, {"set": {"revision": 2, "title": "New title"}}) - original = questions.write_text - source = tmp_path / "questions/ask-palette.json" - - def external_edit(path, value): - if path == tmp_path / "ask-palette.md": - source.write_text("External change", encoding="utf-8") - raise OSError("current document unavailable") - original(path, value) - - monkeypatch.setattr(questions, "write_text", external_edit) - with pytest.raises(questions.QuestionRecordError, match="롤백 확인 필요"): - questions.publish_document(tmp_path, revised, 1, editorial=True) - assert source.read_text(encoding="utf-8") == "External change" - - -@pytest.mark.parametrize("fail_detail", [False, True]) -def test_restore_tracks_explicit_selection_and_generated_detail_in_same_rollback(tmp_path, monkeypatch, fail_detail): - saved = questions.publish_document(tmp_path, draft()) - reviewed = copy.deepcopy(saved) - reviewed["items"][0].update(status="answered", answer=reply()["updates"][0]["answer"], selected="blue") - reviewed["answers"] = [reply()] - reviewed["detail_blocks"][0]["text"] = "Recovered evidence." - source = tmp_path / "questions/ask-palette.json" - current = tmp_path / "ask-palette.md" - current.write_text(current.read_text(encoding="utf-8") + "\n" + reply()["text"], encoding="utf-8") - evidence = tmp_path / "evidence.md" - evidence.write_bytes(current.read_bytes()) - recovery_input = tmp_path / "reviewed.json" - recovery_input.write_text(json.dumps(reviewed), encoding="utf-8") - before = files(tmp_path) - expected_hash = hashlib.sha256(source.read_bytes()).hexdigest() - if fail_detail: - original = questions.write_bytes - original_detail = (tmp_path / "details/ask-palette.md").read_bytes() - - def fail(path, value): - if path == tmp_path / "details/ask-palette.md" and value != original_detail: - raise OSError("detail write interrupted") - original(path, value) - - monkeypatch.setattr(questions, "write_bytes", fail) - with pytest.raises(questions.QuestionRecordError, match="detail write"): - questions.restore_document(tmp_path, recovery_input, evidence, 1, expected_hash) - assert all((tmp_path / name).read_bytes() == value for name, value in before.items()) - else: - assert questions.restore_document(tmp_path, recovery_input, evidence, 1, expected_hash) == reviewed - assert not questions.inspect_document(tmp_path, "ask-palette.md", questions.render_document(reviewed))[1] - receipt, = (tmp_path / "questions/history/ask-palette/recovery").glob("*/receipt.json") - saved_receipt = questions.read_json(receipt) - assert saved_receipt["status"] == ("rolled_back" if fail_detail else "complete") - assert saved_receipt["before_detail_existed"] and "after-detail.md" in saved_receipt["sha256"] diff --git a/tests/integration/mission/test_question_readability.py b/tests/integration/mission/test_question_readability.py deleted file mode 100644 index 9cb6066..0000000 --- a/tests/integration/mission/test_question_readability.py +++ /dev/null @@ -1,628 +0,0 @@ -"""Readable authoring preserves exact decisions and publication safety.""" - -import copy -import json -from types import SimpleNamespace - -import pytest - -from chef.cli import question_commands as cli -from chef.questions import readability, records -from chef.questions.check import check -from tests.integration.mission.test_question_authoring import draft - - -def codes(record): - return {note['code'] for note in readability.analyze(record)} - - -def test_long_prose_is_advisory_and_preview_patch_stdout_remain_parseable(tmp_path, capsys): - record = draft() - record['intro'] = 'A deliberately detailed explanation ' * 12 - source = tmp_path / 'draft.json' - source.write_text(json.dumps(record), encoding='utf-8') - changes = tmp_path / 'changes.json' - changes.write_text('{"set": {"revision": 2}}', encoding='utf-8') - before = copy.deepcopy(record) - assert 'long_item' in codes(record) - assert records.validate_document(record) == before - assert cli.cmd_question_preview(None, SimpleNamespace(input=source))[0].startswith('# ') - assert 'long_item' in capsys.readouterr().err - result = cli.cmd_question_patch(None, SimpleNamespace(input=source, changes=changes, editorial=False)) - assert json.loads(result[0])['revision'] == 2 - assert 'long_sentence' in capsys.readouterr().err - assert record == before - assert records.preflight_document(tmp_path, record) == record - records.publish_document(tmp_path, record) - result = check(tmp_path / 'confirm-A2.md', tmp_path / 'questions/confirm-A2.json') - assert not result['issues'] and result['readability'] - - -def test_condition_array_is_included_in_the_entry_measurement(): - record = draft() - entry = record['blocks'][0]['items'][0] - entry['conditions'] = {'mode': 'all', 'items': [f'Condition {i}: ' + 'x' * 140 for i in range(12)]} - records.validate_document(record) - notes = readability.analyze(record) - assert any(n['code'] == 'long_item' and n['location'] == 'blocks.rules.unique' and n['characters'] > 1600 for n in notes) - - -@pytest.mark.parametrize('split', [False, True]) -def test_short_items_cannot_hide_document_density_by_splitting_blocks(split): - record = draft() - entries = [{'id': f'n{i}', 'label': f'Note {i}', 'text': f'Explanation {i} uses its own saved value and performs the documented action.'} for i in range(100)] - if split: - record['blocks'] = [{'id': f'b{i}', 'title': f'Part {i}', 'type': 'list', 'items': [entry]} for i, entry in enumerate(entries)] - else: - record['blocks'] = [{'id': 'notes', 'title': 'Notes', 'type': 'list', 'items': entries}] - records.validate_document(record) - assert 'dense_document' in codes(record) - assert ('dense_list' in codes(record)) == (not split) - - -def test_large_fields_code_and_technical_spans_do_not_trigger_prose_limits(): - record = draft() - record['blocks'] = [ - {'id': 'fields', 'type': 'fields', 'title': 'Fields', 'fields': [{'name': f'Field{i}', 'type': 'int', 'description': f'Saved value {i}.'} for i in range(100)]}, - {'id': 'code', 'type': 'literal', 'title': 'Code', 'format': 'code', 'value': 'value = 1\n' * 600}, - ] - assert not codes(record) - assert not readability.analyze_markdown('````text\n' + 'text ' * 1000 + '\n````\n| Field | Type |\n| A | int |') - assert not readability.analyze_markdown('Use `' + 'namespace.' * 100 + 'Type` here. Visit https://example.org/' + 'path/' * 100) - - -def test_prose_in_a_table_cell_is_still_diagnosed(): - record = draft() - record['blocks'][-1]['rows'][0][0] = 'A long explanation ' * 40 - assert 'long_item' in codes(record) - - -def test_exact_duplicates_keep_numbers_negation_and_identifier_distinctions(): - common = 'The saved selection remains available after the current document is closed.' - text = f'## First\n\n{common}\n\n## Second\n\n{common}\n\nThe amount is 100 and the result must not be applied.\n\nThe amount is 200 and the result must be applied.' - notes = readability.analyze_markdown(text) - repeated = [n for n in notes if n['code'] == 'duplicate_sentence'] - assert len(repeated) == 1 and len(repeated[0]['locations']) == 2 - assert repeated[0]['text'] == common - assert not any(n['code'] == 'duplicate_sentence' for n in readability.analyze_markdown('The `' + 'FirstType' + '` value must remain available after saving.\n\nThe `SecondType` value must remain available after saving.')) - - -def test_paragraph_is_joined_without_bullets_or_required_heading_and_keeps_anchor(): - record = draft() - record['blocks'].insert(0, {'id': 'context', 'type': 'paragraph', 'sentences': ['First sentence.', 'Second sentence.']}) - text = records.render_document(record) - assert '
\n\nFirst sentence. Second sentence.' in text - assert '- First sentence' not in text - broken = copy.deepcopy(record) - broken['blocks'][0]['sentences'][0] = '' - with pytest.raises(records.QuestionRecordError): - records.validate_document(broken) - - -def test_opt_in_decision_view_keeps_answers_in_history_and_current_contract_inline(tmp_path): - record = draft() - records.publish_document(tmp_path, record) - answer = {'schema': 1, 'id': 'reply', 'revision': 1, 'at': '2041-02-08', 'text': 'Use the account option.', 'updates': [{'id': 'storage', 'status': 'answered', 'answer': 'Use the account option.', 'selected': 'account'}], 'approval': {'status': 'complete', 'reason': 'Approved.'}} - current = records.answer_document(tmp_path, 'confirm-A2.md', answer) - assert '## 현재 선택' in records.render_document(current) - changed = records.patch_document(current, {'set': {'revision': 2, 'presentation': 'decision'}}, editorial=True) - records.publish_document(tmp_path, changed, 1, editorial=True) - text = (tmp_path / 'confirm-A2.md').read_text(encoding='utf-8') - assert '## 현재 선택' not in text and 'Stable ID.' in text - assert 'bold and inline Markdown
" in rendered_html - assert "
\n 설명 · Use 3.14" in rendered_html - - saved = publish_document(tmp_path, record) - archive = question_records.history_path(tmp_path, "ask-1.md").read_text(encoding="utf-8") - assert "Use 3.14 in `config.v2.json`. Then open [the guide. Continue here]" in archive - assert " \n" not in archive - assert saved == before - - -def test_schema1_selected_choice_uses_separate_fields_while_legacy_layouts_stay_tabular(): - record = document() - record["items"][0].update( - status="answered", - answer="Use the detailed choice.", - options=[ - { - "id": "detailed", - "label": "Detailed **choice**", - "description": "A selected description with `Markdown`.", - "impact": "A selected impact.", - } - ], - selected="detailed", - ) - record["items"][1]["options"] = [ - {"id": "plain", "label": "A plain option", "description": "A description."} - ] - - text = render_document(record) - assert "## 현재 선택\n\n### 제출할까요?\n\n- Detailed **choice** \n 설명 · A selected description with `Markdown`. \n 영향 · A selected impact." in text - assert "| id | 선택 | 설명 | 영향 |" in render_document(record, legacy_layout=True) - assert "| id | 선택 | 설명 | 영향 |" in render_document(record, tabular_choices=True) - assert "| 문항 | 선택 id | 현재 선택 | 설명 | 영향 |" in render_document(record, legacy_layout=True) - - -def test_schema1_legacy_choice_keeps_raw_markup_literal_and_markdown_active(): - choice = question_records.render_legacy_choice( - { - "id": "literal", - "label": " **bold**", - "description": "Show and © while keeping `code` and [a link](https://example.org/?a=1&b=2).", - } - ) - - assert "- <default> **bold**" in choice - assert "<token> and &copy;" in choice - assert "`code` and [a link](https://example.org/?a=1&b=2)" in choice - if importlib.util.find_spec("markdown") is not None: - import markdown - - rendered_html = markdown.markdown(choice) - assert "<default> bold" in rendered_html - assert "<token> and &copy;" in rendered_html - assert 'code and a link' in rendered_html - - -def test_long_schema1_choice_wrapping_avoids_markdown_blocks_and_respects_escaped_backticks(): - prose = ( - r"An escaped \` marker. Then `code. Keep literal` safely. First sentence. # Required heading. " - "Second sentence. 1. Keep ordered text. " - "Additional generic prose keeps this explanation long enough to exercise sentence wrapping safely." - ) - - formatted = question_records._format_legacy_choice_prose(prose) - - assert r"An escaped \` marker." in formatted - assert "Then `code. Keep literal` safely." in formatted - assert "First sentence. # Required heading." in formatted - assert "Second sentence. 1. Keep ordered text." in formatted - assert "`code. Keep literal`" in formatted - assert ". \n # Required" not in formatted - assert ". \n 1. Keep" not in formatted - - escaped_close = ( - r"Use `path\` then `code. Keep literal` after that. " - "Additional generic prose keeps the explanation long enough to exercise safe wrapping." - ) - escaped_close_formatted = question_records._format_legacy_choice_prose(escaped_close) - assert r"`path\` then `code. Keep literal`" in escaped_close_formatted - assert "code. \n Keep" not in escaped_close_formatted - if importlib.util.find_spec("markdown") is not None: - import markdown - - rendered_html = markdown.markdown(question_records.render_legacy_choice({"label": "Choice", "description": prose})) - assert "

Required heading

" not in rendered_html - assert "
    " not in rendered_html - assert "# Required heading" in rendered_html and "1. Keep ordered text." in rendered_html - - -def test_baseline_schema1_prose_markdown_still_checks_and_answers(tmp_path): - record = document() - record["items"][0]["options"] = [ - {"id": "preferred", "label": "Preferred", "description": "A clear choice."}, - {"id": "alternate", "label": "Alternate", "impact": "A different result."}, - ] - record["items"][1]["options"] = [ - {"id": "selected", "label": "Selected", "description": "Already chosen."} - ] - publish_document(tmp_path, record) - saved = answer_document( - tmp_path, - "ask-1.md", - answer(updates=[{"id": "2", "status": "answered", "answer": "Keep the existing selection.", "selected": "selected"}]), - ) - baseline_markdown = question_records._render_document(saved, legacy_prose_choices=True) - assert "- Preferred — A clear choice." in baseline_markdown - assert "- 후속 작업할까요? · Selected — Already chosen." in baseline_markdown - (tmp_path / "ask-1.md").write_text(baseline_markdown, encoding="utf-8") - - assert question_records.checked_document(tmp_path, "ask-1.md", baseline_markdown) == saved - answered = answer_document( - tmp_path, - "ask-1.md", - answer("reply-2", updates=[{"id": "1", "status": "answered", "answer": "Preferred."}]), - ) - - assert read_document(tmp_path, "ask-1.md") == answered - assert (tmp_path / "ask-1.md").read_text(encoding="utf-8") == render_document(answered) - assert "- Selected" in render_document(answered) - - -def test_current_view_keeps_pending_options_and_current_design_before_completed_results(tmp_path): - record = document() - record["items"][0].update(status="answered", answer="Keep the blue border.") - record["items"][0]["body"] = "Past choices: blue or green." - record["items"][1]["body"] = "Pending choices: circle or square." - record["body"] = "## Current contract\n\n| 필드 | 타입 |\n| --- | --- |\n| Shape | string |" - record["legacy_markdown"] = "# Original palette\r\n" - publish_document(tmp_path, record) - current = render_document(record) - assert "Past choices" not in current and record["legacy_markdown"] not in current - assert current.index(record["intro"]) < current.index("Pending choices") < current.index(record["body"]) < current.index("## 전체 이력") - assert "Keep the blue border." not in current and "## 현재 결과" not in current - assert "details/history/ask-1.md" in current - archive = question_records.history_path(tmp_path, "ask-1.md").read_bytes().decode("utf-8") - assert "Past choices: blue or green." in archive and record["legacy_markdown"] in archive - assert question_records.validate_history_archive(question_records.history_path(tmp_path, "ask-1.md"), record) - - -def test_history_deduplicates_raw_answers_and_legacy_while_linking_each_revision(tmp_path): - record = document() - record["legacy_markdown"] = "# Original fictional palette\r\nExact legacy text.\r\n" - publish_document(tmp_path, record) - saved = answer_document(tmp_path, "ask-1.md", answer(updates=[{"id": "1", "status": "answered", "answer": "Blue."}])) - revised = copy.deepcopy(saved) - revised.update(revision=2, title="Reworded palette") - publish_document(tmp_path, revised, 1, editorial=True) - archive = question_records.history_path(tmp_path, "ask-1.md").read_bytes().decode("utf-8") - assert archive.count(record["legacy_markdown"]) == 1 - assert archive.count(saved["answers"][0]["text"]) == 1 - assert archive.count("이 개정의 답 기록: `reply-1` (대상 개정 1)") == 2 - assert "## 개정 1" in archive and "## 개정 2" in archive - - -def test_history_revisions_are_ordered_by_number_instead_of_filename(tmp_path): - record = document() - record["revision"] = 2 - publish_document(tmp_path, record) - later = copy.deepcopy(record) - later.update(revision=10, title="Tenth fictional revision") - publish_document(tmp_path, later, 2, editorial=True) - current = copy.deepcopy(later) - current.update(revision=11, title="Eleventh fictional revision") - publish_document(tmp_path, current, 10, editorial=True) - assert [snapshot["revision"] for snapshot in question_records.history_records(tmp_path, current)] == [2, 10, 11] - archive = question_records.render_history_document(tmp_path, current) - assert archive.index("## 개정 2") < archive.index("## 개정 10") < archive.index("## 개정 11") - - -def test_completed_and_withdrawn_answers_are_only_in_history_unless_author_puts_results_in_body(tmp_path): - record = document() - record["items"][0].update(title="1. Blue border", status="answered", answer="Recommended.\nRetain the curved edge.") - record["items"][1].update(status="withdrawn", answer="Drop the optional flag.") - record["body"] = "## Current design\n\nUse blue with the curved edge." - publish_document(tmp_path, record) - text = render_document(record) - assert "1. 1." not in text - assert record["body"] in text - assert record["items"][0]["answer"] not in text and record["items"][1]["answer"] not in text - history = question_records.render_history_document(tmp_path, record) - assert record["items"][0]["answer"] in history and record["items"][1]["answer"] in history - - -def test_completed_questions_leave_current_contract_and_approval_visible_without_empty_question_section(tmp_path): - record = document() - record["items"][0].update(status="answered", answer="Use blue.") - record["items"][1].update(status="withdrawn", answer="No optional border.") - record["approval"] = {"status": "pending", "reason": "Confirm the finished palette."} - publish_document(tmp_path, record) - text = (tmp_path / "ask-1.md").read_text(encoding="utf-8") - assert "## 결정할 것" not in text - assert record["body"] in text and record["approval"]["reason"] in text - assert summarize_document(record).pending - assert not inspect_document(tmp_path, "ask-1.md", text)[1] - - -def test_existing_archive_link_is_not_appended_again_and_record_is_unchanged(tmp_path): - record = document() - record["body"] += "\n\n[Palette source](details/history/ask-1.md)" - publish_document(tmp_path, record) - text = (tmp_path / "ask-1.md").read_text(encoding="utf-8") - assert text.count("](details/history/ask-1.md)") == 1 - assert record["body"] in text - assert read_document(tmp_path, "ask-1.md") == record - assert not inspect_document(tmp_path, "ask-1.md", text)[1] - - -def test_previous_layout_remains_readable_but_edits_fail_and_render_writes_current_layout(tmp_path): - record = document() - record["items"][0].update(status="answered", answer="Use blue.") - record["items"][1].update(status="withdrawn", answer="No optional border.") - record["body"] += "\n\n[Palette source](details/history/ask-1.md)" - publish_document(tmp_path, record) - current = (tmp_path / "ask-1.md").read_text(encoding="utf-8") - previous = current.replace(record["intro"], record["intro"] + "\n\n## 결정할 것") - previous = previous.rstrip() + "\n\n## 전체 이력\n\n[질문·답 원문 전체 이력](details/history/ask-1.md)\n" - (tmp_path / "ask-1.md").write_text(previous, encoding="utf-8") - assert previous != current - assert not inspect_document(tmp_path, "ask-1.md", previous)[1] - assert inspect_document(tmp_path, "ask-1.md", previous.replace(record["body"], "Changed palette."))[1] - render_saved_document(tmp_path, "ask-1.md") - assert (tmp_path / "ask-1.md").read_text(encoding="utf-8") == current - - -@pytest.mark.parametrize("change", ["missing", "tampered"]) -def test_inspection_rejects_missing_or_changed_generated_history_and_render_repairs_it(tmp_path, change): - record = publish_document(tmp_path, document()) - archive = question_records.history_path(tmp_path, "ask-1.md") - if change == "missing": - archive.unlink() - else: - archive.write_text("Changed archived answer", encoding="utf-8") - assert inspect_document(tmp_path, "ask-1.md", render_document(record))[1] - render_saved_document(tmp_path, "ask-1.md") - assert not inspect_document(tmp_path, "ask-1.md", render_document(record))[1] - - -@pytest.mark.parametrize("change", [ - lambda record: record.update(revision=True), - lambda record: record.update(schema=True), - lambda record: record["items"].append(copy.deepcopy(record["items"][0])), - lambda record: record["items"][0].update(status="unknown"), - lambda record: record["items"][0].update(status="answered"), - lambda record: record["items"][0].update(status="withdrawn"), - lambda record: record["items"][0].update(id="../1"), - lambda record: record.update(approval={"status": "pending", "reason": ""}), - lambda record: record.update(answers={}), - lambda record: record.update(body=None), -]) -def test_invalid_records_are_rejected_without_writing(tmp_path, change): - record = document() - change(record) - with pytest.raises(QuestionRecordError): - publish_document(tmp_path, record) - assert not (tmp_path / "ask-1.md").exists() - - -@pytest.mark.parametrize("change", [ - lambda record: record.update(approvals={"status": "pending", "reason": "오타"}), - lambda record: record["items"][0].update(statuz="answered"), - lambda record: record["approval"].update(reasons="오타"), - lambda record: record.update(answers=[{**answer(), "approvals": {"status": "pending", "reason": "오타"}}]), - lambda record: record.update(answers=[answer(updates=[{"id": "1", "status": "answered", "answer": "권장", "title": "잘못된 키"}])]), -]) -def test_unknown_schema_fields_are_rejected_before_publication(tmp_path, change): - record = document() - change(record) - with pytest.raises(QuestionRecordError, match="알 수 없는 필드"): - publish_document(tmp_path, record) - assert not source_path(tmp_path, "ask-1.md").exists() - assert not (tmp_path / "ask-1.md").exists() - - -def test_unknown_answer_payload_fields_are_rejected_before_writing(tmp_path): - original = publish_document(tmp_path, document()) - payload = {**answer(), "approvals": {"status": "pending", "reason": "오타"}} - with pytest.raises(QuestionRecordError, match="알 수 없는 필드"): - answer_document(tmp_path, "ask-1.md", payload) - assert read_document(tmp_path, "ask-1.md") == original - - -def test_empty_items_cannot_claim_a_known_complete_document(tmp_path): - record = document() - record["items"] = [] - with pytest.raises(QuestionRecordError, match="비어 있지 않은 배열"): - publish_document(tmp_path, record) - - -def test_current_revision_history_rejects_unknown_item_but_old_revision_preserves_it(tmp_path): - publish_document(tmp_path, document()) - saved = answer_document(tmp_path, "ask-1.md", answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}])) - removed = copy.deepcopy(saved) - removed["items"] = [removed["items"][1]] - with pytest.raises(QuestionRecordError, match="현재 개정 답 대상 문항이 없음"): - publish_document(tmp_path, removed, 1) - removed["revision"] = 2 - assert publish_document(tmp_path, removed, 1)["answers"] == saved["answers"] - - -def test_publish_cannot_change_existing_answer_but_can_reset_for_reconfirmation(tmp_path): - publish_document(tmp_path, document()) - saved = answer_document(tmp_path, "ask-1.md", answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}])) - changed = copy.deepcopy(saved) - changed["revision"] = 2 - changed["items"][0]["answer"] = "대안" - with pytest.raises(QuestionRecordError, match="기존 문항 답 변경"): - publish_document(tmp_path, changed, 1) - changed["items"][0].update(status="pending", answer="") - assert publish_document(tmp_path, changed, 1)["answers"] == saved["answers"] - - -@pytest.mark.parametrize("approval", [ - {"status": "none", "reason": ""}, - {"status": "complete", "reason": "사용자 승인"}, -]) -def test_publish_cannot_resolve_approval_wait(tmp_path, approval): - record = document() - record["approval"] = {"status": "pending", "reason": "승인 대기"} - saved = publish_document(tmp_path, record) - changed = {**saved, "revision": 2, "approval": approval} - with pytest.raises(QuestionRecordError, match="승인 대기 해소"): - publish_document(tmp_path, changed, 1) - assert read_document(tmp_path, "ask-1.md") == saved - - -def test_publish_cannot_append_answer_history(tmp_path): - saved = publish_document(tmp_path, document()) - changed = {**saved, "revision": 2, "answers": [answer()]} - with pytest.raises(QuestionRecordError, match="이력 변경은 answer"): - publish_document(tmp_path, changed, 1) - assert read_document(tmp_path, "ask-1.md") == saved - - -@pytest.mark.parametrize("field", ["title", "body", "heading"]) -def test_changed_item_definition_cannot_inherit_answered_status(tmp_path, field): - publish_document(tmp_path, document()) - saved = answer_document(tmp_path, "ask-1.md", answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}])) - changed = copy.deepcopy(saved) - changed["revision"] = 2 - changed["items"][0][field] = "새로운 결정 범위" - with pytest.raises(QuestionRecordError, match="내용이 바뀐 문항"): - publish_document(tmp_path, changed, 1) - assert read_document(tmp_path, "ask-1.md") == saved - changed["items"][0].update(status="pending", answer="") - assert publish_document(tmp_path, changed, 1)["answers"] == saved["answers"] - answered = answer_document(tmp_path, "ask-1.md", answer("reply-2", 2, [{"id": "1", "status": "answered", "answer": "새 범위의 대안"}])) - assert answered["items"][0]["status"] == "answered" - assert answered["answers"][-1]["revision"] == 2 - - -@pytest.mark.parametrize("status", ["pending", "withdrawn", "answered"]) -def test_new_item_accepts_pending_or_explicit_withdrawal_but_requires_new_answer(tmp_path, status): - original = publish_document(tmp_path, document()) - changed = copy.deepcopy(original) - changed["revision"] = 2 - changed["items"].append({"id": "3", "title": "추가 결정", "body": "새 선택지", "status": status, "answer": "새 범위 제외"}) - if status == "answered": - with pytest.raises(QuestionRecordError, match="새 문항"): - publish_document(tmp_path, changed, 1) - assert read_document(tmp_path, "ask-1.md") == original - else: - assert publish_document(tmp_path, changed, 1)["items"][-1]["status"] == status - - -@pytest.mark.parametrize("field", ["intro", "body"]) -def test_document_scope_change_requires_explicit_approval_wait_to_preserve_answers(tmp_path, field): - publish_document(tmp_path, document()) - saved = answer_document(tmp_path, "ask-1.md", answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}])) - changed = copy.deepcopy(saved) - changed["revision"] = 2 - changed[field] = "승인 대상이 바뀐 범위" - with pytest.raises(QuestionRecordError, match="approval 대기"): - publish_document(tmp_path, changed, 1) - changed["approval"] = {"status": "pending", "reason": "전체 범위 변경 재확인"} - assert publish_document(tmp_path, changed, 1)["answers"] == saved["answers"] - summary = summarize_document(changed) - assert summary.pending and summary.pending_count == 1 - - -def test_document_scope_change_can_reset_items_while_retaining_raw_history(tmp_path): - publish_document(tmp_path, document()) - saved = answer_document(tmp_path, "ask-1.md", answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}])) - changed = copy.deepcopy(saved) - changed["revision"] = 2 - changed["body"] = "다시 판단할 범위" - changed["items"][0].update(status="pending", answer="") - assert publish_document(tmp_path, changed, 1)["answers"] == saved["answers"] - - -def test_editorial_declaration_preserves_answer_scope_and_allows_text_edits(tmp_path): - publish_document(tmp_path, document()) - saved = answer_document(tmp_path, "ask-1.md", answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}])) - changed = copy.deepcopy(saved) - changed.update(revision=2, title="제목 문체", intro="소개 문체", body="상세 문체") - changed["items"][0].update(title="문항 문체", body="선택지 문체", heading="1. 원래 승인 범위") - with pytest.raises(QuestionRecordError): - publish_document(tmp_path, changed, 1) - assert publish_document(tmp_path, changed, 1, editorial=True) == changed - assert changed["answers"] == saved["answers"] - - -def test_editorial_approval_reason_can_be_reworded_without_changing_state_or_answer_evidence(tmp_path): - publish_document(tmp_path, document()) - payload = answer() - payload["approval"] = {"status": "pending", "reason": "The palette still needs confirmation."} - saved = answer_document(tmp_path, "ask-1.md", payload) - changed = copy.deepcopy(saved) - changed["revision"] = 2 - changed["approval"]["reason"] = "Confirm the palette." - publish_document(tmp_path, changed, 1, editorial=True) - assert summarize_document(changed).pending - assert changed["answers"] == saved["answers"] - assert question_records.read_json(tmp_path / "questions/history/ask-1/1.json") == saved - archive = question_records.history_path(tmp_path, "ask-1.md").read_text(encoding="utf-8") - assert saved["approval"]["reason"] in archive - assert changed["approval"]["reason"] in render_document(changed) - - -@pytest.mark.parametrize("change", [ - lambda record: record["items"][0].update(status="pending"), - lambda record: record["items"][0].update(answer="다른 결정"), - lambda record: record.update(approval={"status": "pending", "reason": "승인 변경"}), - lambda record: record["items"].append({"id": "3", "title": "추가", "body": "", "status": "pending", "answer": ""}), - lambda record: record.update(legacy_markdown="새 원문"), -]) -def test_editorial_declaration_cannot_change_states_approval_or_item_identity(tmp_path, change): - publish_document(tmp_path, document()) - saved = answer_document(tmp_path, "ask-1.md", answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}])) - changed = copy.deepcopy(saved) - changed["revision"] = 2 - change(changed) - with pytest.raises(QuestionRecordError, match="editorial"): - publish_document(tmp_path, changed, 1, editorial=True) - assert read_document(tmp_path, "ask-1.md") == saved - - -def test_editorial_declaration_requires_an_existing_document(tmp_path): - with pytest.raises(QuestionRecordError, match="기존 질문"): - publish_document(tmp_path, document(), editorial=True) - - -def test_new_publication_preserves_reviewed_revision_and_legacy_original(tmp_path): - record = document() - record["revision"] = 2 - record["legacy_markdown"] = "# 기존 원문\r\n\r\n- 답: 권장\r\n" - assert publish_document(tmp_path, record) == record - assert read_document(tmp_path, "ask-1.md")["legacy_markdown"] == record["legacy_markdown"] - assert document_names(tmp_path) == ["ask-1.md"] - - -def test_initial_publication_without_legacy_original_does_not_overwrite_markdown(tmp_path): - original = "# 기존 답변\r\n\r\n권장대로\r\n".encode("utf-8") - markdown_path = tmp_path / "ask-1.md" - markdown_path.write_bytes(original) - with pytest.raises(QuestionRecordError, match="기존 Markdown 보호"): - publish_document(tmp_path, document()) - assert markdown_path.read_bytes() == original - assert not source_path(tmp_path, "ask-1.md").exists() - - -def test_initial_migration_rejects_changed_original_and_accepts_matching_legacy(tmp_path): - record = document() - record["legacy_markdown"] = "\ufeff# 이전 답변\r\n\r\n권장대로\r\n" - markdown_path = tmp_path / "ask-1.md" - changed = record["legacy_markdown"] + "다른 세션의 추가 답변\r\n" - markdown_path.write_bytes(changed.encode("utf-8")) - with pytest.raises(QuestionRecordError, match="기존 Markdown 보호"): - publish_document(tmp_path, record) - assert markdown_path.read_bytes() == changed.encode("utf-8") - assert not source_path(tmp_path, "ask-1.md").exists() - record["legacy_markdown"] = changed - assert publish_document(tmp_path, record) == record - assert read_document(tmp_path, "ask-1.md")["legacy_markdown"] == changed - markdown_path.write_text("손편집", encoding="utf-8") - assert publish_document(tmp_path, record) == record - assert markdown_path.read_text(encoding="utf-8") == render_document(record) - - -def test_legacy_heading_preserves_anchor_separately_from_item_identity(tmp_path): - record = document() - record["items"][0]["heading"] = "A2 결정 5 해금 기준을 선택할까요?" - record["items"][1]["heading"] = "결정 a. 답변 완료 범위는?" - saved = publish_document(tmp_path, record) - text = render_document(saved) - assert "### A2 결정 5 해금 기준을 선택할까요?\n" in text - assert "### 결정 a. 답변 완료 범위는?\n" in text - summary = summarize_document(saved) - assert [(item.number, item.status) for item in summary.items] == [("1", "pending"), ("2", "pending")] - assert summary.pending - - -@pytest.mark.parametrize("heading", ["", " ", "첫 줄\n둘째 줄", "한 줄\n", None]) -def test_invalid_legacy_heading_is_rejected(tmp_path, heading): - record = document() - record["items"][0]["heading"] = heading - with pytest.raises(QuestionRecordError, match="heading"): - publish_document(tmp_path, record) - - -def test_publish_requires_new_revision_and_current_expectation_and_preserves_history(tmp_path): - original = publish_document(tmp_path, document()) - changed = copy.deepcopy(original) - changed["title"] = "수정된 질문" - with pytest.raises(QuestionRecordError, match="revision"): - publish_document(tmp_path, changed, 1) - changed["revision"] = 2 - with pytest.raises(QuestionRecordError, match="expected_revision"): - publish_document(tmp_path, changed) - published = publish_document(tmp_path, changed, 1) - history = tmp_path / "questions" / "history" / "ask-1" / "1.json" - assert json.loads(history.read_text(encoding="utf-8")) == original - assert published == changed and document_names(tmp_path) == ["ask-1.md"] - with pytest.raises(QuestionRecordError, match="expected_revision"): - publish_document(tmp_path, {**published, "revision": 3, "title": "지연된 작성"}, 1) - assert read_document(tmp_path, "ask-1.md") == changed - - -def test_publish_preserves_prior_raw_answer_and_legacy_bytes(tmp_path): - record = document() - record["legacy_markdown"] = "원래 문서\r\n" - publish_document(tmp_path, record) - saved = answer_document(tmp_path, "ask-1.md", answer()) - changed = {**saved, "revision": 2, "answers": []} - with pytest.raises(QuestionRecordError, match="이력"): - publish_document(tmp_path, changed, 1) - changed["answers"] = saved["answers"] - changed["legacy_markdown"] = "고친 원문" - with pytest.raises(QuestionRecordError, match="legacy_markdown"): - publish_document(tmp_path, changed, 1) - - -def test_publish_history_collision_is_rejected(tmp_path): - publish_document(tmp_path, document()) - history = tmp_path / "questions" / "history" / "ask-1" / "1.json" - history.parent.mkdir(parents=True) - history.write_text("{}", encoding="utf-8") - with pytest.raises(QuestionRecordError, match="이력 충돌"): - publish_document(tmp_path, {**document(), "revision": 2}, 1) - assert read_document(tmp_path, "ask-1.md")["revision"] == 1 - - -def test_answer_operation_retry_is_idempotent_after_later_revision(tmp_path): - publish_document(tmp_path, document()) - payload = answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}]) - saved = answer_document(tmp_path, "ask-1.md", payload) - updated = copy.deepcopy(saved) - updated["revision"] = 2 - updated["items"][0].update(status="pending", answer="") - publish_document(tmp_path, updated, 1) - (tmp_path / "ask-1.md").unlink() - assert answer_document(tmp_path, "ask-1.md", payload) == updated - assert read_document(tmp_path, "ask-1.md")["items"][0]["status"] == "pending" - with pytest.raises(QuestionRecordError, match="내용이 다름"): - answer_document(tmp_path, "ask-1.md", {**payload, "text": "다른 원문"}) - with pytest.raises(QuestionRecordError, match="revision"): - answer_document(tmp_path, "ask-1.md", answer("late-reply", 1)) - - -@pytest.mark.parametrize("updates", [ - [{"id": "missing", "status": "answered", "answer": "권장"}], - [{"id": "1", "status": "answered", "answer": ""}], - [{"id": "1", "status": "bogus", "answer": "권장"}], - [{"id": "1", "status": "answered", "answer": "권장"}] * 2, -]) -def test_bad_answer_does_not_modify_source(tmp_path, updates): - saved = publish_document(tmp_path, document()) - with pytest.raises(QuestionRecordError): - answer_document(tmp_path, "ask-1.md", answer(updates=updates)) - assert read_document(tmp_path, "ask-1.md") == saved - - -def test_inspection_never_falls_back_to_markdown_status(tmp_path): - text = "# 이미 답변\n\n답변 완료\n\n## 답\n\n권장대로\n" - summary, issue = inspect_document(tmp_path, "ask-1.md", text) - assert issue and not summary.pending and not summary.count_known and not summary.total_known - publish_document(tmp_path, document()) - summary, issue = inspect_document(tmp_path, "ask-1.md", text) - assert issue and summary.items == [] - source_path(tmp_path, "ask-1.md").write_text("{", encoding="utf-8") - summary, issue = inspect_document(tmp_path, "ask-1.md", text) - assert issue and not summary.count_known - - -def test_markdown_and_direct_source_edits_require_explicit_render_repair(tmp_path): - record = publish_document(tmp_path, document()) - text = render_document(record) - assert not inspect_document(tmp_path, "ask-1.md", text.replace("\n", "\r\n"))[1] - assert inspect_document(tmp_path, "ask-1.md", text + "수기 답변 완료\n")[1] - record["items"][0].update(status="answered", answer="대안") - source_path(tmp_path, "ask-1.md").write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8") - assert inspect_document(tmp_path, "ask-1.md", text)[1] - assert render_saved_document(tmp_path, "ask-1.md") == record - assert not inspect_document(tmp_path, "ask-1.md", (tmp_path / "ask-1.md").read_text(encoding="utf-8"))[1] - - -def test_publication_and_answer_rollback_all_outputs_after_markdown_failure(tmp_path, monkeypatch): - write_text = question_records.write_text - - def fail_markdown(path, text): - if path.suffix == ".md": - raise OSError("Markdown 쓰기 중단") - write_text(path, text) - - monkeypatch.setattr(question_records, "write_text", fail_markdown) - with pytest.raises(QuestionRecordError, match="Markdown"): - publish_document(tmp_path, document()) - assert not source_path(tmp_path, "ask-1.md").exists() - monkeypatch.setattr(question_records, "write_text", write_text) - original = publish_document(tmp_path, document()) - payload = answer(updates=[{"id": "1", "status": "answered", "answer": "권장"}]) - monkeypatch.setattr(question_records, "write_text", fail_markdown) - with pytest.raises(QuestionRecordError, match="Markdown"): - answer_document(tmp_path, "ask-1.md", payload) - assert read_document(tmp_path, "ask-1.md") == original - monkeypatch.setattr(question_records, "write_text", write_text) - saved = answer_document(tmp_path, "ask-1.md", payload) - assert len(saved["answers"]) == 1 - assert not inspect_document(tmp_path, "ask-1.md", (tmp_path / "ask-1.md").read_text(encoding="utf-8"))[1] - - -@pytest.mark.parametrize("name", ["../ask-1.md", ".ask-1.md", "sub/ask-1.md", "ask-../x.md", "C:\\ask-1.md", "ask-1.json", "mission.md"]) -def test_hidden_or_external_names_are_rejected(tmp_path, name): - with pytest.raises(QuestionRecordError): - source_path(tmp_path, name) - - -@pytest.mark.parametrize("target", ["questions", "ask-1.md"]) -def test_symlink_escape_is_rejected(tmp_path, target): - mission = tmp_path / "mission" - outside = tmp_path / "outside" - mission.mkdir() - outside.mkdir() - link = mission / target - destination = outside / "other.md" - if target == "questions": - destination = outside - try: - link.symlink_to(destination, target_is_directory=target == "questions") - except OSError: - pytest.skip("symlink 생성 권한 없음") - with pytest.raises(QuestionRecordError, match="미션 밖"): - publish_document(mission, document()) - assert not list(outside.iterdir()) - - -@pytest.fixture -def recovery(tmp_path): - earlier = {"schema": 1, "id": "first-choice", "revision": 1, "at": "2041-02-03", - "text": "Keep the author filter.", - "updates": [{"id": "author", "status": "answered", "answer": "Author filter retained."}]} - current = { - "schema": 1, "id": "ask-library", "revision": 3, "title": "Library filters", "intro": "Choose filters.", - "items": [{"id": "author", "title": "Author", "body": "", "status": "answered", "answer": "Author filter retained."}, - {"id": "year", "title": "Year", "body": "", "status": "pending", "answer": ""}], - "body": "", "approval": {"status": "pending", "reason": "Review remaining filters."}, - "answers": [earlier], "legacy_markdown": "# Initial library choices\r\n", - } - publish_document(tmp_path, current) - original_json = b"\xef\xbb\xbf" + json.dumps(current, ensure_ascii=False).encode("utf-8") + b"\r\n" - source_path(tmp_path, "ask-library.md").write_bytes(original_json) - restored = copy.deepcopy(current) - restored["items"][1].update(status="answered", answer="Year filter retained.") - restored["items"].append({"id": "publisher", "title": "Publisher", "body": "", "status": "withdrawn", - "answer": "Publisher filter excluded."}) - restored["body"] = "## Approved filter design\n\nAuthor and year filters." - restored["approval"] = {"status": "complete", "reason": "Filter design approved."} - restored["answers"].extend([ - {"schema": 1, "id": "year-choice", "revision": 2, "at": "2041-02-05T10:15:00Z", - "text": "Keep the year filter.\nShow the selected year.", - "updates": [{"id": "year", "status": "answered", "answer": "Year filter retained."}]}, - {"schema": 1, "id": "final-choice", "revision": 3, "at": "2041-02-07", - "text": "Exclude publisher. Approve the filter design.", - "updates": [{"id": "publisher", "status": "withdrawn", "answer": "Publisher filter excluded."}], - "approval": restored["approval"]}, - ]) - original_markdown = ("\ufeff# Recorded library discussion\r\n\r\n" + - "\r\n\r\n".join(item["text"].replace("\n", "\r\n") for item in restored["answers"]) + - "\r\n\r\n## Approved filter design\r\nAuthor and year filters.\r\n").encode("utf-8") - (tmp_path / "ask-library.md").write_bytes(original_markdown) - evidence = tmp_path / "saved-original.md" - evidence.write_bytes(original_markdown) - reviewed = tmp_path / "reviewed.json" - - def run(record=restored, **options): - reviewed.write_bytes(json.dumps(record, ensure_ascii=False).encode("utf-8")) - arguments = {"input_path": reviewed, "source": evidence, "expected_revision": 3, - "expected_sha256": hashlib.sha256(original_json).hexdigest()} - arguments.update(options) - return restore_document(tmp_path, **arguments) - - return current, restored, original_json, original_markdown, evidence, reviewed, run - - -def assert_recovery_originals(tmp_path, recovery): - assert source_path(tmp_path, "ask-library.md").read_bytes() == recovery[2] - assert (tmp_path / "ask-library.md").read_bytes() == recovery[3] - - -def test_restore_preserves_historical_dates_revisions_and_byte_snapshots(tmp_path, recovery): - current, restored, original_json, original_markdown, _, reviewed, run = recovery - assert run() == restored - saved = read_document(tmp_path, "ask-library.md") - assert saved["revision"] == 3 and saved["answers"][:1] == current["answers"] - assert [(entry["revision"], entry["at"]) for entry in saved["answers"]] == [ - (1, "2041-02-03"), (2, "2041-02-05T10:15:00Z"), (3, "2041-02-07")] - history = tmp_path / "questions" / "history" / "ask-library" / "recovery" - snapshot, = history.iterdir() - assert (snapshot / "before.json").read_bytes() == original_json - assert (snapshot / "before.md").read_bytes() == original_markdown - assert (snapshot / "input.json").read_bytes() == reviewed.read_bytes() - receipt = json.loads((snapshot / "receipt.json").read_text(encoding="utf-8")) - assert receipt["status"] == "complete" and receipt["repaired_at"] - for name, digest in receipt["sha256"].items(): - assert hashlib.sha256((snapshot / name).read_bytes()).hexdigest() == digest - assert (snapshot / "after.json").read_bytes() == source_path(tmp_path, "ask-library.md").read_bytes() - assert not inspect_document(tmp_path, "ask-library.md", (tmp_path / "ask-library.md").read_text(encoding="utf-8"))[1] - with pytest.raises(QuestionRecordError, match="expected_sha256"): - run() - assert list(history.iterdir()) == [snapshot] - with pytest.raises(QuestionRecordError, match="현재 정본과 같음"): - run(expected_sha256=receipt["sha256"]["after.json"], source=snapshot / "after.md") - - -@pytest.mark.parametrize("change, message", [ - (lambda record: record["answers"][0].update(at="2041-02-04"), "앞부분"), - (lambda record: record["answers"].pop(0), "앞부분"), - (lambda record: record.pop("legacy_markdown"), "legacy_markdown"), - (lambda record: record.update(legacy_markdown="Changed original"), "legacy_markdown"), - (lambda record: record["items"].pop(0), "문항 id"), - (lambda record: record.update(revision=4), "id와 revision"), - (lambda record: record["answers"][1].update(text="Use a subject filter instead."), "원문"), - (lambda record: record["answers"][1].update(updates=[]), "추가 이력"), - (lambda record: record["answers"][2].update(updates=[]), "추가 이력"), - (lambda record: record["answers"][2].pop("approval"), "승인 변경"), - (lambda record: record["items"][0].update(status="pending", answer=""), "추가 이력"), - (lambda record: record["items"][0].update(answer="Author filter excluded."), "추가 이력"), - (lambda record: record["answers"][1]["updates"].append({"id": "missing", "status": "answered", "answer": "Include."}), "대상 문항"), -]) -def test_restore_rejects_lost_history_and_unbacked_outcomes(tmp_path, recovery, change, message): - restored = copy.deepcopy(recovery[1]) - change(restored) - with pytest.raises(QuestionRecordError, match=message): - recovery[-1](restored) - assert_recovery_originals(tmp_path, recovery) - assert not (tmp_path / "questions" / "history").exists() - - -@pytest.mark.parametrize("options, message", [ - ({"expected_revision": 2}, "expected_revision"), - ({"expected_sha256": "0" * 64}, "expected_sha256"), -]) -def test_restore_snapshot_preconditions_reject_before_backups(tmp_path, recovery, options, message): - with pytest.raises(QuestionRecordError, match=message): - recovery[-1](**options) - assert_recovery_originals(tmp_path, recovery) - assert not (tmp_path / "questions" / "history").exists() - - -def test_restore_source_requires_exact_bytes(tmp_path, recovery): - recovery[4].write_bytes(recovery[3].replace(b"\r\n", b"\n")) - with pytest.raises(QuestionRecordError, match="source"): - recovery[-1]() - assert_recovery_originals(tmp_path, recovery) - - -@pytest.mark.parametrize("target", ["ask-library.md", "questions/ask-library.json"]) -def test_restore_requires_both_live_files(tmp_path, recovery, target): - (tmp_path / target).unlink() - with pytest.raises(QuestionRecordError, match="기존 JSON과 Markdown"): - recovery[-1]() - - -@pytest.mark.parametrize("target", ["ask-library.md", "questions/ask-library.json"]) -def test_restore_rechecks_snapshot_after_backups(tmp_path, recovery, monkeypatch, target): - write_json = question_records.write_json - live = tmp_path / target - external = b"External writer changed this file.\n" - - def change_live_after_receipt(path, value): - write_json(path, value) - if path.name == "receipt.json": - live.write_bytes(external) - - monkeypatch.setattr(question_records, "write_json", change_live_after_receipt) - with pytest.raises(QuestionRecordError, match="준비 중"): - recovery[-1]() - assert live.read_bytes() == external - unchanged = tmp_path / ("questions/ask-library.json" if target.endswith(".md") else "ask-library.md") - assert unchanged.read_bytes() == recovery[2 if target.endswith(".md") else 3] - - -@pytest.mark.parametrize("target", ["ask-library.md", "ask-library.json"]) -def test_restore_write_failure_rolls_back_pair_and_retains_backups(tmp_path, recovery, monkeypatch, target): - write_bytes = question_records.write_bytes - - def fail_live_once(path, value): - if path.name == target and "recovery" not in path.parts: - raise OSError("Simulated live write failure") - write_bytes(path, value) - - monkeypatch.setattr(question_records, "write_bytes", fail_live_once) - with pytest.raises(QuestionRecordError, match="원본 복원됨"): - recovery[-1]() - assert_recovery_originals(tmp_path, recovery) - snapshot, = (tmp_path / "questions" / "history" / "ask-library" / "recovery").iterdir() - assert (snapshot / "before.json").read_bytes() == recovery[2] - assert (snapshot / "before.md").read_bytes() == recovery[3] - assert json.loads((snapshot / "receipt.json").read_text(encoding="utf-8"))["status"] == "rolled_back" - - -def test_restore_does_not_overwrite_external_edit_during_rollback(tmp_path, recovery, monkeypatch): - write_bytes = question_records.write_bytes - path = source_path(tmp_path, "ask-library.md") - - def fail_markdown_after_external_edit(target, value): - if target == tmp_path / "ask-library.md": - path.write_bytes(b"External change\n") - raise OSError("Simulated write failure") - write_bytes(target, value) - - monkeypatch.setattr(question_records, "write_bytes", fail_markdown_after_external_edit) - with pytest.raises(QuestionRecordError, match="롤백 확인 필요"): - recovery[-1]() - assert path.read_bytes() == b"External change\n" - assert (tmp_path / "ask-library.md").read_bytes() == recovery[3] - - -def test_restore_preserves_publish_and_answer_protections(tmp_path, recovery): - restored = recovery[1] - with pytest.raises(QuestionRecordError, match="revision"): - publish_document(tmp_path, restored, 3) - newer = {**restored, "revision": 4} - with pytest.raises(QuestionRecordError, match="이력 변경은 answer"): - publish_document(tmp_path, newer, 3) - with pytest.raises(QuestionRecordError, match="revision"): - answer_document(tmp_path, "ask-library.md", restored["answers"][1]) - with pytest.raises(QuestionRecordError, match="대상 문항이 없음"): - answer_document(tmp_path, "ask-library.md", restored["answers"][2]) - assert_recovery_originals(tmp_path, recovery) - - -def test_restore_backup_failure_keeps_live_pair_and_retry_uses_new_history(tmp_path, recovery, monkeypatch): - write_bytes = question_records.write_bytes - - def fail_before_markdown(path, value): - if path.name == "before.md": - raise OSError("Simulated backup write failure") - write_bytes(path, value) - - monkeypatch.setattr(question_records, "write_bytes", fail_before_markdown) - with pytest.raises(QuestionRecordError, match="백업 저장 실패"): - recovery[-1]() - assert_recovery_originals(tmp_path, recovery) - history = tmp_path / "questions" / "history" / "ask-library" / "recovery" - failed, = history.iterdir() - assert (failed / "before.json").read_bytes() == recovery[2] - monkeypatch.setattr(question_records, "write_bytes", write_bytes) - recovery[-1]() - assert len(list(history.iterdir())) == 2 - assert (failed / "before.json").read_bytes() == recovery[2] - - -def test_restore_cannot_add_legacy_markdown_when_absent(tmp_path, recovery): - current = copy.deepcopy(recovery[0]) - current.pop("legacy_markdown") - path = source_path(tmp_path, "ask-library.md") - path.write_bytes(json.dumps(current).encode("utf-8")) - before = path.read_bytes() - with pytest.raises(QuestionRecordError, match="legacy_markdown"): - recovery[-1](expected_sha256=hashlib.sha256(before).hexdigest()) - assert path.read_bytes() == before - assert (tmp_path / "ask-library.md").read_bytes() == recovery[3] - - -def test_restore_accepts_evidenced_downgrade_and_rejects_mismatched_final_approval(tmp_path, recovery): - restored = copy.deepcopy(recovery[1]) - restored["items"][0].update(status="pending", answer="") - restored["answers"][-1]["updates"].append({"id": "author", "status": "pending", "answer": ""}) - restored["answers"][-1]["text"] += " Reconsider the author filter." - evidence = recovery[3] + b"\r\nExclude publisher. Approve the filter design. Reconsider the author filter.\r\n" - recovery[4].write_bytes(evidence) - (tmp_path / "ask-library.md").write_bytes(evidence) - wrong = copy.deepcopy(restored) - wrong["approval"] = {"status": "pending", "reason": "Another review."} - with pytest.raises(QuestionRecordError, match="승인 변경"): - recovery[-1](wrong) - assert recovery[-1](restored) == restored - - -def test_restore_history_collision_never_overwrites_snapshot(tmp_path, recovery, monkeypatch): - fixed = datetime(2041, 2, 8, tzinfo=timezone.utc) - - class FixedDatetime(datetime): - @classmethod - def now(cls, tz): - return fixed - - monkeypatch.setattr(question_records, "datetime", FixedDatetime) - monkeypatch.setattr(question_records.uuid, "uuid4", lambda: SimpleNamespace(hex="fixed-id")) - history = tmp_path / "questions" / "history" / "ask-library" / "recovery" / "20410208T000000000000Z-fixed-id" - history.mkdir(parents=True) - snapshot = history / "before.json" - snapshot.write_bytes(b"Previously preserved bytes\n") - with pytest.raises(QuestionRecordError, match="백업 저장 실패"): - recovery[-1]() - assert snapshot.read_bytes() == b"Previously preserved bytes\n" - assert list(history.iterdir()) == [snapshot] - assert_recovery_originals(tmp_path, recovery) - - -def test_restore_receipt_completion_failure_rolls_back_pair(tmp_path, recovery, monkeypatch): - write_json = question_records.write_json - - def fail_completion(path, value): - if path.name == "receipt.json" and value["status"] == "complete": - raise OSError("Simulated receipt failure") - write_json(path, value) - - monkeypatch.setattr(question_records, "write_json", fail_completion) - with pytest.raises(QuestionRecordError, match="원본 복원됨"): - recovery[-1]() - assert_recovery_originals(tmp_path, recovery) - snapshot, = (tmp_path / "questions" / "history" / "ask-library" / "recovery").iterdir() - assert json.loads((snapshot / "receipt.json").read_text(encoding="utf-8"))["status"] == "rolled_back" - - -def test_restore_preserves_markdown_edit_between_live_replacements(tmp_path, recovery, monkeypatch): - write_bytes = question_records.write_bytes - path = source_path(tmp_path, "ask-library.md") - markdown = tmp_path / "ask-library.md" - external_markdown = b"# Library filters\n\nKeep the subject filter too.\n" - - def edit_markdown_after_json(target, value): - write_bytes(target, value) - if target == path and value != recovery[2]: - markdown.write_bytes(external_markdown) - - monkeypatch.setattr(question_records, "write_bytes", edit_markdown_after_json) - with pytest.raises(QuestionRecordError, match="현재 파일이 바뀜"): - recovery[-1]() - assert path.read_bytes() == recovery[2] - assert markdown.read_bytes() == external_markdown - snapshot, = (tmp_path / "questions" / "history" / "ask-library" / "recovery").iterdir() - assert (snapshot / "before.md").read_bytes() == recovery[3] - assert json.loads((snapshot / "receipt.json").read_text(encoding="utf-8"))["status"] == "rollback_failed" - - -def test_restore_revalidates_containment_before_replacement_and_rollback(tmp_path, recovery, monkeypatch): - contained_path = question_records.contained_path - write_bytes = question_records.write_bytes - path = source_path(tmp_path, "ask-library.md") - json_replaced = False - rechecked = [] - - def invalidate_markdown_after_json(folder, *parts): - if json_replaced: - rechecked.append(parts) - if parts == ("ask-library.md",): - raise QuestionRecordError("미션 밖 질문 경로: changed Markdown target") - return contained_path(folder, *parts) - - def track_json_replacement(target, value): - nonlocal json_replaced - write_bytes(target, value) - if target == path: - json_replaced = True - - monkeypatch.setattr(question_records, "contained_path", invalidate_markdown_after_json) - monkeypatch.setattr(question_records, "write_bytes", track_json_replacement) - with pytest.raises(QuestionRecordError, match="미션 밖 질문 경로"): - recovery[-1]() - assert_recovery_originals(tmp_path, recovery) - assert ("questions", "ask-library.json") in rechecked - assert ("ask-library.md",) in rechecked - - -@pytest.mark.parametrize("archive_existed", [True, False]) -def test_restore_backs_up_generated_history_and_can_create_it_for_older_records(tmp_path, recovery, archive_existed): - archive = question_records.history_path(tmp_path, "ask-library.md") - original = archive.read_bytes() - if not archive_existed: - archive.unlink() - original = b"" - recovery[-1]() - snapshot, = (tmp_path / "questions/history/ask-library/recovery").iterdir() - receipt = json.loads((snapshot / "receipt.json").read_text(encoding="utf-8")) - assert receipt["before_history_existed"] == archive_existed - assert (snapshot / "before-history.md").read_bytes() == original - assert (snapshot / "after-history.md").read_bytes() == archive.read_bytes() - assert question_records.validate_history_archive(archive, recovery[0]) - assert question_records.validate_history_archive(archive, recovery[1]) - assert "## Approved filter design" in archive.read_text(encoding="utf-8") - - -@pytest.mark.parametrize("archive_existed", [True, False]) -def test_restore_completion_failure_restores_history_bytes_or_removes_new_file(tmp_path, recovery, monkeypatch, archive_existed): - archive = question_records.history_path(tmp_path, "ask-library.md") - original = archive.read_bytes() - if not archive_existed: - archive.unlink() - write_json = question_records.write_json - - def fail_completion(path, value): - if path.name == "receipt.json" and value["status"] == "complete": - raise OSError("Simulated completion failure") - write_json(path, value) - - monkeypatch.setattr(question_records, "write_json", fail_completion) - with pytest.raises(QuestionRecordError, match="원본 복원됨"): - recovery[-1]() - assert_recovery_originals(tmp_path, recovery) - assert archive.exists() == archive_existed - if archive_existed: - assert archive.read_bytes() == original - - -def test_restore_detects_external_history_change_after_backups(tmp_path, recovery, monkeypatch): - archive = question_records.history_path(tmp_path, "ask-library.md") - write_json = question_records.write_json - - def change_archive(path, value): - write_json(path, value) - if path.name == "receipt.json": - archive.write_bytes(b"External history edit") - - monkeypatch.setattr(question_records, "write_json", change_archive) - with pytest.raises(QuestionRecordError, match="준비 중 현재 전체 이력"): - recovery[-1]() - assert archive.read_bytes() == b"External history edit" - assert_recovery_originals(tmp_path, recovery) - - -def test_restore_history_write_failure_rolls_back_other_targets(tmp_path, recovery, monkeypatch): - archive = question_records.history_path(tmp_path, "ask-library.md") - original = archive.read_bytes() - write_bytes = question_records.write_bytes - - def fail_history(path, value): - if path == archive: - raise OSError("Simulated history write failure") - write_bytes(path, value) - - monkeypatch.setattr(question_records, "write_bytes", fail_history) - with pytest.raises(QuestionRecordError, match="원본 복원됨"): - recovery[-1]() - assert_recovery_originals(tmp_path, recovery) - assert archive.read_bytes() == original - - -def test_inspection_stamp_covers_every_input_the_inspection_reads(tmp_path): - publish_document(tmp_path, document()) - publish_document(tmp_path, {**document(), "revision": 2, "title": "개정"}, 1) - text = render_document(read_document(tmp_path, "ask-1.md")) - base, _ = question_records.inspection_stamp(tmp_path, "ask-1.md", text) - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] == base - inputs = {os.path.relpath(path, tmp_path).replace(os.sep, "/") for path in question_records.inspection_inputs(tmp_path, "ask-1.md")} - assert {"questions/ask-1.json", "details/history/ask-1.md", "questions/history/ask-1/1.json"} <= inputs - for relative in sorted(inputs): - path = tmp_path / relative - before = path.stat().st_mtime_ns - os.utime(path, ns=(before + 10**9, before + 10**9)) - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] != base, relative - os.utime(path, ns=(before, before)) - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text + "x")[0] != base - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] == base - - -def test_inspection_stamp_notices_missing_added_and_recovery_inputs(tmp_path): - publish_document(tmp_path, document()) - text = render_document(read_document(tmp_path, "ask-1.md")) - base, newest = question_records.inspection_stamp(tmp_path, "ask-1.md", text) - assert newest == max(os.stat(path).st_mtime_ns for path in question_records.inspection_inputs(tmp_path, "ask-1.md")) - receipt = tmp_path / "questions/history/ask-1/recovery/20260101T000000Z-a/receipt.json" - receipt.parent.mkdir(parents=True) - receipt.write_text("{}", encoding="utf-8") - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] != base - receipt.unlink() - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] == base - question_records.history_path(tmp_path, "ask-1.md").unlink() - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] != base - - -def test_inspection_stamp_rejects_unusable_names_and_text(tmp_path): - with pytest.raises(QuestionRecordError): - question_records.inspection_stamp(tmp_path, "notes.md", "text") - with pytest.raises(QuestionRecordError): - question_records.inspection_stamp(tmp_path, "ask-1.md", None) - - -def link_directory(link, target): - if sys.platform == "win32": - subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], check=True, capture_output=True) - else: - link.symlink_to(target, target_is_directory=True) - - -def unlink_directory(link): - if sys.platform == "win32": - os.rmdir(link) - else: - link.unlink() - - -def test_inspection_stamp_changes_when_an_input_directory_becomes_a_link_to_identical_content(tmp_path): - publish_document(tmp_path, document()) - publish_document(tmp_path, {**document(), "revision": 2, "title": "개정"}, 1) - text = render_document(read_document(tmp_path, "ask-1.md")) - base, _ = question_records.inspection_stamp(tmp_path, "ask-1.md", text) - history = tmp_path / "questions" / "history" / "ask-1" - copied = tmp_path / "copied-history" - shutil.copytree(history, copied) - shutil.rmtree(history) - link_directory(history, copied) - try: - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] != base - finally: - unlink_directory(history) - - -def test_inspection_stamp_changes_when_the_document_file_becomes_a_link_to_identical_content(tmp_path): - publish_document(tmp_path, document()) - text = render_document(read_document(tmp_path, "ask-1.md")) - base, _ = question_records.inspection_stamp(tmp_path, "ask-1.md", text) - document_path = tmp_path / "ask-1.md" - copied = tmp_path / "copied.md" - shutil.copy2(document_path, copied) - document_path.unlink() - try: - document_path.symlink_to(copied) - except OSError: - pytest.skip("symlink 생성 권한 없음") - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] != base - - -def test_inspection_inputs_follow_a_linked_recovery_directory_like_history_records(tmp_path): - publish_document(tmp_path, document()) - elsewhere = tmp_path / "elsewhere" - receipt = elsewhere / "20260101T000000Z-a" / "receipt.json" - receipt.parent.mkdir(parents=True) - receipt.write_text("{}", encoding="utf-8") - recovery = tmp_path / "questions" / "history" / "ask-1" / "recovery" - recovery.parent.mkdir(parents=True) - link_directory(recovery, elsewhere) - try: - text = render_document(read_document(tmp_path, "ask-1.md")) - base, _ = question_records.inspection_stamp(tmp_path, "ask-1.md", text) - inputs = {os.path.normcase(path) for path in question_records.inspection_inputs(tmp_path, "ask-1.md")} - assert os.path.normcase(str(recovery / "20260101T000000Z-a" / "receipt.json")) in inputs - assert os.path.normcase(str(recovery / "20260101T000000Z-a" / "after.json")) in inputs - os.utime(receipt, ns=(10**18, 10**18)) - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] != base - finally: - unlink_directory(recovery) - - -def test_inspection_stamp_includes_the_resolved_path_of_the_document_file(tmp_path, monkeypatch): - publish_document(tmp_path, document()) - text = render_document(read_document(tmp_path, "ask-1.md")) - base, _ = question_records.inspection_stamp(tmp_path, "ask-1.md", text) - document_path = os.path.normcase(str(tmp_path / "ask-1.md")) - original = os.path.realpath - monkeypatch.setattr(os.path, "realpath", lambda path: str(tmp_path / "other.md") if os.path.normcase(os.fspath(path)) == document_path else original(path)) - assert question_records.inspection_stamp(tmp_path, "ask-1.md", text)[0] != base diff --git a/tests/integration/mission/test_question_summary.py b/tests/integration/mission/test_question_summary.py deleted file mode 100644 index 6d3ee6c..0000000 --- a/tests/integration/mission/test_question_summary.py +++ /dev/null @@ -1,356 +0,0 @@ -import os -import sys -from pathlib import Path - -import pytest -from chef.questions.summary import summarize_question - -from tests.paths import PLUGIN_ROOT - - -def question_text(state="답변 대기", answer=""): - return ( - "# [해금 **클라**](ask-3.md): `CL2` 제출\n\n" - f"{state} · 2026-10-22\n\n" - "## 결정할 것\n\n" - "### 1. CL1(427720)과 CL2(427727)를 지금 제출할까요?\n\n" - "- 권장: 제출합니다.\n\n" - "### 2. CL2 제출 뒤 M2b를 M18 대기에서 풀까요?\n\n" - "- 권장: 풉니다.\n\n" - "## 답\n\n" - f"{answer}\n" - ) - - -def test_numbered_metadata_preserves_question_titles_and_remaining_item(): - result = summarize_question("ask-3.md", question_text("질문 1 답변(제출 보류) · 질문 2 대기"), True) - assert result.name == "ask-3.md" - assert result.title == "해금 클라: CL2 제출" - assert [(item.number, item.status) for item in result.items] == [("1", "answered"), ("2", "pending")] - assert result.items[1].title == "CL2 제출 뒤 M2b를 M18 대기에서 풀까요?" - assert result.pending and result.count_known - - -def test_dated_answer_does_not_remove_explicit_remaining_question(): - text = question_text("질문 1 답변 · 질문 2 대기", "2026-10-22 질문 1: 제출 보류") - result = summarize_question("ask-3.md", text, False) - assert result.pending and result.count_known - assert [item.status for item in result.items] == ["answered", "pending"] - - -@pytest.mark.parametrize("name", ["ask-3.md", "confirm-A3.md"]) -@pytest.mark.parametrize("state", ["질문 1 답변 · 질문 2 답변 완료", "답변 완료"]) -def test_all_explicit_answers_remove_document_pending(name, state): - result = summarize_question(name, question_text(state), True) - assert not result.pending and result.count_known - assert all(item.status == "answered" for item in result.items) - - -def test_approved_confirm_overrides_old_waiting_metadata(): - result = summarize_question("confirm-A3.md", question_text(), False) - assert not result.pending and result.count_known - assert all(item.status == "answered" for item in result.items) - - -@pytest.mark.parametrize("marker", ["승인 대기", "전체 승인 확인 대기"]) -@pytest.mark.parametrize("name", ["ask-3.md", "confirm-A3.md"]) -def test_explicit_approval_wait_preserves_document_pending(name, marker): - result = summarize_question(name, question_text(f"답변 완료 · {marker}"), True) - assert result.pending and result.count_known - assert all(item.status == "answered" for item in result.items) - - -@pytest.mark.parametrize("marker", ["승인 대기", "전체 승인 확인 대기"]) -def test_approved_confirm_overrides_explicit_approval_wait(marker): - result = summarize_question("confirm-A3.md", question_text(f"답변 완료 · {marker}"), False) - assert not result.pending and result.count_known - assert all(item.status == "answered" for item in result.items) - - -@pytest.mark.parametrize("name", ["ask-3.md", "confirm-A3.md"]) -def test_global_answer_complete_without_decision_items_clears_pending(name): - result = summarize_question(name, "# 후속 범위\n\n답변 완료\n\n## 답\n\n2026-10-23 권장대로\n", True) - assert not result.pending and not result.total_known and not result.count_known - - -def test_duplicate_confirm_items_do_not_claim_complete_document(): - text = question_text("답변 완료").replace("### 2.", "### 1.") - result = summarize_question("confirm-A3.md", text, True) - assert result.pending and not result.total_known and not result.count_known - - -def test_unnumbered_decision_heading_counts_without_inventing_number(): - result = summarize_question("ask-1.md", "# **다음 작업**\n\n답변 대기\n\n## 결정할 것\n\n### 제출할까요?\n", True) - assert result.title == "다음 작업" - assert [(item.number, item.title, item.status) for item in result.items] == [("", "제출할까요?", "pending")] - assert result.pending and result.count_known and result.total_known - - -@pytest.mark.parametrize("state", ["답변 접수", "답변 전달", "부분 답변", "답변 검토중"]) -def test_receipt_partial_or_unrecognized_status_does_not_claim_answers(state): - result = summarize_question("confirm-A3.md", question_text(f"질문 1 {state} · 질문 2 대기"), True) - assert [item.status for item in result.items] == ["unknown", "pending"] - assert result.pending and not result.count_known - - -def test_standard_waiting_document_without_answers_counts_all_items(): - result = summarize_question("ask-3.md", question_text("초안 · 답변 대기", ""), True) - assert result.pending and result.count_known - assert all(item.status == "pending" for item in result.items) - - -def test_unstructured_answer_is_not_guessed_from_numbers_or_approval_words(): - text = question_text("답변 대기", "2026-10-22 1번은 승인. 2번은 나중에 생각할게요.") - result = summarize_question("ask-3.md", text, False) - assert not result.pending and not result.count_known - assert all(item.status == "unknown" for item in result.items) - - -def test_partial_explicit_metadata_does_not_fill_missing_statuses(): - result = summarize_question("ask-3.md", question_text("답변 대기 · 질문 1 답변"), True) - assert [item.status for item in result.items] == ["answered", "unknown"] - assert result.pending and not result.count_known - - -def test_comments_and_code_do_not_provide_headings_states_or_answers(): - fake = ( - "\n" - "```markdown\n# 코드 제목\n질문 1 답변\n## 결정할 것\n### 9. 가짜 질문\n```\n" - ) - text = fake + question_text("답변 대기", "~~~text\n2026-10-22 승인\n~~~") - result = summarize_question("ask-3.md", text, True) - assert result.title == "해금 클라: CL2 제출" - assert [item.number for item in result.items] == ["1", "2"] - assert result.pending and result.count_known - - -def test_approval_words_in_question_content_are_not_status(): - text = question_text().replace("- 권장: 제출합니다.", "- 권장: 승인합니다. 질문 1 답변 · 질문 2 답변") - result = summarize_question("confirm-A3.md", text, True) - assert result.pending and result.count_known - assert all(item.status == "pending" for item in result.items) - - -def test_explicit_item_answer_fields_are_counted_without_parsing_prose(): - text = question_text("").replace("- 권장: 제출합니다.", "- 답: 답변 완료").replace("- 권장: 풉니다.", "- 답: 미결") - result = summarize_question("ask-3.md", text, False) - assert [item.status for item in result.items] == ["answered", "pending"] - assert result.pending and result.count_known - - -def test_conflicting_explicit_metadata_remains_unknown(): - result = summarize_question("ask-3.md", question_text("질문 1 답변 · 질문 1 대기 · 질문 2 대기"), True) - assert [item.status for item in result.items] == ["unknown", "pending"] - assert result.pending and not result.count_known - - -def test_only_decision_section_questions_are_counted(): - text = question_text() + "\n## 이전 이력\n\n### 3. 이전 질문\n" - result = summarize_question("ask-3.md", text, True) - assert [item.number for item in result.items] == ["1", "2"] - assert result.count_known - - -def test_missing_title_uses_name_and_duplicate_numbers_make_count_unknown(): - text = question_text().replace("# [해금 **클라**](ask-3.md): `CL2` 제출\n", "").replace("### 2.", "### 1.") - result = summarize_question("ask-3.md", text, True) - assert result.title == "ask-3.md" - assert not result.count_known and not result.total_known - - -def test_title_markup_becomes_plain_text(): - result = summarize_question("ask-3.md", "# 상태 & **[기준](https://example.com)**\n", True) - assert result.title == "상태 & 기준" - assert not result.count_known - - -def test_title_preserves_literal_code_conditions_and_language_suffix(): - result = summarize_question("ask-3.md", "# `List`에서 값 < 10 조건을 쓸까요? C#\n", True) - assert result.title == "List에서 값 < 10 조건을 쓸까요? C#" - - -def test_partial_global_status_does_not_expand_old_waiting_into_all_pending(): - result = summarize_question("ask-3.md", question_text("답변 대기 · 부분 답변"), True) - assert all(item.status == "unknown" for item in result.items) - assert not result.count_known - - -def test_partial_answer_annotation_is_unknown(): - result = summarize_question("ask-3.md", question_text("질문 1 답변(일부) · 질문 2 대기"), True) - assert [item.status for item in result.items] == ["unknown", "pending"] - assert not result.count_known - - -def test_metadata_for_missing_question_makes_count_unknown(): - result = summarize_question("ask-3.md", question_text("질문 1 답변 · 질문 2 답변 · 질문 3 대기"), False) - assert result.pending and not result.count_known and not result.total_known - - -def test_comment_markers_in_code_and_fences_in_comments_do_not_hide_real_content(): - hidden = "\n```text\n\n\n```markdown\n### 가짜 sync 승인\n```\n\n" - " ### 들여쓴 승인\n\n### 실제 sync 승인\n" - ) - result = summarize_question("ask-1.md", text, True) - assert result.total_known and result.count_known - assert [(item.number, item.title) for item in result.items] == [("", "실제 sync 승인")] - - -@pytest.mark.parametrize("pending", [True, False]) -def test_explicit_unknown_item_states_keep_document_pending(pending): - result = summarize_question("ask-1.md", question_text("답변 검토중"), pending) - assert result.total_known and not result.count_known - assert result.pending - - -@pytest.mark.parametrize("state", ["답변 접수", "답변 전달", "부분 답변", "질문 1 답변 · 질문 2 답변 접수", "질문 1 답변"]) -def test_dated_answer_cannot_clear_explicit_partial_or_unknown_states(state): - result = summarize_question("ask-1.md", question_text(state, "2026-10-23 사용자 답변"), False) - assert result.pending and not result.count_known - - -@pytest.mark.parametrize("heading", ["답 없이 진행 중인 정리", "답변 완료한 질문", "답변 범위를 넓힐까요?"]) -def test_answer_word_in_other_section_does_not_record_an_answer(heading): - text = question_text().replace("## 답\n", f"## {heading}\n\n2026-10-23 답이 아닌 기록\n") - result = summarize_question("ask-1.md", text, True) - assert result.pending and result.count_known - assert [item.status for item in result.items] == ["pending", "pending"] - - -def test_real_answer_after_fake_answer_heading_records_an_answer(): - text = question_text().replace("## 답\n", "## 답 없이 진행 중인 정리\n\n아직 답이 없음\n\n## 답\n\n2026-10-23 사용자 답변\n") - result = summarize_question("ask-1.md", text, False) - assert not result.pending and result.total_known and not result.count_known - - -@pytest.mark.parametrize("heading", ["답", "답변", "답 (2026-10-23)", "답변: 2026-10-23", "답변 2026-10-23", "답변 (2026.10.23 사용자)"]) -def test_level_three_answer_sections_do_not_add_decisions(heading): - text = ( - "# 질문\n\n답변 대기\n\n## 결정할 것\n\n### 1. 제출할까요?\n\n" - f"### {heading}\n\n2026-10-23 사용자: 승인\n" - ) - result = summarize_question("ask-1.md", text, False) - assert result.total_known and not result.count_known - assert [(item.number, item.title) for item in result.items] == [("1", "제출할까요?")] - assert not result.pending - - -def test_level_three_answer_body_headings_do_not_resume_question_collection(): - text = ( - "# 질문\n\n답변 대기\n\n## 결정할 것\n\n### 1. 제출할까요?\n\n" - "### 답\n\n2026-10-23 사용자: 승인\n\n" - "#### 근거\n\n### 참고한 자료\n\n### 9. 답변의 예시 번호\n" - ) - result = summarize_question("ask-1.md", text, False) - assert result.total_known and len(result.items) == 1 - assert result.items[0].number == "1" and not result.count_known - - -@pytest.mark.parametrize("title", ["답 없이 진행해도 될까요?", "답변 범위를 넓힐까요?"]) -def test_question_starting_with_answer_word_is_still_a_decision(title): - text = ( - "# 질문\n\n답변 대기\n\n## 결정할 것\n\n### 1. 제출할까요?\n\n" - f"### {title}\n\n- 권장: 대기합니다.\n\n" - "### 답\n\n2026-10-23 사용자: 승인\n\n### 답변의 참고 자료\n" - ) - result = summarize_question("ask-1.md", text, False) - assert result.total_known and not result.count_known - assert [(item.number, item.title) for item in result.items] == [("1", "제출할까요?"), ("", title)] - assert not result.pending diff --git a/tests/integration/mission/test_reference_bundle.py b/tests/integration/mission/test_reference_bundle.py deleted file mode 100644 index d1435d0..0000000 --- a/tests/integration/mission/test_reference_bundle.py +++ /dev/null @@ -1,148 +0,0 @@ -import json -from pathlib import Path - -import pytest -from chef.verification import references as reference_bundle - -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture -def project(tmp_path): - root = tmp_path / "project" - root.mkdir() - (root / "guide.md").write_text("Original guidance\n", encoding="utf-8") - return root - - -def test_snapshot_keeps_only_pointers_and_checks_changed_missing(project): - bundle = reference_bundle.snapshot(project, ["guide.md"], "state/reference.json", "r7", "Rules") - assert set(bundle) == {"schema", "sources"} - assert bundle["sources"][0]["path"] == "guide.md" - assert bundle["sources"][0]["revision"] == "r7" - assert "Original guidance" not in (project / "state/reference.json").read_text() - assert reference_bundle.check(project, "state/reference.json")["status"] == "pass" - (project / "guide.md").write_text("Updated guidance\n") - result = reference_bundle.check(project, "state/reference.json") - assert result["changed"] == ["guide.md"] and result["missing"] == [] - with pytest.raises(reference_bundle.ReferenceError, match="snapshot"): - reference_bundle.require_current(project, "state/reference.json") - (project / "guide.md").unlink() - result = reference_bundle.check(project, "state/reference.json") - assert result["missing"] == ["guide.md"] and result["changed"] == [] - - -def test_snapshot_explicit_external_source_and_confined_output(project, tmp_path): - source = tmp_path / "external.md" - source.write_text("External reference\n") - bundle = reference_bundle.snapshot(project, [str(source)], "state/reference.json") - assert bundle["sources"][0]["path"] == str(source.resolve()) - assert reference_bundle.check(project, "state/reference.json")["status"] == "pass" - with pytest.raises(reference_bundle.ReferenceError, match="프로젝트 밖"): - reference_bundle.snapshot(project, ["guide.md"], str(tmp_path / "escaped.json")) - with pytest.raises(reference_bundle.ReferenceError, match="상대"): - reference_bundle.snapshot(project, ["guide.md"], str(project / "absolute.json")) - assert source.read_text() == "External reference\n" - - -@pytest.mark.parametrize("source", ["../outside.md", "guide.md\n", "guide.md\x00", "missing.md", "guide.md:stream"]) -def test_rejects_invalid_or_missing_sources_without_output(project, source): - with pytest.raises(reference_bundle.ReferenceError): - reference_bundle.snapshot(project, [source], "state/reference.json") - assert not (project / "state").exists() - - -def test_rejects_source_overwrite_duplicate_and_bad_metadata(project): - for sources, output, metadata in [(["guide.md"], "guide.md", {}), - (["guide.md", "./guide.md"], "bundle.json", {}), - (["guide.md"], "bundle.json", {"revision": "x\ny"})]: - with pytest.raises(reference_bundle.ReferenceError): - reference_bundle.snapshot(project, sources, output, **metadata) - assert (project / "guide.md").read_text() == "Original guidance\n" - - -@pytest.mark.parametrize("change", ["schema", "unknown", "source-unknown", "sha", "section", "duplicate", "traversal", "empty"]) -def test_load_rejects_malformed_bundles(project, change): - bundle = reference_bundle.snapshot(project, ["guide.md"], "bundle.json") - source = bundle["sources"][0] - if change == "schema": - bundle["schema"] = True - elif change == "unknown": - bundle["extra"] = "value" - elif change == "source-unknown": - source["content"] = "unrequested copy" - elif change == "sha": - source["sha256"] = "not-a-hash" - elif change == "section": - source["section"] = "bad\tsection" - elif change == "duplicate": - bundle["sources"].append(dict(source)) - elif change == "traversal": - source["path"] = "../outside.md" - else: - bundle["sources"] = [] - (project / "bundle.json").write_text(json.dumps(bundle)) - with pytest.raises(reference_bundle.ReferenceError): - reference_bundle.load(project, "bundle.json") - - -def test_project_path_rejects_symlink_escape(project, tmp_path): - outside = tmp_path / "outside" - outside.mkdir() - try: - (project / "link").symlink_to(outside, target_is_directory=True) - except OSError: - pytest.skip("symlink permission unavailable") - with pytest.raises(reference_bundle.ReferenceError, match="프로젝트 밖"): - reference_bundle.snapshot(project, ["guide.md"], "link/bundle.json") - assert not (outside / "bundle.json").exists() - - -@pytest.mark.parametrize("output,content", [ - ("CLAUDE.md", "# Project guidance\n"), - ("state/questions/confirm-A.json", '{"schema":1,"approval":{"status":"complete"}}'), - ("state/mission.md", "# Mission\n"), - ("plugin.json", '{"name":"example","version":"1.0"}'), - ("source.py", "print('source')\n"), -]) -def test_snapshot_never_overwrites_existing_non_bundle(project, output, content): - destination = project / output - destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_text(content) - expected = reference_bundle.file_pointer(project, output)["sha256"] - for options in ({}, {"expected_sha256": expected}): - with pytest.raises(reference_bundle.ReferenceError): - reference_bundle.snapshot(project, ["guide.md"], output, **options) - assert destination.read_text() == content - - -def test_bundle_refresh_requires_expected_hash_and_preserves_stale_update(project): - reference_bundle.snapshot(project, ["guide.md"], "bundle.json") - before = (project / "bundle.json").read_bytes() - expected = reference_bundle.file_pointer(project, "bundle.json")["sha256"] - (project / "guide.md").write_text("New current guidance\n") - for options in ({}, {"expected_sha256": "0" * 64}): - with pytest.raises(reference_bundle.ReferenceError, match="expect-sha256"): - reference_bundle.snapshot(project, ["guide.md"], "bundle.json", **options) - assert (project / "bundle.json").read_bytes() == before - reference_bundle.snapshot(project, ["guide.md"], "bundle.json", expected_sha256=expected) - assert reference_bundle.check(project, "bundle.json")["status"] == "pass" - with pytest.raises(reference_bundle.ReferenceError, match="expect-sha256"): - reference_bundle.snapshot(project, ["guide.md"], "new.json", expected_sha256=expected) - assert not (project / "new.json").exists() - - -def test_concurrent_bundle_change_before_replace_is_preserved(project, monkeypatch): - reference_bundle.snapshot(project, ["guide.md"], "bundle.json") - expected = reference_bundle.file_pointer(project, "bundle.json")["sha256"] - concurrent = (project / "bundle.json").read_bytes() + b"\n" - original = reference_bundle.file_pointer - def pointer(root, value, external=False): - if value == "guide.md": - (project / "bundle.json").write_bytes(concurrent) - return original(root, value, external) - monkeypatch.setattr(reference_bundle, "file_pointer", pointer) - with pytest.raises(reference_bundle.ReferenceError, match="expect-sha256"): - reference_bundle.snapshot(project, ["guide.md"], "bundle.json", expected_sha256=expected) - assert (project / "bundle.json").read_bytes() == concurrent - assert sorted(path.name for path in project.iterdir()) == ["bundle.json", "guide.md"] diff --git a/tests/integration/mission/test_review_worker.py b/tests/integration/mission/test_review_worker.py deleted file mode 100644 index a9621a0..0000000 --- a/tests/integration/mission/test_review_worker.py +++ /dev/null @@ -1,412 +0,0 @@ -"""Subprocess lifetime tests using newly invented widget review fixtures.""" - -import json -import os -import subprocess -import sys -import time -from pathlib import Path - -import pytest - -from chef.locations import PLUGIN_ROOT -from chef.infrastructure import configuration -from chef.infrastructure.fingerprints import implementation_digest -from chef.infrastructure import process as infrastructure_process -from chef.mission import review_dispatch, review_worker, state -from chef.mission.contracts import EDITABLE_FIELDS, UNIT_HEADER -from chef.mission.storage import read_table -from chef.verification import execution, plan as plans, references -from chef.verification.contracts import VerificationError, digest - -ENTRY = PLUGIN_ROOT / "skills/mission/scripts/mission_state.py" -PACKAGE = PLUGIN_ROOT - - -def python_binary(): - # The Windows Store alias can launch Python but cannot pin executable bytes. - candidate = Path(sys.base_prefix) / "python.exe" if os.name == "nt" else Path(sys.executable) - if not candidate.is_file(): - pytest.skip("hashable Python executable unavailable") - return str(candidate) - - -def eventually(predicate, timeout=12): - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: - value = predicate() - if value: - return value - time.sleep(0.02) - pytest.fail("subprocess did not reach the expected observable checkpoint") - - -@pytest.fixture -def sample(tmp_path, monkeypatch, capsys): - home, root = tmp_path / "home", tmp_path / "widget-project" - home.mkdir() - monkeypatch.setenv("HOME", str(home)) - monkeypatch.setenv("USERPROFILE", str(home)) - monkeypatch.setenv("PYTHONPATH", str(PACKAGE)) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "empty-adapters")) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - adapter = {"schema": 1, "paths": {"stateDir": "state"}, - "verify": {"grades": ["widget-check"]}, "guard": {}} - configuration_dir = root / ".claude/orchestrator" - configuration_dir.mkdir(parents=True) - (configuration_dir / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - (root / "state").mkdir() - (root / "state/ACTIVE").write_text('{"id":"widget","session":"fictional-session"}', encoding="utf-8") - monkeypatch.chdir(root) - for arguments in (("init",), ("unit", "add", "U1", "--goal", "Inspect widget", "--files", "widget.py", - "--done", "Expected value", "--verify", "widget check", "--timebox", "30", "--forbid", "publish")): - assert state.main(["--project", str(root), *arguments]) == 0 - capsys.readouterr() - (root / "widget.py").write_text("value = 3\n", encoding="utf-8") - (root / "plan.json").write_text(json.dumps({"grade": "widget-check", "inputs": ["widget.py"], - "environment": {"target": "fictional"}, "commands": [{"argv": [python_binary(), "-c", "pass"]}]}), encoding="utf-8") - (root / "scope.json").write_text('["widget.py"]', encoding="utf-8") - (root / "findings.json").write_text('[]', encoding="utf-8") - folder = root / "state/widget" - effective_adapter = configuration.read_adapter(configuration.locate(str(root), "claude").adapter_path, "claude") - with execution.workspace_scope(root): - yield root, folder, execution.registry_directory(), effective_adapter - - -def request_file(sample, script="print('widget inspected')", *, timeout=10, limit=1024): - root, folder, _, adapter = sample - (root / "reviewer.py").write_text(script + "\n", encoding="utf-8") - plan = plans.load_plan(root, root / "plan.json", adapter["verify"]["grades"]) - row = read_table(folder / "units.tsv", UNIT_HEADER)[0] - plan["unitBrief"] = {name: row[name] for name in EDITABLE_FIELDS} - argv = [python_binary(), "reviewer.py"] - command = {"argv": argv, "cwd": "."} - before = plans.snapshot(root, plan["inputs"]) - runtime = review_dispatch.runtime_identity(root, command, lambda command: None) - plan_source = references.file_pointer(root, "plan.json") - implementation = implementation_digest() - identity = digest({"project": str(root.resolve()), "plan": plan, "settings": adapter["verify"], - "snapshot": before, "command": command, "runtime": runtime, "references": {}, - "environment": review_dispatch.effective_environment(root, plan), "timeout": timeout, "planSource": plan_source, - "implementation": implementation, "maxLogBytes": limit, "adapter": adapter, "runtimeName": "claude"}) - job = execution.reserve_review(folder, "U1", identity, "widget inspection", ["widget.py"], []) - directory = folder / "verification/review-jobs" / job["key"] / job["token"] - directory.mkdir(parents=True) - path = directory / "request.json" - request = {"schema": 1, "project": str(root), "folder": str(folder), "unit": "U1", "plan": plan, - "settings": adapter["verify"], "adapter": adapter, "runtimeName": "claude", "command": command, - "argv": argv, "timeout": timeout, "before": before, "runtime": runtime, "references": {}, - "requestIdentity": identity, "job": job, "maxLogBytes": limit, "planSource": plan_source, - "implementation": implementation} - path.write_text(json.dumps(request), encoding="utf-8") - return path, request - - -def current_job(sample, request): - return execution.read_record(execution.job_path(execution.job_directory(sample[1]), request["job"]["key"])) - - -def launch_worker(path): - return subprocess.Popen([python_binary(), str(ENTRY), "_review-worker", "--input", str(path)], - stdout=subprocess.PIPE, stderr=subprocess.PIPE) - - -def cli_arguments(root, timeout=10): - return [python_binary(), str(ENTRY), "--project", str(root), "review-run", "U1", "--plan", "plan.json", - "--snapshot", digest(plans.snapshot(root, ["widget.py"])), "--purpose", "widget inspection", - "--scope", "scope.json", "--findings", "findings.json", "--timeout-seconds", str(timeout), - "--", python_binary(), "reviewer.py"] - - -HOLD = """import os, time -from pathlib import Path -Path('child-ready').write_text(str(os.getpid())) -while not Path('release').exists(): - time.sleep(0.02) -print('widget inspected') -""" - - -@pytest.mark.parametrize("script,timeout,exit_code,timed_out", [ - ("print('widget inspected')", 10, 0, False), - ("raise SystemExit(7)", 10, 7, False), - ("import os,time; from pathlib import Path; Path('timed-child').write_text(str(os.getpid())); time.sleep(30)", 1, None, True), -]) -def test_worker_normal_failure_and_timeout_release_child_and_inputs(sample, script, timeout, exit_code, timed_out): - path, request = request_file(sample, script, timeout=timeout) - with launch_worker(path) as worker: - out, err = worker.communicate(timeout=15) - assert worker.returncode == 0, (out, err) - job = current_job(sample, request) - assert job["status"] == "completed" and job.get("child") is None and job.get("launchPending") is False - result = review_dispatch.read_completed(sample[1], job, request["requestIdentity"]) - assert result["exitCode"] == exit_code and result["timedOut"] is timed_out - assert result["status"] == ("completed" if exit_code == 0 else "failed") - if timed_out: - assert not execution.locking.process_alive(int((sample[0] / "timed-child").read_text())) - execution.require_mutation_allowed([sample[0] / "widget.py"]) - assert json.loads((sample[2] / "inputs.json").read_text())["leases"] == [] - with execution.unit_execution_lock(sample[1], "U1"): - pass - - -@pytest.mark.parametrize("mutate", [ - lambda value: value.update(schema=True), - lambda value: value.update(maxLogBytes=2 ** 40), - lambda value: value.update(timeout=0), - lambda value: value.update(argv=["changed-command"]), - lambda value: value.update(requestIdentity="0" * 64), - lambda value: value["job"].update(token="../invalid"), -]) -def test_malformed_request_does_not_claim_job_or_launch(sample, mutate): - path, request = request_file(sample, "from pathlib import Path; Path('unexpected').touch()") - original = current_job(sample, request) - mutate(request) - path.write_text(json.dumps(request), encoding="utf-8") - with pytest.raises(VerificationError): - review_worker.run_from_file(path) - assert execution.read_record(execution.job_path(execution.job_directory(sample[1]), original["key"])) == original - assert not (sample[0] / "unexpected").exists() - - -def test_unknown_fresh_token_cannot_claim_existing_job(sample): - path, request = request_file(sample, "from pathlib import Path; Path('unexpected').touch()") - original = current_job(sample, request) - request["job"]["token"] = "f" * 32 if original["token"] != "f" * 32 else "e" * 32 - fresh = path.parent.parent / request["job"]["token"] / "request.json" - fresh.parent.mkdir() - fresh.write_text(json.dumps(request), encoding="utf-8") - with pytest.raises(VerificationError, match="no longer owned"): - review_worker.run_from_file(fresh) - assert current_job(sample, request) == original - assert not (sample[0] / "unexpected").exists() - - -@pytest.mark.parametrize("raw", [b"[", b"[]", b'{"nested":' * 1500 + b'0' + b'}' * 1500, - b"x" * (review_worker.MAX_REQUEST_BYTES + 1)], - ids=["malformed", "array", "deeply-nested", "oversized"]) -def test_unreadable_or_unbounded_request_does_not_transfer_ownership(sample, raw): - path, request = request_file(sample) - original = current_job(sample, request) - path.write_bytes(raw) - with pytest.raises(VerificationError, match="invalid review supervisor request"): - review_worker.run_from_file(path) - assert current_job(sample, request) == original - - -def test_forged_command_and_recomputed_digest_cannot_reuse_registered_token(sample): - path, request = request_file(sample) - original = current_job(sample, request) - request["argv"] = [python_binary(), "-c", "raise SystemExit(99)"] - request["command"] = {"argv": request["argv"], "cwd": "."} - request["runtime"] = review_dispatch.runtime_identity(sample[0], request["command"], lambda command: None) - request["requestIdentity"] = digest({"project": request["project"], "plan": request["plan"], - "settings": request["settings"], "snapshot": request["before"], "command": request["command"], - "runtime": request["runtime"], "references": request["references"], - "environment": review_dispatch.effective_environment(sample[0], request["plan"]), "timeout": request["timeout"], - "planSource": request["planSource"], "implementation": request["implementation"], - "maxLogBytes": request["maxLogBytes"], "adapter": request["adapter"], "runtimeName": request["runtimeName"]}) - path.write_text(json.dumps(request), encoding="utf-8") - with pytest.raises(VerificationError, match="no longer owned"): - review_worker.run_from_file(path) - assert current_job(sample, request) == original - - -def test_valid_request_cannot_be_claimed_by_a_second_worker(sample): - root, _, _, _ = sample - path, request = request_file(sample, HOLD) - with launch_worker(path) as first: - try: - eventually(lambda: (root / "child-ready").exists()) - owner = current_job(sample, request) - with launch_worker(path) as second: - second.communicate(timeout=8) - assert second.returncode != 0 - assert current_job(sample, request) == owner - assert first.poll() is None - finally: - (root / "release").touch() - out, err = first.communicate(timeout=10) - assert first.returncode == 0, (out, err) - - -@pytest.mark.parametrize("target", ["plan.json", "widget.py", "reviewer.py", "units.tsv"]) -def test_changed_pinned_inputs_prevent_actual_launch(sample, target): - path, request = request_file(sample, "from pathlib import Path; Path('unexpected').touch()") - root, folder, _, _ = sample - source = folder / target if target == "units.tsv" else root / target - text = source.read_text(encoding="utf-8") - source.write_text(text.replace("Inspect widget", "Inspect changed widget") if target == "units.tsv" else text + " ", encoding="utf-8") - with launch_worker(path) as worker: - worker.communicate(timeout=12) - assert worker.returncode != 0 - assert not (root / "unexpected").exists() - assert current_job(sample, request) is None - - -def test_logs_are_capped_while_both_streams_are_still_live(sample): - root, folder, _, _ = sample - path, request = request_file(sample, "import os\nos.write(1,b'a'*250000)\nos.write(2,b'b'*230000)\n" + HOLD, limit=128) - directory = path.parent - with launch_worker(path) as worker: - try: - eventually(lambda: (root / "child-ready").exists()) - assert worker.poll() is None - eventually(lambda: (directory / "stdout.log").stat().st_size == 128) - assert (directory / "stderr.log").stat().st_size == 128 - assert current_job(sample, request)["child"]["pid"] == int((root / "child-ready").read_text()) - with pytest.raises(VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "widget.py"]) - finally: - (root / "release").touch() - out, err = worker.communicate(timeout=12) - assert worker.returncode == 0, (out, err) - result = review_dispatch.read_completed(folder, current_job(sample, request), request["requestIdentity"]) - assert all(result[name]["truncated"] and result[name]["bytes"] == 128 for name in ("stdout", "stderr")) - - -def test_cli_death_leaves_worker_and_input_ownership_live(sample): - root, folder, _, _ = sample - (root / "reviewer.py").write_text(HOLD, encoding="utf-8") - cli = subprocess.Popen(cli_arguments(root), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - try: - eventually(lambda: (root / "child-ready").exists()) - path = next(execution.job_directory(folder).glob("*.json")) - job = execution.read_record(path) - assert job["pid"] != cli.pid and execution.process_owner_alive(job) - cli.kill() - cli.communicate(timeout=5) - duplicate = subprocess.run(cli_arguments(root), capture_output=True, timeout=8) - assert duplicate.returncode == 0, duplicate.stderr - output = json.loads(duplicate.stdout) - assert output["status"] == "running" and not output["dispatched"] - assert output["job"]["token"] == job["token"] - with pytest.raises(VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "widget.py"]) - with pytest.raises(execution.ExecutionBusy): - with execution.unit_execution_lock(folder, "U1"): - pytest.fail("unit lock acquired during live review") - finally: - (root / "release").touch() - if cli.poll() is None: - cli.kill() - cli.communicate(timeout=5) - eventually(lambda: execution.read_record(path).get("status") == "completed") - # Completion is published just before the supervisor exits input_lease(). - # Wait for that separate cleanup checkpoint before asserting write access. - eventually(lambda: not execution.has_input_leases()) - execution.require_mutation_allowed([root / "widget.py"]) - - -def test_worker_death_keeps_registered_live_child_protected(sample): - root, folder, _, _ = sample - path, request = request_file(sample, HOLD) - worker = launch_worker(path) - try: - eventually(lambda: (root / "child-ready").exists()) - child_pid = int((root / "child-ready").read_text()) - worker.kill() - worker.communicate(timeout=5) - stored = current_job(sample, request) - assert stored["child"]["pid"] == child_pid and execution.child_alive(stored) - duplicate = execution.reserve_review(folder, "U1", request["requestIdentity"], "widget inspection", ["widget.py"], []) - assert not duplicate["acquired"] and duplicate["token"] == request["job"]["token"] - with pytest.raises(VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "widget.py"]) - with pytest.raises(execution.ExecutionBusy): - with execution.unit_execution_lock(folder, "U1"): - pytest.fail("unit lock acquired with surviving child") - finally: - (root / "release").touch() - if worker.poll() is None: - worker.kill() - worker.communicate(timeout=5) - - -def test_worker_death_between_spawn_and_registration_requires_recovery(sample): - root, folder, _, _ = sample - path, request = request_file(sample, HOLD) - script = "from chef.verification import execution; from chef.mission import review_worker; import os,sys; " \ - "execution.register_job_child=lambda *a: os._exit(77); review_worker.run_from_file(sys.argv[1])" - with subprocess.Popen([python_binary(), "-c", script, str(path)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as worker: - try: - worker.communicate(timeout=8) - assert worker.returncode == 77 - eventually(lambda: (root / "child-ready").exists()) - stored = current_job(sample, request) - assert stored["launchPending"] is True and stored["child"] is None - duplicate = execution.reserve_review(folder, "U1", request["requestIdentity"], "widget inspection", ["widget.py"], []) - assert not duplicate["acquired"] - with pytest.raises(VerificationError, match="protected execution input"): - execution.require_mutation_allowed([root / "widget.py"]) - finally: - (root / "release").touch() - - -def test_bounded_process_reports_seen_and_retained_bytes(sample): - root, folder, _, _ = sample - _, request = request_file(sample) - job = execution.transfer_job(folder, request["job"]["key"], request["job"]["token"], os.getpid()) - with execution.input_lease([root / "widget.py"]) as lease: - code, timed_out, counts = review_worker.bounded_process( - [python_binary(), "-c", "import os; os.write(1,b'a'*170000); os.write(2,b'b'*190000)"], - root, root / "stdout", root / "stderr", 5, 91, folder=folder, job=job, lease=lease) - assert code == 0 and timed_out is False - assert counts == [{"seen": 170000, "written": 91}, {"seen": 190000, "written": 91}] - execution.finish_job(folder, job["key"], job["token"], release=True) - - -@pytest.mark.parametrize("key", ["PATH", "PWD"]) -def test_declared_environment_identifies_the_actual_reviewer_child_environment(sample, monkeypatch, key): - root, folder, _, _ = sample - plan_path = root / "plan.json" - plan = json.loads(plan_path.read_text(encoding="utf-8")) - plan["environmentKeys"] = [key] - plan_path.write_text(json.dumps(plan), encoding="utf-8") - (root / "reviewer.py").write_text( - "import json,os\nprint(json.dumps({" + repr(key) + ":os.environ.get(" + repr(key) + ")}))\n", encoding="utf-8") - # Include the machine's ordinary child-only bins before adding a fresh, - # existing fixture bin in the real caller subprocess. The new bin must be - # added once by child_env and remain identical in worker/reviewer children. - monkeypatch.setenv("PATH", infrastructure_process.child_env(str(root))["PATH"]) - extra_bin = root / "fixture-bin" - extra_bin.mkdir() - monkeypatch.setenv("PWD", str(root.parent / "different-working-directory")) - launcher = "import os,sys; from chef.infrastructure import process; " \ - "from chef.mission import state; process.P4_INSTALLATIONS=[os.path.join(sys.argv[1],'p4')]; " \ - "raise SystemExit(state.main(sys.argv[2:]))" - command = [python_binary(), "-c", launcher, str(extra_bin), *cli_arguments(root)[2:]] - completed = subprocess.run(command, capture_output=True, timeout=15) - assert completed.returncode == 0, completed.stderr - result = json.loads(completed.stdout)["result"] - stdout_path = references.resolve_path(folder, result["stdout"]["file"]["path"]) - observed = json.loads(stdout_path.read_text(encoding="utf-8"))[key] - expected = os.pathsep.join([str(extra_bin), os.environ["PATH"]]) if key == "PATH" else str(root) - assert observed == expected - assert result["status"] == "completed" and result["exitCode"] == 0 - reused = subprocess.run(command, capture_output=True, timeout=15) - assert reused.returncode == 0, reused.stderr - reused_output = json.loads(reused.stdout) - assert reused_output["dispatched"] is False and reused_output["result"] == result - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX process-group cleanup requires POSIX") -def test_timeout_stops_owned_process_group_including_pipe_holding_child(sample): - descendant = "import time; from pathlib import Path; time.sleep(3); Path('escaped-timeout').touch()" - script = "import subprocess,sys,time\nfrom pathlib import Path\np=subprocess.Popen([sys.executable,'-c'," \ - + repr(descendant) + "])\nPath('descendant-ready').write_text(str(p.pid))\ntime.sleep(30)" - path, request = request_file(sample, script, timeout=1) - with launch_worker(path) as worker: - out, err = worker.communicate(timeout=12) - assert worker.returncode == 0, (out, err) - assert (sample[0] / "descendant-ready").exists() - child_pid = int((sample[0] / "descendant-ready").read_text()) - if sys.platform.startswith("linux"): - status = Path(f"/proc/{child_pid}/stat") - assert not status.exists() or status.read_text().rsplit(")", 1)[1].split()[0] == "Z" - else: - inspected = subprocess.run(["ps", "-o", "stat=", "-p", str(child_pid)], capture_output=True, timeout=5) - assert inspected.returncode != 0 or not inspected.stdout.strip() or inspected.stdout.strip().startswith(b"Z") - result = review_dispatch.read_completed(sample[1], current_job(sample, request), request["requestIdentity"]) - assert result["timedOut"] is True - assert not (sample[0] / "escaped-timeout").exists() diff --git a/tests/integration/mission/test_routing.py b/tests/integration/mission/test_routing.py deleted file mode 100644 index 09c795e..0000000 --- a/tests/integration/mission/test_routing.py +++ /dev/null @@ -1,85 +0,0 @@ -from pathlib import Path - -from chef.mission import routing as routing - -from tests.paths import PLUGIN_ROOT - - -def row(strategy, success, condition='same', **kwargs): - return {'strategy': strategy, 'success': success, 'conditionKey': condition, - 'runtime': 'codex', 'model': 'synthetic', 'kind': 'single', 'taskKind': 'implementation', **kwargs} - - -def test_unknown_observatory_outcomes_do_not_imply_success(): - result = routing.analyze_records([row('base', None), row('other', None)], 'base') - assert result['comparisons'][0]['status'] == 'insufficient_evidence' - assert result['strata'][0]['successRate'] is None - assert result['diagnostics']['unknown_outcomes'] == 2 - - -def test_matched_quality_gain_requires_enough_candidate_trials(): - rows = [row('base', False) for _ in range(40)] + [row('other', True) for _ in range(40)] - result = routing.analyze_records(rows, 'base') - assert result['comparisons'][0]['status'] == 'measured_quality_gain' - assert result['comparisons'][0]['usageComparison'] == 'unknown' - assert result['credits'] is None - - -def test_conditions_and_task_kind_prevent_confounded_pooling(): - rows = [row('base', False, 'hard') for _ in range(40)] + [row('other', True, 'easy') for _ in range(40)] - result = routing.analyze_records(rows, 'base') - assert all(item['status'] == 'unmatched_condition' for item in result['comparisons']) - result = routing.analyze_records([row('base', True), row('other', True, taskKind='review')], 'base') - assert result['coverage']['matchedComparisons'] == 0 - - -def test_fixtures_low_n_and_no_improvement_are_honest(): - result = routing.analyze_records([row('base', False), row('other', True)], 'base') - assert result['comparisons'][0]['status'] == 'insufficient_evidence' - rows = [row('base', False) for _ in range(40)] + [row('other', True, kind='fixture') for _ in range(40)] - assert routing.analyze_records(rows, 'base')['comparisons'][0]['status'] == 'fixture_only' - rows = [row(name, True) for name in ('base', 'other') for _ in range(40)] - assert routing.analyze_records(rows, 'base')['comparisons'][0]['status'] == 'no_demonstrated_improvement' - - -def test_partial_token_coverage_prevents_efficiency_comparison(): - rows = [row('base', True, tokens={'input_tokens': 10}), row('other', True, tokens={})] - assert routing.analyze_records(rows, 'base')['comparisons'][0]['usageComparison'] == 'unknown' - - -def test_lab_uses_holdout_only_and_candidate_count_not_case_count(): - def candidate(name, passed=100): - return {'generation': 1, 'strategy': {'name': name, 'kind': 'fixture', 'runtime': 'unknown', - 'model': 'unknown', 'effort': 'unknown'}, - 'passed': 0, 'total': 100, 'holdout': {'passed': passed, 'total': 100, 'seconds': .1}} - lab = {'schema': 1, 'phase': 'complete', 'evaluator': 'test-v1', 'holdoutHash': 'same', - 'results': [candidate('base'), candidate('other')], 'config': {}} - result = routing.analyze_lab(lab, 'base') - assert result['comparisons'][0]['baselineSummary']['knownOutcomes'] == 1 - assert result['comparisons'][0]['baselineSummary']['successRate'] == 1 - assert result['comparisons'][0]['status'] == 'fixture_only' - lab['phase'] = 'prepared' - assert routing.analyze_lab(lab, 'base')['coverage']['excludedCandidates'] == 2 - - -def test_missing_explicit_baseline_or_condition_does_not_guess(): - result = routing.analyze_records([row('easy-single', True)]) - assert result['comparisons'] == [] - assert result['diagnostics']['missing_explicit_baseline'] == 1 - result = routing.analyze_records([{'strategy': 'single', 'success': True}]) - assert result['coverage']['eligibleRecords'] == 0 - - -def test_replicated_lab_strategy_runs_can_reach_recommendation_threshold(): - candidates = [] - for name, passed in (('base', 0), ('other', 100)): - for _ in range(5): - candidates.append({'generation': 1, 'strategy': {'name': name, 'kind': 'single', - 'runtime': 'codex', 'model': 'configured-only', 'effort': 'medium'}, - 'holdout': {'passed': passed, 'total': 100, 'seconds': .1}}) - report = {'schema': 1, 'phase': 'complete', 'evaluator': 'synthetic-test', - 'holdoutHash': 'same-condition', 'results': candidates, 'config': {}} - result = routing.analyze_lab(report, 'base') - assert result['comparisons'][0]['status'] == 'measured_quality_gain' - assert result['comparisons'][0]['baselineSummary']['knownOutcomes'] == 5 - assert result['modelMetadataBasis'] == 'configured_strategy_not_observed_runtime' diff --git a/tests/integration/mission/test_state_efficiency.py b/tests/integration/mission/test_state_efficiency.py deleted file mode 100644 index c0052fd..0000000 --- a/tests/integration/mission/test_state_efficiency.py +++ /dev/null @@ -1,451 +0,0 @@ -"""Fictional mission fixtures for contract/evidence efficiency contracts.""" - -import json -import sys -from pathlib import Path - -import pytest - -from chef.mission import state -from chef.mission import unit_contracts -from chef.verification import references - - -@pytest.fixture -def sample(tmp_path, monkeypatch, capsys): - root = tmp_path / "project" - adapter = root / ".claude/orchestrator" - adapter.mkdir(parents=True) - (adapter / "adapter.json").write_text(json.dumps({ - "schema": 1, "paths": {"stateDir": "state"}, - "verify": {"grades": ["sample-pass"]}, "guard": {}, - }), encoding="utf-8") - (root / "state").mkdir() - (root / "state/ACTIVE").write_text('{"id":"sample","session":"fictional-session"}') - monkeypatch.chdir(root) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "none")) - - def run(*args): - capsys.readouterr() - code = state.main(["--project", str(root), *args]) - output = capsys.readouterr() - return code, output.out.strip(), output.err.strip() - - assert run("init")[0] == 0 - assert run("unit", "add", "U1", "--goal", "Check widget", "--files", "widget.py", - "--done", "Expected value", "--verify", "sample checks", "--timebox", "30", - "--forbid", "publish")[0] == 0 - assert run("unit", "set", "U1", "--status", "doing")[0] == 0 - (root / "widget.py").write_text("value = 7\n") - (root / "plan.json").write_text(json.dumps({"grade": "sample-pass", "inputs": ["widget.py"], "environment": {"target": "fictional"}, - "commands": [{"argv": [sys.executable, "-c", "pass"]}]})) - return root, root / "state/sample", run - - -def receipt_path(folder): - return Path(json.loads((folder / "verification/U1.latest.json").read_text())["receipt"]) - - -def test_effective_noop_preserves_all_mission_files(sample): - root, folder, run = sample - assert run("verify", "U1", "--plan", "plan.json")[0] == 0 - before = {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in folder.rglob("*") if path.is_file()} - code, out, err = run("unit", "set", "U1", "--goal", " Check widget ", "--timebox", "030", "--status", "doing") - assert code == 0 and "no-op" in out and not err - assert before == {path: (path.read_bytes(), path.stat().st_mtime_ns) for path in folder.rglob("*") if path.is_file()} - assert not (folder / "contracts").exists() - - -def test_contract_edit_preserves_pass_and_reports_reverification(sample): - root, folder, run = sample - assert run("verify", "U1", "--plan", "plan.json")[0] == 0 - receipt = receipt_path(folder) - preserved = receipt.read_bytes() - assert run("ledger", "record", "U1", "--status", "pass", "--grade", "sample-pass", - "--evidence", "fictional recorded pass")[0] == 0 - ledger = (folder / "ledger.tsv").read_bytes() - code, output, _ = run("unit", "set", "U1", "--done", "Updated expected value") - assert code == 0 - change = json.loads(output.splitlines()[-1])["contractChange"] - assert change["reverificationNeeded"] is True - assert change["old"]["version"] == 1 and change["new"]["version"] == 2 - assert change["old"]["sha256"] != change["new"]["sha256"] - assert change["previousReceipt"] == str(receipt) - assert receipt.read_bytes() == preserved and (folder / "ledger.tsv").read_bytes() == ledger - assert "reverification needed" in run("status")[1] - assert json.loads(run("brief", "U1")[1])["contract"]["reverificationNeeded"] is True - assert run("verify", "U1", "--plan", "plan.json")[0] == 0 - latest = receipt_path(folder) - assert latest != receipt - assert json.loads(latest.read_text())["plan"]["unitContract"] == change["new"] - assert json.loads(run("brief", "U1")[1])["contract"]["reverificationNeeded"] is False - - -def test_edit_then_revert_does_not_resurrect_old_receipt(sample, monkeypatch): - root, folder, run = sample - assert run("verify", "U1", "--plan", "plan.json")[0] == 0 - old = receipt_path(folder) - assert run("unit", "set", "U1", "--done", "Other value")[0] == 0 - assert run("unit", "set", "U1", "--done", "Expected value")[0] == 0 - monkeypatch.setattr(state.verification, "validate_receipt", lambda *a, **k: None) - monkeypatch.setattr(state.verification, "validate_latest", lambda *a, **k: None) - code, _, err = run("complete", "U1", "--receipt", str(old), "--review", "unused", "--done-evidence", "sample") - assert code == 1 and "contract version" in err - saved = json.loads((folder / "contracts/U1.json").read_text()) - assert saved["current"]["version"] == 3 and len(saved["history"]) == 2 - - -def write_evidence(root, files): - (root / "evidence.json").write_text(json.dumps({"schema": 1, "files": files})) - - -def test_ledger_structured_and_legacy_evidence_audit_is_read_only_and_bounded(sample): - root, folder, run = sample - (root / "report.log").write_text("fictional check completed") - (root / "result.json").write_text('{"result":"fictional"}') - write_evidence(root, [{"path": "report.log", "kind": "log"}, {"path": "result.json", "kind": "report"}]) - assert run("ledger", "record", "U1", "--status", "pass", "--grade", "sample-pass", - "--evidence-input", "evidence.json", "--evidence", "Two fictional checks")[0] == 0 - assert run("ledger", "record", "U1", "--status", "retry", "--grade", "sample-pass", "--evidence", "old note")[0] == 0 - code, output, _ = run("ledger", "audit") - result = json.loads(output) - assert code == 0 and result["semanticValidity"] == "not_checked" - assert result["counts"]["legacyRows"] == 1 and result["counts"]["checkedFiles"] == 2 - (root / "report.log").unlink() - (root / "result.json").write_text("changed") - before = {path: path.read_bytes() for path in folder.rglob("*") if path.is_file()} - code, output, _ = run("ledger", "audit", "--limit", "1") - result = json.loads(output) - assert code == 1 and result["counts"]["missing"] == result["counts"]["changed"] == 1 - assert len(result["issues"]) == 1 and result["omitted"] == 1 - assert before == {path: path.read_bytes() for path in folder.rglob("*") if path.is_file()} - - -@pytest.mark.parametrize("item", [{"path": "absent", "kind": "log"}, {"path": "widget.py", "kind": ""}, - {"path": "widget.py", "kind": "file", "sha256": "0" * 64}, {"path": "../outside", "kind": "file"}]) -def test_evidence_validation_rejects_without_ledger_write(sample, item): - root, folder, run = sample - before = (folder / "ledger.tsv").read_bytes() - write_evidence(root, [item]) - assert run("ledger", "record", "U1", "--status", "pass", "--grade", "sample-pass", "--evidence-input", "evidence.json")[0] == 1 - assert (folder / "ledger.tsv").read_bytes() == before - - -def test_frozen_reference_keeps_immutable_content_and_reports_live_drift(sample): - root, _, run = sample - (root / "guide.md").write_text("Fictional rules version one\n") - code, output, _ = run("reference", "snapshot", "--source", "guide.md", "--output", "references.json", "--freeze") - assert code == 0 - source = json.loads(output)["sources"][0] - assert source["path"] == "guide.md" and source["frozen"]["sha256"] == source["sha256"] - frozen = root / source["frozen"]["path"] - preserved = frozen.read_bytes() - (root / "guide.md").write_text("Fictional rules version two\n") - checked = references.check(root, "references.json") - assert checked["status"] == "pass" and checked["liveSources"]["changed"] == ["guide.md"] - assert frozen.read_bytes() == preserved - old_hash = references.file_pointer(root, "references.json")["sha256"] - updated = references.snapshot(root, ["guide.md"], "references.json", expected_sha256=old_hash, freeze=True) - assert updated["sources"][0]["frozen"]["path"] != source["frozen"]["path"] - assert frozen.read_bytes() == preserved - with pytest.raises(references.ReferenceError, match="expect-sha256"): - references.snapshot(root, ["guide.md"], "references.json", expected_sha256=old_hash, freeze=True) - - -def test_frozen_object_corruption_or_escape_is_rejected(sample): - root, _, _ = sample - bundle = references.snapshot(root, ["widget.py"], "refs.json", freeze=True) - source = bundle["sources"][0] - frozen = root / source["frozen"]["path"] - frozen.write_text("corrupt") - assert references.check(root, "refs.json")["status"] == "fail" - with pytest.raises(references.ReferenceError, match="hash"): - references.snapshot(root, ["widget.py"], "second.json", freeze=True) - source["frozen"]["path"] = "../outside" - (root / "refs.json").write_text(json.dumps(bundle)) - with pytest.raises(references.ReferenceError): - references.load(root, "refs.json") - - -def test_coordinator_ineligible_does_not_create_receipt_or_execute(sample, monkeypatch): - root, folder, run = sample - def forbidden(*args, **kwargs): - pytest.fail("ineligible coordinator executed commands") - monkeypatch.setattr(state.verification, "run", forbidden) - code, _, err = run("verify", "U1", "--plan", "plan.json", "--coordinator") - assert code == 1 and err - assert not list((folder / "verification").glob("*.json")) - - -def review_args(root, *, text="print('fictional review output')"): - from chef.verification.contracts import digest - from chef.verification.plan import snapshot - python = Path(sys.prefix) / ("python.exe" if sys.platform == "win32" else "bin/python") - if not python.is_file(): - python = Path(sys.executable) - (root / "scope.json").write_text('["widget.py"]') - (root / "findings.json").write_text('[]') - (root / "reviewer.py").write_text("from pathlib import Path\np=Path('review-count')\np.write_text(p.read_text()+'x' if p.exists() else 'x')\n" + text + "\n") - return ["review-run", "U1", "--plan", "plan.json", "--snapshot", digest(snapshot(root, ["widget.py"])), - "--purpose", "fictional independent inspection", "--scope", "scope.json", "--findings", "findings.json", - "--", str(python), "reviewer.py"] - - -def test_review_run_reuses_completed_job_without_clean_verdict(sample): - root, folder, run = sample - args = review_args(root) - code, output, err = run(*args) - assert code == 0, (output, err) - first = json.loads(output) - assert first["dispatched"] is True and first["reviewVerdict"] == "not_recorded" - assert first["result"]["status"] == "completed" - assert not (folder / "verification/U1.review.latest.json").exists() - code, output, err = run(*args) - assert code == 0, err - second = json.loads(output) - assert second["dispatched"] is False and second["job"]["key"] == first["job"]["key"] - assert (root / "review-count").read_text() == "x" - - -def test_review_reuse_requires_unchanged_output_hash(sample): - root, folder, run = sample - args = review_args(root) - code, output, err = run(*args) - assert code == 0, err - result = json.loads(output) - log = folder / result["result"]["stdout"]["file"]["path"] - log.write_text("tampered") - code, _, err = run(*args) - assert code == 1 and "changed" in err - assert (root / "review-count").read_text() == "x" - - -def test_review_snapshot_and_tool_changes_cannot_reuse_previous_job(sample): - root, _, run = sample - args = review_args(root) - assert run(*args)[0] == 0 - (root / "widget.py").write_text("value = 8\n") - code, _, err = run(*args) - assert code == 1 and "stale" in err - assert (root / "review-count").read_text() == "x" - (root / "widget.py").write_text("value = 7\n") - (root / "reviewer.py").write_text((root / "reviewer.py").read_text() + "print('changed tool')\n") - code, output, err = run(*args) - assert code == 0, err - assert json.loads(output)["dispatched"] is True - assert (root / "review-count").read_text() == "xx" - - -def test_review_failed_dispatch_is_never_clean_and_retains_result(sample): - root, folder, run = sample - args = review_args(root, text="raise SystemExit(4)") - code, output, err = run(*args) - assert code == 1 and not err - result = json.loads(output) - assert result["result"]["exitCode"] == 4 and result["reviewVerdict"] == "not_recorded" - code, output, _ = run(*args) - assert code == 1 and json.loads(output)["dispatched"] is False - assert (root / "review-count").read_text() == "x" - assert not (folder / "verification/U1.review.latest.json").exists() - - -def test_review_bounded_log_pointers(sample, monkeypatch): - from chef.mission import review_dispatch - root, folder, run = sample - monkeypatch.setattr(review_dispatch, "MAX_LOG_BYTES", 64) - args = review_args(root, text="print('x'*1000)") - code, output, err = run(*args) - assert code == 0, err - log = json.loads(output)["result"]["stdout"] - assert log["truncated"] is True and log["bytes"] == 64 - assert (folder / log["file"]["path"]).stat().st_size == 64 - assert "x" * 100 not in output - - -def test_review_duplicate_running_job_does_not_dispatch(sample, monkeypatch): - from chef.mission import review_dispatch - root, _, run = sample - args = review_args(root) - def reserve(*_args, **_kwargs): - return {"key": "a" * 64, "token": "fictional-token", "pid": 123, - "status": "running", "acquired": False} - monkeypatch.setattr(review_dispatch.execution, "reserve_review", reserve) - code, output, err = run(*args) - assert code == 0, err - result = json.loads(output) - assert result["status"] == "running" and result["dispatched"] is False - assert not (root / "review-count").exists() - - -def test_unit_mutation_and_completion_reject_active_execution(sample): - from chef.verification import execution - root, folder, run = sample - before = (folder / "units.tsv").read_bytes() - with execution.unit_execution_lock(folder, "U1"): - code, output, err = run("unit", "set", "U1", "--done", "New condition") - assert code == 1 and not err - assert json.loads(output)["category"] == "execution_busy" - code, output, _ = run("complete", "U1", "--receipt", "unused", "--review", "unused", "--done-evidence", "fictional") - assert code == 1 and json.loads(output)["category"] == "execution_busy" - assert (folder / "units.tsv").read_bytes() == before - assert not (folder / "contracts/U1.json").exists() - - -def test_unit_write_failure_rolls_back_contract_sidecar(sample, monkeypatch): - root, folder, run = sample - before = (folder / "units.tsv").read_bytes() - def fail_write(*_args): - raise OSError("fictional storage failure") - monkeypatch.setattr(state, "write_table", fail_write) - code, _, err = run("unit", "set", "U1", "--goal", "Other goal") - assert code == 1 and "storage failure" in err - assert (folder / "units.tsv").read_bytes() == before - assert not (folder / "contracts/U1.json").exists() - - -@pytest.mark.parametrize("stage", ["before-unit", "after-unit"]) -@pytest.mark.parametrize("existing", [False, True]) -def test_contract_journal_survives_actual_process_kill(sample, stage, existing): - import os - import queue - import subprocess - import threading - root, folder, run = sample - if existing: - assert run("unit", "set", "U1", "--goal", "Earlier goal")[0] == 0 - old_brief = json.loads(run("brief", "U1")[1]) - script = ''' -import sys, threading -from chef.mission import state, unit_contracts -stage, project = sys.argv[1:] -def pause(): - print("transition-ready", flush=True) - threading.Event().wait(30) -if stage == "before-unit": - original = unit_contracts.save - def save(folder, row, value): - original(folder, row, value) - if "transition" in value: - pause() - unit_contracts.save = save -else: - original = state.write_table - def write(*args): - original(*args) - pause() - state.write_table = write -state.main(["--project", project, "unit", "set", "U1", "--goal", "Interrupted goal"]) -''' - env = {**os.environ, "PYTHONPATH": str(Path(state.__file__).parents[2])} - child = subprocess.Popen([sys.executable, "-c", script, stage, str(root)], env=env, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) - ready = queue.Queue() - threading.Thread(target=lambda: ready.put(child.stdout.readline()), daemon=True).start() - try: - assert ready.get(timeout=10).strip() == "transition-ready" - child.kill() - child.wait(timeout=10) - finally: - if child.poll() is None: - child.kill() - child.wait(timeout=10) - child.stdout.close() - child.stderr.close() - code, output, err = run("brief", "U1") - assert code == 0, err - current = json.loads(output) - assert current["goal"] == (old_brief["goal"] if stage == "before-unit" else "Interrupted goal") - assert run("unit", "set", "U1", "--goal", "Recovered goal")[0] == 0 - saved = json.loads((folder / "contracts/U1.json").read_text()) - assert "transition" not in saved - assert json.loads(run("brief", "U1")[1])["goal"] == "Recovered goal" - - -def test_review_bundle_recapture_at_same_path_changes_request_identity(sample): - root, _, run = sample - (root / "guide.md").write_text("Fictional guide") - references.snapshot(root, ["guide.md"], "references.json", revision="one") - plan = json.loads((root / "plan.json").read_text()) - plan["referenceBundle"] = "references.json" - (root / "plan.json").write_text(json.dumps(plan)) - args = review_args(root) - code, output, err = run(*args) - assert code == 0, err - old = json.loads(output)["job"]["key"] - expected = references.file_pointer(root, "references.json")["sha256"] - references.snapshot(root, ["guide.md"], "references.json", revision="two", expected_sha256=expected) - code, output, err = run(*args) - assert code == 0, err - result = json.loads(output) - assert result["dispatched"] is True and result["job"]["key"] != old - assert (root / "review-count").read_text() == "xx" - - -def test_reference_read_targets_separate_frozen_pointer_and_provenance(sample): - root, _, run = sample - (root / "guide.md").write_text("Fictional frozen guidance") - references.snapshot(root, ["guide.md"], "references.json", freeze=True) - (root / "guide.md").write_text("Changed live guidance") - for output in (run("reference", "show", "--input", "references.json")[1], - run("brief", "U1", "--references", "references.json")[1]): - read = json.loads(output)["readSources"][0] - assert read["mode"] == "frozen" - assert read["path"].startswith(".reference-objects/sha256/") - assert read["provenance"]["path"] == "guide.md" - assert (root / read["path"]).read_text() == "Fictional frozen guidance" - - -def test_coordinator_explicit_path_always_executes_new_checks(sample): - from chef.verification import plan as plans - root, folder, run = sample - python = Path(sys.prefix) / ("python.exe" if sys.platform == "win32" else "bin/python") - if not python.is_file(): - python = Path(sys.executable) - (root / "tiny-check.py").write_text("from pathlib import Path\np=Path('tiny-runs')\np.write_text(p.read_text()+'x' if p.exists() else 'x')\n") - command = {"argv": [str(python), "tiny-check.py"], "cwd": ".", "reusable": True, - "inputs": ["widget.py", "tiny-check.py"], "outputs": []} - plan = {"grade": "sample-pass", "inputs": ["widget.py", "tiny-check.py"], - "environment": {"target": "fictional"}, "commands": [command]} - (root / "plan.json").write_text(json.dumps(plan)) - adapter_file = root / ".claude/orchestrator/adapter.json" - adapter = json.loads(adapter_file.read_text()) - adapter["verify"]["coordinatorChecks"] = [{"grade": "sample-pass", "commands": [ - {"argv": command["argv"], "cwd": ".", "tools": plans.command_runtime(root, command)["tools"]}]}] - adapter_file.write_text(json.dumps(adapter)) - for _ in range(2): - code, output, err = run("verify", "U1", "--plan", "plan.json", "--coordinator") - assert code == 0, err - receipt = json.loads(receipt_path(folder).read_text()) - assert receipt["executionCounts"]["executed"] == 1 and receipt["executionCounts"]["reused"] == 0 - assert (root / "tiny-runs").read_text() == "xx" - - -def test_review_bundle_change_during_dispatch_cannot_pass(sample): - root, _, run = sample - (root / "guide.md").write_text("Fictional guide") - references.snapshot(root, ["guide.md"], "references.json", revision="one") - plan = json.loads((root / "plan.json").read_text()) - plan["referenceBundle"] = "references.json" - (root / "plan.json").write_text(json.dumps(plan)) - args = review_args(root, text="import json\np=Path('references.json')\nb=json.loads(p.read_text())\nb['sources'][0]['revision']='two'\np.write_text(json.dumps(b))") - code, output, err = run(*args) - assert code == 1, (output, err) - result = json.loads(output) - assert result["result"]["exitCode"] == 0 and result["result"]["inputsUnchanged"] is False - assert result["result"]["status"] == "failed" and result["reviewVerdict"] == "not_recorded" - - -def test_contract_journal_retained_if_writer_raises_after_replacing_tsv(sample, monkeypatch): - root, folder, run = sample - original = state.write_table - def after_replace(*args): - original(*args) - raise OSError("fictional post-replace failure") - monkeypatch.setattr(state, "write_table", after_replace) - code, _, err = run("unit", "set", "U1", "--goal", "Committed before error") - assert code == 1 and "post-replace" in err - code, output, err = run("brief", "U1") - assert code == 0, err - assert json.loads(output)["goal"] == "Committed before error" - assert "transition" in json.loads((folder / "contracts/U1.json").read_text()) diff --git a/tests/integration/mission/test_supervisor.py b/tests/integration/mission/test_supervisor.py deleted file mode 100644 index 65c4bb0..0000000 --- a/tests/integration/mission/test_supervisor.py +++ /dev/null @@ -1,412 +0,0 @@ -import copy -import json -import sys -from pathlib import Path - -import pytest -from chef.mission import supervisor as sup - -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture -def setup(tmp_path, monkeypatch): - project = tmp_path / "fictional-project" - project.mkdir() - config = {"schema": 1, "projects": {"demo": {"path": str(project), "slots": ["one", "two"], - "runtimes": ["codex", "grok"], "resources": []}}, - "budgets": {"maxRuns": 4, "maxConcurrent": 2, "maxSeconds": 100, "launchTimeoutSeconds": 10}} - config_path = tmp_path / "config.json" - config_path.write_text(json.dumps(config)) - monkeypatch.setenv("CHEF_SUPERVISOR_HOME", str(tmp_path / "supervisor")) - for key in ("CODEX_HOME", "CLAUDE_CONFIG_DIR", "GROK_HOME"): - monkeypatch.setenv(key, str(tmp_path / key.lower())) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "unused-registry")) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - state_path = tmp_path / "supervisor" / "queue.json" - state = sup.load_state(state_path, config, now=100) - - def observer(registered, slot, runtime, mission=""): - return {"path": str(tmp_path / "slots" / slot), "ready": True, "active": "", "session": "", - "corrupt": False, "missions": [], "completed": False, "interrupted": False} - return config, state, observer, config_path, state_path - - -def add(state, config, task_id="first", **kwargs): - return sup.enqueue(state, config, task_id, "demo", "Build fictional counter", **kwargs) - - -def test_priority_dependencies_and_cycle_validation(setup): - config, state, observer, *_ = setup - add(state, config) - add(state, config, "dependent", priority=50, after=["first"]) - add(state, config, "urgent", priority=10) - result = sup.plan(state, config, observer, lambda _: True, now=101) - assert [item["id"] for item in result["dispatch"]] == ["urgent", "first"] - assert result["blocked"]["dependent"] == "dependencies incomplete" - state["tasks"][0]["after"] = ["dependent"] - with pytest.raises(sup.SupervisorError, match="cycle"): - sup.validate_state(state, config) - - -@pytest.mark.parametrize("kwargs", [{"after": ["missing"]}, {"runtime": "claude"}, {"after": ["first"]}]) -def test_enqueue_rejects_invalid_contract_without_partial_mutation(setup, kwargs): - config, state, *_ = setup - with pytest.raises(sup.SupervisorError): - add(state, config, **kwargs) - assert state["tasks"] == [] - - -@pytest.mark.parametrize("goal", ["", "bad\nline", 'bad"quote', "bad\x00null"]) -def test_goals_cannot_break_slot_task_contract(setup, goal): - config, state, *_ = setup - with pytest.raises(sup.SupervisorError): - sup.enqueue(state, config, "first", "demo", goal) - - -@pytest.mark.parametrize("change", ["busy", "corrupt", "unready", "unavailable"]) -def test_plan_fails_closed_without_launch_or_mutation(setup, change): - config, state, observer, *_ = setup - add(state, config) - before = copy.deepcopy(state) - def changed(*args): - view = observer(*args) - view.update(active="other" if change == "busy" else "", corrupt=change == "corrupt", - ready=change != "unready") - return view - result = sup.dispatch(state, config, lambda _: pytest.fail("saved"), observer=changed, - readiness=lambda _: change != "unavailable", now=101, - launcher=lambda *_: pytest.fail("launched")) - assert not result["dispatch"] - assert state == before - - -def test_durable_reservation_precedes_launcher_and_holds_both_slots(setup): - config, state, observer, _, state_path = setup - add(state, config) - add(state, config, "second") - launched = [] - def launcher(task, project): - disk = json.loads(state_path.read_text()) - saved = next(t for t in disk["tasks"] if t["id"] == task["id"]) - assert saved["status"] == "reserved" - assert disk["runs"] == len(launched) + 1 - launched.append(task["assignment"]["slot"]) - return 0 - sup.dispatch(state, config, lambda value: sup.atomic_write(state_path, value), True, - observer, lambda _: True, launcher, now=101) - assert launched == ["one", "two"] - assert all(task["status"] == "launched" for task in state["tasks"]) - add(state, config, "third") - assert not sup.plan(state, config, observer, lambda _: True, now=102)["dispatch"] - - -@pytest.mark.parametrize("collision", ["resource", "alias", "nested"]) -def test_resource_and_canonical_path_collisions(setup, collision): - config, state, observer, *_ = setup - if collision == "resource": - config["projects"]["demo"]["resources"] = ["shared-editor"] - state["configHash"] = sup.digest(config) - add(state, config) - add(state, config, "second") - def changed(*args): - view = observer(*args) - if collision != "resource": - view["path"] = str(Path(view["path"]).parent / "one") - if collision == "nested" and args[1] == "two": - view["path"] += "/nested" - return view - assert len(sup.plan(state, config, changed, lambda _: True, now=101)["dispatch"]) == 1 - - -@pytest.mark.parametrize("key,value", [("maxRuns", 1), ("maxConcurrent", 1), ("maxSeconds", 1)]) -def test_budgets_bound_launches(setup, key, value): - config, state, observer, *_ = setup - config["budgets"][key] = value - state["configHash"] = sup.digest(config) - add(state, config) - add(state, config, "second") - planned = sup.plan(state, config, observer, lambda _: True, now=102)["dispatch"] - assert len(planned) == (0 if key == "maxSeconds" else 1) - - -def test_dispatch_rechecks_time_after_each_launch(setup, monkeypatch): - config, state, observer, *_ = setup - add(state, config) - add(state, config, "second") - current = [101] - monkeypatch.setattr(sup.time, "time", lambda: current[0]) - launched = [] - def launcher(task, project): - launched.append(task["id"]) - current[0] = 300 - return 0 - sup.dispatch(state, config, lambda _: None, True, observer, lambda _: True, launcher) - assert launched == ["first"] - - -@pytest.mark.parametrize("failure", ["exit", "timeout", "death"]) -def test_failed_or_interrupted_launch_never_requeues(setup, failure): - config, state, observer, _, state_path = setup - add(state, config) - def launcher(*_): - if failure == "timeout": - raise TimeoutError("fictional timeout") - if failure == "death": - raise KeyboardInterrupt() - return 1 - if failure == "death": - with pytest.raises(KeyboardInterrupt): - sup.dispatch(state, config, lambda value: sup.atomic_write(state_path, value), True, - observer, lambda _: True, launcher, now=101) - state = sup.load_state(state_path, config) - assert state["tasks"][0]["status"] == "reserved" - sup.reconcile(state, config, observer, now=102) - else: - sup.dispatch(state, config, lambda _: None, True, observer, lambda _: True, launcher, now=101) - assert state["tasks"][0]["status"] == "needs-operator" - assert state["runs"] == 1 - assert state["tasks"][0]["assignment"] - - -def test_reconcile_requires_observed_active_then_validated_completion(setup): - config, state, observer, *_ = setup - task = add(state, config) - sup.dispatch(state, config, lambda _: None, True, observer, lambda _: True, lambda *_: 0, now=101) - sup.reconcile(state, config, observer, now=102) - assert task["status"] == "launched" - def running(*args): - return {**observer(*args), "active": "20260101-fictional", "session": "fictional-session"} - sup.reconcile(state, config, running, now=103) - assert task["status"] == "running" - def completed(*args): - assert args[3] == "20260101-fictional" - return {**observer(*args), "completed": True} - sup.reconcile(state, config, completed, now=104) - assert task["status"] == "completed" - - -@pytest.mark.parametrize("case", ["timeout", "old", "session", "missing", "corrupt", "stale", "interrupted"]) -def test_ambiguous_ownership_is_operator_candidate(setup, case): - config, state, observer, *_ = setup - task = add(state, config) - sup.dispatch(state, config, lambda _: None, True, observer, lambda _: True, lambda *_: 0, now=101) - if case == "old": - task["assignment"]["knownMissions"] = ["old-mission"] - if case in ("session", "missing"): - task.update(status="running", mission="old-mission", session="original") - def changed(*args): - return {**observer(*args), "active": "old-mission" if case in ("old", "session") else "", - "session": "different", "corrupt": case == "corrupt", "stale": case == "stale", - "interrupted": case == "interrupted"} - sup.reconcile(state, config, changed, now=120) - assert task["status"] == "needs-operator" - assert task["assignment"] - - -def test_launcher_uses_only_existing_slot_run_and_literal_goal(setup, monkeypatch): - config, state, observer, *_ = setup - task = add(state, config) - task["assignment"] = {"slot": "one"} - calls = [] - def run(argv, **kwargs): - calls.append((argv, kwargs)) - return type("Result", (), {"returncode": 0})() - monkeypatch.setattr(sup.subprocess, "run", run) - assert sup.launch(task, config["projects"]["demo"]) == 0 - argv, options = calls[0] - assert argv == [sys.executable, str(sup.SLOTS_SCRIPT), "--project", config["projects"]["demo"]["path"], - "--runtime", "codex", "run", "one", "--", task["goal"]] - assert options["shell"] is False - assert "--resume" not in argv and "--editor" not in argv - - -def test_cli_status_and_plan_do_not_create_files_and_config_drift_fails(setup, capsys): - config, state, _, config_path, state_path = setup - args = ["--config", str(config_path), "--state", str(state_path)] - assert sup.main([*args, "status"]) == 0 - assert not state_path.exists() and not Path(str(state_path) + ".lock").exists() - assert sup.main([*args, "enqueue", "first", "--project", "demo", "--goal", "Fictional work"]) == 0 - disk = sup.load_state(state_path, config) - assert disk["tasks"][0]["status"] == "pending" - config["budgets"]["maxRuns"] += 1 - with pytest.raises(sup.SupervisorError, match="mismatch"): - sup.load_state(state_path, config) - - -def test_cli_refuses_concurrent_queue_mutation(setup): - _, _, _, config_path, state_path = setup - with sup.slots.FileLock(str(state_path) + ".lock", "test"): - assert sup.main(["--config", str(config_path), "--state", str(state_path), "enqueue", "first", - "--project", "demo", "--goal", "Fictional work"]) == 1 - assert not state_path.exists() - - -@pytest.fixture -def real_slot(setup): - config, state, _, _, _ = setup - project = config["projects"]["demo"] - root = Path(project["path"]) - adapter_dir = root / ".claude" / "orchestrator" - adapter_dir.mkdir(parents=True) - slot_root = root.parent / "slots" - adapter = {"schema": 1, "project": "Fictional", "paths": {"stateDir": "records"}, - "verify": {"grades": ["pytest-pass"]}, - "slots": {"enabled": True, "root": str(slot_root), "names": ["one", "two"], - "client": "fictional_{name}", "prepare": [], "vcs": "none"}} - (adapter_dir / "adapter.json").write_text(json.dumps(adapter)) - assert sup.slots.main(["--project", str(root), "create", "one"]) == 0 - return config, state, project, root, slot_root, adapter - - -def test_real_slot_observer_uses_existing_readiness_active_and_evidence(real_slot): - _, _, project, root, slot_root, _ = real_slot - before = {str(p): p.read_bytes() for p in root.rglob("*") if p.is_file()} - view = sup.observe(project, "one", "codex") - assert view["ready"] and not view["active"] - assert before == {str(p): p.read_bytes() for p in root.rglob("*") if p.is_file()} - records = slot_root / "one" / "records" - records.mkdir() - (records / "ACTIVE").write_text(json.dumps({"id": "20260101-fictional", "session": "fictional-session"})) - view = sup.observe(project, "one", "codex") - assert view["active"] == "20260101-fictional" and not view["ready"] - (records / "ACTIVE").unlink() - mission = records / "20260101-fictional" - mission.mkdir() - (mission / "mission.md").write_text("상태: 닫힘\n확인 C: 승인\n## 목표\nFictional work\n", encoding="utf-8") - unit = {key: "fictional" for key in sup.mission_state.UNIT_HEADER} - unit.update(id="M1", status="done") - sup.mission_state.write_table(mission / "units.tsv", sup.mission_state.UNIT_HEADER, [unit]) - # A closed header and done TSV cannot stand in for the actual receipt/review. - with pytest.raises(sup.verification.VerificationError): - sup.observe(project, "one", "codex", "20260101-fictional") - - -@pytest.mark.parametrize("mutation", [None, "source", "review-evidence"]) -def test_real_receipt_review_completion_and_dependency_gates(real_slot, mutation): - config, state, project, _, slot_root, adapter = real_slot - task = add(state, config) - add(state, config, "dependent", after=[task["id"]]) - sup.dispatch(state, config, lambda _: None, True, sup.observe, lambda _: True, - lambda *_: 0, now=101) - assert task["status"] == "launched" - assert sup.plan(state, config, sup.observe, lambda _: True, now=102)["blocked"]["dependent"] == "dependencies incomplete" - - workspace = slot_root / "one" - records = workspace / "records" - mission = records / "20260101-fictional" - mission.mkdir(parents=True) - active = records / "ACTIVE" - active.write_text(json.dumps({"id": mission.name, "session": "fictional-session"})) - mission_document = mission / "mission.md" - mission_document.write_text("상태: 진행\n확인 C: 대기\n## 목표\nFictional work\n", encoding="utf-8") - sup.reconcile(state, config, sup.observe, now=102) - assert task["status"] == "running" and task["mission"] == mission.name - - source = workspace / "src.py" - source.write_text("value = 1\n") - plan = {"grade": "pytest-pass", "inputs": ["src.py"], "environment": {"target": "fictional"}, - "commands": [{"argv": [sys.executable, "-c", - "import runpy; assert runpy.run_path('src.py')['value'] == 1"], "timeoutSeconds": 10}]} - receipt_path, receipt, reused = sup.verification.run( - workspace, mission, "M1", plan, lambda _: None, settings=adapter["verify"]) - assert receipt["status"] == "pass" and not reused - evidence = mission / "independent-review.md" - evidence.write_text("Synthetic independent review fixture: no findings.\n") - review_path = sup.verification.record_review( - workspace, mission, "M1", receipt_path, evidence, "fictional-independent-reviewer", "unit", "clean", - settings=adapter["verify"]) - assert Path(review_path).is_file() - - # These approval/done records are synthetic fixtures only, never production approvals. - unit = {key: "fictional" for key in sup.mission_state.UNIT_HEADER} - unit.update(id="M1", status="done") - sup.mission_state.write_table(mission / "units.tsv", sup.mission_state.UNIT_HEADER, [unit]) - mission_document.write_text("상태: 닫힘\n확인 C: 승인\n## 목표\nFictional work\n", encoding="utf-8") - active.unlink() - if mutation == "source": - source.write_text("value = 2\n") - elif mutation == "review-evidence": - evidence.write_text("Synthetic changed review evidence.\n") - - sup.reconcile(state, config, sup.observe, now=103) - if mutation is None: - assert task["status"] == "completed" - selected = sup.plan(state, config, sup.observe, lambda _: True, now=104)["dispatch"] - assert [item["id"] for item in selected] == ["dependent"] - else: - assert task["status"] == "needs-operator" - assert task["assignment"] - result = sup.plan(state, config, sup.observe, lambda _: True, now=104) - assert not result["dispatch"] and result["blocked"]["dependent"] == "dependencies incomplete" - - -def test_runtime_readiness_requires_both_terminal_and_runtime(monkeypatch): - monkeypatch.setattr(sup.shutil, "which", lambda name: "/fictional/runtime" if name == "codex" else None) - assert not sup.runtime_ready("codex") - monkeypatch.setattr(sup.shutil, "which", lambda name: "/fictional/terminal" if name == "wt.exe" else None) - assert not sup.runtime_ready("codex") - - -@pytest.mark.parametrize("command", [["status"], ["plan"], ["dispatch", "--execute"], ["reconcile"], - ["enqueue", "second", "--project", "demo", "--goal", "Fictional work"]]) -def test_other_queue_paths_cannot_bypass_shared_authority(setup, command, tmp_path): - config, state, observer, config_path, state_path = setup - add(state, config) - sup.dispatch(state, config, lambda value: sup.atomic_write(state_path, value), True, - observer, lambda _: True, lambda *_: 0, now=101) - saved = state_path.read_bytes() - alternate = tmp_path / "other-authority" / "queue.json" - assert sup.main(["--config", str(config_path), "--state", str(alternate), *command]) == 1 - assert not alternate.parent.exists() - assert state_path.read_bytes() == saved - assert sup.load_state(state_path, config)["tasks"][0]["status"] == "launched" - - -def test_authority_path_default_and_relative_home_fail_closed(tmp_path, monkeypatch): - monkeypatch.delenv("CHEF_SUPERVISOR_HOME", raising=False) - monkeypatch.setattr(sup.Path, "home", classmethod(lambda cls: tmp_path)) - assert sup.authority_path() == tmp_path / ".chef" / "supervisor" / "queue.json" - assert not (tmp_path / ".chef").exists() - monkeypatch.setenv("CHEF_SUPERVISOR_HOME", "relative") - with pytest.raises(sup.SupervisorError, match="absolute"): - sup.authority_path() - - -@pytest.mark.parametrize("value", [True, False, float("nan"), float("inf"), -1]) -def test_corrupt_queue_clocks_cannot_disable_time_budget(setup, value): - config, state, observer, *_ = setup - state["createdAt"] = value - with pytest.raises(sup.SupervisorError): - sup.validate_state(state, config) - state["createdAt"] = 100 - task = add(state, config) - sup.dispatch(state, config, lambda _: None, True, observer, lambda _: True, lambda *_: 0, now=101) - task["reservedAt"] = value - with pytest.raises(sup.SupervisorError): - sup.validate_state(state, config) - - -def test_corrupt_runs_and_mission_paths_are_rejected(setup): - config, state, observer, *_ = setup - task = add(state, config) - sup.dispatch(state, config, lambda _: None, True, observer, lambda _: True, lambda *_: 0, now=101) - state["runs"] = 0 - with pytest.raises(sup.SupervisorError, match="count"): - sup.validate_state(state, config) - state["runs"] = 1 - task["mission"] = "../../outside" - with pytest.raises(sup.SupervisorError, match="mission"): - sup.validate_state(state, config) - - -@pytest.mark.parametrize("schema", [True, False, 1.0]) -def test_schema_requires_actual_integer_in_config_and_queue(setup, schema): - config, state, _, config_path, _ = setup - invalid_config = {**config, "schema": schema} - config_path.write_text(json.dumps(invalid_config)) - with pytest.raises(sup.SupervisorError, match="schema"): - sup.load_config(config_path) - state["schema"] = schema - with pytest.raises(sup.SupervisorError, match="schema"): - sup.validate_state(state, config) diff --git a/tests/integration/mission/test_unified_cli.py b/tests/integration/mission/test_unified_cli.py deleted file mode 100644 index 3581806..0000000 --- a/tests/integration/mission/test_unified_cli.py +++ /dev/null @@ -1,539 +0,0 @@ -"""Exercise the bundled entry point against an isolated fictional project.""" - -import hashlib -import json -import os -import subprocess -import sys -from datetime import datetime -from pathlib import Path - -import pytest - -from chef.guards import mission -from chef.mission.contracts import StateError -from chef.mission.documents import share_documents, shared_documents -from chef.verification.contracts import digest -from chef.verification.plan import snapshot -from chef.verification import reviews -from chef.workers import cli as worker_cli, controller -from chef.workers.store import Store -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture -def project(tmp_path, monkeypatch): - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "empty-registry")) - monkeypatch.setenv("CHEF_WORKERS_HOME", str(tmp_path / "unused-worker-state")) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - project = tmp_path / "fictional project" - adapter = project / ".claude/orchestrator" - adapter.mkdir(parents=True) - (adapter / "adapter.json").write_text(json.dumps({ - "schema": 1, "paths": {"stateDir": "state"}, "documents": {"schemaCatalog": "schema.json"}, - "verify": {"grades": ["pytest-pass"]}, - }), encoding="utf-8") - folder = project / "state" / "orchard" - folder.mkdir(parents=True) - (folder / "mission.md").write_text("# Orchard\n", encoding="utf-8") - mission.write_active(str(folder.parent), mission.Active("orchard", "fictional", "original", runtime="codex")) - (project / "schema.json").write_text(json.dumps({"schema": 1, "tables": [ - {"kind": "db", "name": "Tree", "fields": {"Id": "int"}}, - {"kind": "proto", "name": "Species", "fields": {"Key": "str"}}, - ]}), encoding="utf-8") - return project, folder - - -def run(project, *args, input=None, runtime="codex"): - options = ("--runtime", runtime) if runtime else () - return subprocess.run( - [sys.executable, "-I", "-B", str(PLUGIN_ROOT / "chef_cli.py"), *args, *options], - cwd=project, env={**os.environ, "PYTHONUTF8": "1"}, input=json.dumps(input) if input is not None else None, - capture_output=True, encoding="utf-8", timeout=20, - ) - - -def tree_block(): - return {"id": "tree", "type": "schema-table", "title": "Tree fields", - "target": {"kind": "db", "name": "Tree", "state": "existing"}, - "fields": [{"name": "Id", "type": "int"}]} - - -def test_context_and_document_share_checks_the_registered_bytes(project): - root, folder = project - context = run(root, "context", "--session", "fictional") - assert context.returncode == 0, context.stderr - assert json.loads(context.stdout)["ownerMatches"] is True - - draft = run(root, "document", "create", "--kind", "report", "--title", "Orchard report") - assert draft.returncode == 0, draft.stderr - assert run(root, "document", "share", "report.md").returncode == 1 - assert run(root, "document", "list", "--json").stdout.strip() == "[]" - report = folder / "report.md" - report.write_text(report.read_text(encoding="utf-8").replace( - "## 지금", "## 지금\nReady").replace("## 남은 확인", "## 남은 확인\nNone") - .replace("## 다음 일", "## 다음 일\nPlant the tree"), encoding="utf-8") - shared = run(root, "document", "share", "report.md", "--json") - assert shared.returncode == 0, shared.stderr - assert json.loads(shared.stdout)["documents"][0]["sha256"] == hashlib.sha256(report.read_bytes()).hexdigest() - listed = json.loads(run(root, "document", "list", "--json").stdout)[0] - assert listed["sharing"] == "shared" and listed["issues"] == [] and listed["approval"] is None - assert listed["sha256"] == hashlib.sha256(report.read_bytes()).hexdigest() - report.write_text("# Changed report\n", encoding="utf-8") - assert json.loads(run(root, "document", "check", "report.md").stdout)[0]["sharing"] == "unshared" - - -def test_edit_during_document_validation_does_not_register_stale_bytes(project): - _, folder = project - report = folder / "report.md" - report.write_text("# Original\n", encoding="utf-8") - - def validate(_name, _path, content): - assert content.startswith(b"# Original") - report.write_text("# Changed\n", encoding="utf-8") - - with pytest.raises(StateError, match="검사 중 바뀌었습니다"): - share_documents(folder, ["report.md"], check_content=validate) - assert not shared_documents(folder) - - -def test_normal_init_yields_one_managed_report_and_a_valid_design_template(project): - root, folder = project - started = run(root, "mission", "init", "--tier", "M", "--goal", "Review storage") - assert started.returncode == 0, started.stderr - assert "chef:document report" in (folder / "report.md").read_text(encoding="utf-8") - checked = run(root, "document", "share", "report.md") - assert checked.returncode == 1 and "empty section" in checked.stderr - duplicate = run(root, "document", "create", "--kind", "report", "--title", "Different title") - assert duplicate.returncode == 1 and "already exists" in duplicate.stderr - template = run(root, "question", "template", "--kind", "design", "--id", "confirm-A2") - assert template.returncode == 0, template.stderr - draft = json.loads(template.stdout) - preflight = run(root, "question", "preflight", "--input", "-", "--preview", input=draft) - assert preflight.returncode == 0, preflight.stderr - assert preflight.stdout.startswith("# ") and "revision 1" in preflight.stderr - assert not (folder / "confirm-A2.md").exists() - published = run(root, "question", "publish", "--input", "-", input=draft) - assert published.returncode == 0, published.stderr - snapshot = (folder / "questions/confirm-A2.json").read_bytes() - template = run(root, "question", "reply-template", "confirm-A2.md") - assert template.returncode == 0, template.stderr - reply = json.loads(template.stdout) - assert reply["id"] and reply["revision"] == 1 and datetime.fromisoformat(reply["at"]).utcoffset().total_seconds() == 0 - assert reply["text"] == "" and reply["updates"] == [] - assert (folder / "questions/confirm-A2.json").read_bytes() == snapshot - reply.update(text="Blue", updates=[{"id": "color", "status": "answered", "answer": "Blue", "selected": "blue"}]) - answered = run(root, "question", "answer", "confirm-A2.md", "--input", "-", input=reply) - assert answered.returncode == 0, answered.stderr - assert run(root, "question", "check").returncode == 0 - checked = run(root, "document", "compare", str(folder / "questions/confirm-A2.json")) - assert checked.returncode == 0 and json.loads(checked.stdout)["issues"] == [], checked.stderr - - -def test_direct_question_answer_keeps_exact_text_and_checks_revision_and_retries(project): - root, folder = project - template = run(root, "question", "template", "--kind", "design", "--id", "confirm-A2") - assert template.returncode == 0, template.stderr - visible = run(root, "question", "publish", "--input", "-", input=json.loads(template.stdout)) - assert visible.returncode == 0, visible.stderr - path = folder / "questions/confirm-A2.json" - original = path.read_bytes() - raw = "Choose blue.\nPlease keep the earlier requirement." - args = ("question", "answer", "confirm-A2.md", "--text", raw, "--reply-id", "reply-one", - "--select", "color", "blue", "Blue") - wrong = run(root, *args, "--expect-revision", "2") - assert wrong.returncode == 1 and path.read_bytes() == original - first = run(root, *args, "--expect-revision", "1") - assert first.returncode == 0, first.stderr - after = json.loads(path.read_bytes()) - assert after["answers"][0]["text"] == raw - assert after["answers"][0]["updates"][0]["selected"] == "blue" - assert "approval" not in after["answers"][0] - assert after["approval"] == json.loads(original)["approval"] - repeat = run(root, *args, "--expect-revision", "1") - assert repeat.returncode == 0 and json.loads(path.read_bytes()) == after, repeat.stderr - - -def test_unit_batch_admits_stdin_without_a_temporary_payload_file(project): - root, folder = project - started = run(root, "mission", "init", "--tier", "M", "--goal", "Plant") - assert started.returncode == 0, started.stderr - record = {"schema": 1, "units": [{"id": "M1", "goal": "Plant", "files": "garden.txt", "done": "Planted", - "verify": "Inspect the garden", "timebox": 15, "forbid": "No outside edits"}]} - result = run(root, "unit", "add", "--input", "-", input=record) - assert result.returncode == 0, result.stderr - assert (folder / "units.tsv").is_file() - assert list(root.glob("*.json")) == [root / "schema.json"] - - -def init_unit(root, files='["garden.txt", "seedlings.txt"]'): - started = run(root, "mission", "init", "--tier", "M", "--goal", "Plant") - assert started.returncode == 0, started.stderr - (root / "garden.txt").write_text("garden\n", encoding="utf-8") - result = run(root, "unit", "add", "--input", "-", input={ - "schema": 1, "units": [{"id": "M1", "goal": "Plant the garden", "files": files, - "done": "Planted", "verify": "Inspect the garden", "timebox": 15, - "forbid": "No outside edits"}], - }) - assert result.returncode == 0, result.stderr - - -def dispatch(root, role, attempt, *options, session="fictional"): - return run(root, "worker", "dispatch", "M1", "--role", role, "--session", session, "--request-id", attempt, - "--mode", "native", "--host-role", f"chef:{role}", *options) - - -def registered_plan(root): - result = run(root, "plan", "template", "M1") - assert result.returncode == 0 and "Inspect the garden" in result.stderr - plan = json.loads(result.stdout) - assert plan["grade"] == "pytest-pass" and plan["inputs"] == ["garden.txt", "seedlings.txt"] - assert not plan["commands"] and not plan["environment"] - plan.update(commands=[{"argv": [sys.executable, "-c", "assert open('garden.txt').read()"]}], - environment={"fixture": "orchard"}) - saved = run(root, "plan", "save", "M1", "--input", "-", input=plan) - assert saved.returncode == 0, saved.stderr - return plan, json.loads(saved.stdout) - - -def test_compact_dispatch_reuses_approved_scope_and_request_identity(project): - root, _ = project - init_unit(root) - wrong = dispatch(root, "dev-small", "writing", session="someone-else") - assert wrong.returncode == 1 and "ACTIVE" in wrong.stdout - outside = dispatch(root, "dev-small", "writing", "--file", "schema.json") - assert outside.returncode == 1 and "approved unit files" in outside.stdout - created = dispatch(root, "dev-small", "writing", "--prompt", "Plant in this order") - assert created.returncode == 0, created.stdout + created.stderr - job = json.loads(created.stdout) - assert job["native"] and "Plant the garden" in job["brief"] and "Plant in this order" in job["brief"] - request = Store().get(job["key"], reconcile=False)["request"] - assert request["files"] == ["garden.txt", "seedlings.txt"] and request["mission"] == "orchard" - retry = dispatch(root, "dev-small", "writing", "--prompt", "Plant in this order") - assert retry.returncode == 0 and json.loads(retry.stdout)["key"] == job["key"] - assert json.loads(retry.stdout)["created"] is False - assert dispatch(root, "dev-small", "writing", "--prompt", "Different scope").returncode == 1 - - -def test_plain_scope_only_admits_an_actual_file_and_rejects_opaque_prose(project): - root, _ = project - init_unit(root, "garden.txt and related files") - assert dispatch(root, "dev-small", "writing", "--file", "garden.txt").returncode == 1 - edit = run(root, "unit", "set", "M1", "--files", "garden.txt") - assert edit.returncode == 0, edit.stderr - assert dispatch(root, "dev-small", "writing").returncode == 0 - - -def test_ledger_stdin_records_and_audits_current_evidence_hash(project): - root, folder = project - init_unit(root) - evidence = {"schema": 1, "files": [{"path": "garden.txt", "kind": "report", "sha256": "a" * 64}]} - args = ("ledger", "record", "M1", "--status", "pass", "--grade", "pytest-pass", "--evidence-input", "-") - ledger = (folder / "ledger.tsv").read_bytes() - rejected = run(root, *args, input=evidence) - assert rejected.returncode == 1 and "sha256 differs" in rejected.stderr - assert (folder / "ledger.tsv").read_bytes() == ledger - evidence["files"][0].pop("sha256") - recorded = run(root, *args, input=evidence) - assert recorded.returncode == 0, recorded.stderr - assert json.loads(run(root, "ledger", "audit").stdout)["counts"]["checkedFiles"] == 1 - (root / "garden.txt").write_text("changed\n", encoding="utf-8") - assert json.loads(run(root, "ledger", "audit").stdout)["counts"]["changed"] == 1 - - -def test_registered_plan_is_reusable_with_content_and_revision_checks(project): - root, _ = project - init_unit(root) - plan, first = registered_plan(root) - repeated = run(root, "plan", "save", "M1", "--input", "-", input=plan) - assert repeated.returncode == 0 and json.loads(repeated.stdout) == first - verifier = dispatch(root, "verifier", "verification") - assert verifier.returncode == 0, verifier.stdout + verifier.stderr - bound_path = Store().get(json.loads(verifier.stdout)["key"], reconcile=False)["request"]["verification"] - assert bound_path["path"] == first["path"] and bound_path["sha256"] == first["sha256"] - assert run(root, "preflight", "M1").returncode == 0 - verified = run(root, "verify", "M1") - assert verified.returncode == 0, verified.stderr - assert "재사용" in run(root, "verify", "M1").stdout - assert run(root, "review-start", "M1").returncode == 0 - assert run(root, "unit", "set", "M1", "--verify", "Inspect again").returncode == 0 - assert json.loads(run(root, "plan", "show", "M1").stdout)["stale"] - assert run(root, "preflight", "M1").returncode == 1 - plan["environment"] = {"fixture": "second"} - assert run(root, "plan", "save", "M1", "--input", "-", input=plan).returncode == 1 - replaced = run(root, "plan", "save", "M1", "--input", "-", "--expect-sha256", first["sha256"], input=plan) - assert replaced.returncode == 0, replaced.stderr - second = json.loads(replaced.stdout) - assert second["sha256"] != first["sha256"] and Path(first["path"]).is_file() - Path(second["path"]).write_text("{}\n", encoding="utf-8") - assert run(root, "preflight", "M1").returncode == 1 - assert run(root, "preflight", "M1", "--plan", first["path"]).returncode == 0 - - -def test_registered_plan_supplies_review_run_without_an_explicit_path(project): - root, _ = project - python = Path(sys.base_prefix) / "python.exe" if os.name == "nt" else Path(sys.executable) - if not python.is_file(): - pytest.skip("hashable Python executable unavailable") - init_unit(root) - plan, _ = registered_plan(root) - for name in ("scope.json", "findings.json"): - (root / name).write_text("[]", encoding="utf-8") - result = run(root, "review-run", "M1", "--runtime", "codex", "--snapshot", digest(snapshot(root, plan["inputs"])), - "--purpose", "Inspect garden", "--scope", "scope.json", "--findings", "findings.json", - "--", str(python), "-c", "print('Reviewed the garden')", runtime=None) - assert result.returncode == 0, result.stdout + result.stderr - review = json.loads(result.stdout) - assert review["status"] == "completed" and review["result"]["inputsUnchanged"] - - -def test_named_plan_uses_adapter_commands_and_the_unit_files(project): - root, folder = project - adapter = root / ".claude/orchestrator/adapter.json" - config = json.loads(adapter.read_bytes()) - config["verify"]["planPresets"] = { - "garden": {"grade": "pytest-pass", "environment": {"target": "orchard"}, - "commands": [{"argv": [sys.executable, "-c", "assert open('garden.txt').read()"]}]}, - } - adapter.write_text(json.dumps(config), encoding="utf-8") - init_unit(root, "garden.txt") - listed = run(root, "plan", "presets") - assert json.loads(listed.stdout)["presets"] == [{"name": "garden", "grade": "pytest-pass"}] - assert run(root, "plan", "save", "M1", "--preset", "unknown").returncode == 1 - result = run(root, "plan", "save", "M1", "--preset", "garden") - assert result.returncode == 0, result.stderr - source = json.loads(Path(json.loads(result.stdout)["path"]).read_bytes()) - assert source == {**config["verify"]["planPresets"]["garden"], "inputs": ["garden.txt"]} - verification = run(root, "verify", "M1") - assert verification.returncode == 0, verification.stderr - assert (folder / "verification/M1.latest.json").is_file() - - -def collect_review(root, job, review): - result = run(root, "worker", "native-result", "--key", job["key"], "--token", job["token"], "--result", "-", - input=review, runtime=None) - assert result.returncode == 0, result.stdout + result.stderr - assert json.loads(result.stdout)["status"] == "completed" - - -def clean_review(): - return {"schema": 1, "report": "Reviewed the garden.", "findings": [], "resolvedIds": [], "suggestions": []} - - -def test_worker_run_dispatches_collects_records_and_closes_only_confirmed_low(project, monkeypatch, capsys): - root, folder = project - init_unit(root) - registered_plan(root) - assert run(root, "verify", "M1").returncode == 0 - monkeypatch.chdir(root) - monkeypatch.setattr(controller.policy.user_config, "read", lambda: {}) - launched = [] - review = clean_review() - review["findings"] = [{"id": "F1", "kind": "defect", "origin": "new", "severity": "low", - "reason": "Missing label", "evidence": "garden.txt:1"}] - - def candidates(_adapter, _cwd, role, **kwargs): - assert kwargs["native"] is None and kwargs["allowed_runtimes"] == ["codex"] - return [{"runtime": "codex", "available": True, "roles": [role], "tools": ["Read"]}] - - def backend(runtime, role, prompt, **_kwargs): - launched.append(role) - assert runtime == "codex" - if role == "reviewer-small": - assert "Read the exact verified change diff" in prompt - return {"ok": True, "result": json.dumps(review)} - - def launch(store, record, _directory): - controller.supervise(record["key"], record["token"], store=store) - - monkeypatch.setattr(controller.backends, "candidates", candidates) - monkeypatch.setattr(controller.backends, "run", backend) - monkeypatch.setattr(controller, "launch_supervisor", launch) - - def managed(role, attempt, *options, expected=0): - code = worker_cli.main(["run", "M1", "--role", role, "--request-id", attempt, "--mode", "native", - "--session", "fictional", "--runtime", "codex", "--wait-seconds", "5", *options]) - assert code == expected - return json.loads(capsys.readouterr().out) - - first = managed("code-reviewer", "first", "--record-review") - assert first["status"] == "completed" and first["execution"] == "supervised" - assert first["reviewRecord"]["status"] == "recorded" - proof = json.loads(Path(first["reviewRecord"]["path"]).read_bytes()) - assert proof["findings"][0]["id"] == "F1" and proof["workerJob"] == first["key"] - assert managed("code-reviewer", "first", "--record-review")["key"] == first["key"] - directory = Path(first["details"]).parent.parent / "attempts" / first["key"] / first["token"] - (directory / "review-record.json").unlink() - assert managed("code-reviewer", "first", "--record-review")["reviewRecord"] == first["reviewRecord"] - assert "text diff" in managed("reviewer-small", "unchanged", "--close-low", expected=1)["error"] - assert launched == ["code-reviewer"] - - (root / "garden.txt").write_text("labeled garden\n", encoding="utf-8") - assert run(root, "verify", "M1").returncode == 0 - with monkeypatch.context() as patch: - patch.setattr(reviews, "project_path", lambda *_: root / "schema.json") - stale = managed("reviewer-small", "stale-diff", "--close-low", expected=1) - assert "complete text diff" in stale["error"] - assert launched == ["code-reviewer"] - review = clean_review() - blocked = managed("reviewer-small", "unresolved", "--close-low", expected=1) - assert blocked["status"] == "completed" and blocked["reviewRecord"]["status"] == "blocked" - pointer = folder / "verification/M1.review.latest.json" - assert json.loads(pointer.read_bytes())["review"] == first["reviewRecord"]["path"] - review.update(report="The existing label finding is fixed in garden.txt:1.", resolvedIds=["F1"]) - closed = managed("reviewer-small", "close", "--close-low") - closed_review = json.loads(Path(closed["reviewRecord"]["path"]).read_bytes()) - assert closed_review["status"] == "closed-low" and closed_review["closedLowIds"] == ["F1"] - diff = Path(closed_review["workerDiff"]) - assert b"+labeled garden" in diff.read_bytes() - diff.write_text("changed", encoding="utf-8") - assert run(root, "review-open", "M1").returncode == 1 - - -def test_worker_run_waits_for_a_detached_supervisor_to_record_review(project, tmp_path, monkeypatch, capsys): - root, folder = project - init_unit(root) - registered_plan(root) - assert run(root, "verify", "M1").returncode == 0 - bootstrap = tmp_path / "supervisor fixture" - bootstrap.mkdir() - (bootstrap / "worker.py").write_text( - "import os, sys\n" - f"sys.path.insert(0, {str(PLUGIN_ROOT)!r})\n" - "from chef.workers import backends, cli\n" - f"backends.run = lambda *args, **kwargs: {{'ok': True, 'review': {clean_review()!r}, 'fixturePid': os.getpid()}}\n" - "raise SystemExit(cli.main())\n", - encoding="utf-8", - ) - monkeypatch.chdir(root) - monkeypatch.setattr(controller, "PLUGIN_ROOT", bootstrap) - monkeypatch.setattr(controller.policy.user_config, "read", lambda: {}) - monkeypatch.setattr(controller.backends, "candidates", lambda *_args, **_kwargs: [ - {"runtime": "codex", "available": True, "roles": ["code-reviewer"], "tools": ["Read"]}, - ]) - code = worker_cli.main(["run", "M1", "--role", "code-reviewer", "--request-id", "detached-review", - "--mode", "codex", "--session", "fictional", "--runtime", "codex", - "--record-review", "--wait-seconds", "20"]) - result = json.loads(capsys.readouterr().out) - assert code == 0 and result["reviewRecord"]["status"] == "recorded", result - assert Store().get(result["key"])["result"]["fixturePid"] != os.getpid() - pointer = json.loads((folder / "verification/M1.review.latest.json").read_bytes()) - assert pointer["review"] == result["reviewRecord"]["path"] - - -def test_review_job_records_first_findings_and_manual_diff_closes_same_id(project): - root, folder = project - init_unit(root) - registered_plan(root) - assert run(root, "verify", "M1").returncode == 0 - started = dispatch(root, "code-reviewer", "first-review") - assert started.returncode == 0, started.stdout + started.stderr - job = json.loads(started.stdout) - args = ("review", "M1", "--job", job["key"]) - assert run(root, *args, "--session", "fictional").returncode == 1 - result = clean_review() - result["findings"].append({"id": "F1", "kind": "defect", "origin": "new", "severity": "low", - "reason": "Missing label", "evidence": "garden.txt:1"}) - collect_review(root, job, result) - wrong = run(root, *args, "--session", "someone-else") - assert wrong.returncode == 1 and "owner session" in wrong.stderr - pointer = folder / "verification/M1.review.latest.json" - assert not pointer.exists() - recorded = run(root, *args, "--session", "fictional") - assert recorded.returncode == 0, recorded.stderr - first = pointer.read_bytes() - assert run(root, *args, "--session", "fictional").returncode == 0 - assert pointer.read_bytes() == first - first_review = json.loads(Path(json.loads(first)["review"]).read_bytes()) - assert first_review["workerJob"] == job["key"] and first_review["findings"][0]["id"] == "F1" - assert Path(first_review["evidence"]).read_text(encoding="utf-8") == result["report"] - assert run(root, *args, "--session", "fictional", "--status", "closed-low").returncode == 1 - (root / "garden.txt").write_text("labeled garden\n", encoding="utf-8") - assert run(root, *args, "--session", "fictional").returncode == 1 - scope = run(root, "review-scope", "M1") - assert scope.returncode == 0 and "garden.txt" in scope.stdout - assert run(root, "verify", "M1").returncode == 0 - receipt = json.loads((folder / "verification/M1.latest.json").read_bytes())["receipt"] - diff = root / "reviewed-diff.md" - diff.write_text("Confirmed label in garden.txt:1.\n", encoding="utf-8") - closed = run(root, "review", "M1", "--receipt", receipt, "--evidence", str(diff), "--reviewer", "coordinator", - "--kind", "unit", "--status", "closed-low", "--resolved-id", "F1") - assert closed.returncode == 0, closed.stderr - current = json.loads(Path(json.loads(pointer.read_bytes())["review"]).read_bytes()) - assert current["closedLowIds"] == ["F1"] and current["round"] == 2 - - -def test_review_job_rejects_superseded_receipt_and_unstructured_result(project): - root, folder = project - init_unit(root) - registered_plan(root) - assert run(root, "verify", "M1").returncode == 0 - started = dispatch(root, "reviewer-small", "review") - assert started.returncode == 0, started.stdout + started.stderr - job = json.loads(started.stdout) - invalid = run(root, "worker", "native-result", "--key", job["key"], "--token", job["token"], "--result", "-", - input={"ok": True, "result": "No issues."}, runtime=None) - assert invalid.returncode == 1 and "structured JSON" in invalid.stdout - collect_review(root, job, clean_review()) - assert run(root, "verify", "M1", "--force").returncode == 0 - rejected = run(root, "review", "M1", "--job", job["key"], "--session", "fictional") - assert rejected.returncode == 1 and "마지막 검증 기록" in rejected.stderr - assert not (folder / "verification/M1.review.latest.json").exists() - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -@pytest.mark.parametrize("action", ["worker dispatch M1 --role code-reviewer", "worker run M1 --role code-reviewer", - "review M1 --job candidate"]) -def test_host_guard_checks_new_commands_against_actual_host_identity(project, runtime, action): - root, folder = project - mission.write_active(str(folder.parent), mission.Active("orchard", "actual-session", "original", runtime=runtime)) - command = f'python "{PLUGIN_ROOT / "chef_cli.py"}" {action}' - payload = {"cwd": str(root), "han_runtime": runtime, "session_id": "actual-session", "tool_name": "PowerShell"} - valid = f"{command} --runtime={runtime} --session actual-session" - assert not mission.decide({**payload, "tool_input": {"command": valid}}).deny - wrong_session = valid.replace("actual-session", "different-session") - assert "--session" in mission.decide({**payload, "tool_input": {"command": wrong_session}}).deny - wrong_runtime = valid.replace(f"--runtime={runtime}", "--runtime=foreign") - assert "--runtime" in mission.decide({**payload, "tool_input": {"command": wrong_runtime}}).deny - - -def test_typed_schema_is_checked_and_tampering_cannot_be_shared(project): - root, folder = project - schema = tree_block() - created = run(root, "document", "create", "--kind", "schema", "--name", "tree", "--input", "-", input=schema) - assert created.returncode == 0 and "verified" in created.stdout, created.stderr - name = "details/tree.md" - assert run(root, "document", "share", name).returncode == 0 - (folder / name).write_text((folder / name).read_text(encoding="utf-8") + "| Key | str |\n", encoding="utf-8") - assert run(root, "document", "share", name).returncode == 1 - schema["fields"].append({"name": "Key", "type": "str"}) - rejected = run(root, "document", "create", "--kind", "schema", "--name", "mixed", "--input", "-", input=schema) - assert rejected.returncode == 1 and "does not match" in rejected.stderr - assert not (folder / "details/mixed.md").exists() - - -@pytest.mark.parametrize("area", ["blocks", "detail_blocks"]) -@pytest.mark.parametrize("untyped", ["fields", "table"]) -def test_new_confirm_rejects_generic_schema_tables_before_publication(project, area, untyped): - root, folder = project - record = json.loads((PLUGIN_ROOT / "skills/mission/references/templates/design-confirm.json").read_text(encoding="utf-8")) - record["blocks"] = [tree_block()] - improper = {"id": "mixed", "type": untyped, "title": "Mixed definitions"} - if untyped == "table": - improper.update(columns=["Store", "Attribute", "Format"], - rows=[["Orchard DB", "Id", "int"], ["Catalog Proto", "Key", "str"]]) - else: - improper["fields"] = [{"name": "Id", "type": "int"}, {"name": "Key", "type": "str"}] - record.setdefault(area, []).append(improper) - path = root / "draft.json" - path.write_text(json.dumps(record), encoding="utf-8") - result = run(root, "question", "publish", "--input", str(path)) - assert result.returncode == 1 and "use a schema-table" in result.stderr - assert not (folder / "confirm-A.md").exists() - record[area].remove(improper) - if not record[area]: - record.pop(area) - path.write_text(json.dumps(record), encoding="utf-8") - result = run(root, "question", "publish", "--input", str(path)) - assert result.returncode == 0 and "Schema db Tree: verified" in result.stdout, result.stderr - assert "`DB Tree`" in (folder / "confirm-A.md").read_text(encoding="utf-8") diff --git a/tests/integration/mission/test_unit_input.py b/tests/integration/mission/test_unit_input.py deleted file mode 100644 index 6061332..0000000 --- a/tests/integration/mission/test_unit_input.py +++ /dev/null @@ -1,125 +0,0 @@ -"""Batch unit registration must not leave a partially accepted plan.""" - -import json -from datetime import datetime, timedelta - -import pytest - -from chef.mission import state -from chef.mission.storage import read_table, write_table -from chef.mission.contracts import UNIT_HEADER -from tests.integration.mission.test_state_efficiency import sample - - -def unit(name, **changes): - return {"id": name, "goal": "Check a fictional widget", "files": "widget.py", - "done": "Expected value", "verify": "sample checks", "timebox": 30, - "forbid": "publish", **changes} - - -def save(root, items): - (root / "units.json").write_text(json.dumps({"schema": 1, "units": items}), encoding="utf-8") - - -@pytest.mark.parametrize("runtime", ["claude", "codex", "grok"]) -def test_template_is_standalone_and_writes_nothing(tmp_path, monkeypatch, capsys, runtime): - monkeypatch.chdir(tmp_path) - monkeypatch.setattr(state.infrastructure_configuration, "locate", lambda *a: pytest.fail("adapter lookup")) - assert state.main(["unit", "template", "--id", "U2", "--id", "U3"], runtime=runtime) == 0 - data = json.loads(capsys.readouterr().out) - assert [u["id"] for u in data["units"]] == ["U2", "U3"] - assert data["units"][0]["timebox"] == 30 - assert data["units"][0]["forbid"] == "" - assert list(tmp_path.iterdir()) == [] - - -def test_all_validation_errors_return_before_any_write(sample): - root, folder, run = sample - save(root, [unit("U2", forbid="", timebox="30 minutes", after="absent"), - unit("U1", done="", extra="unexpected")]) - before = (folder / "units.tsv").read_bytes() - code, _, err = run("unit", "add", "--input", "units.json") - assert code == 1 - for expected in ("forbid", "양의 정수", "absent", "이미 있음", "done", "extra"): - assert expected in err - assert (folder / "units.tsv").read_bytes() == before - - -def test_batch_is_one_atomic_write_and_dependencies_use_input_order(sample, monkeypatch): - root, folder, run = sample - save(root, [unit("U2", after="U1"), unit("U3", after="U2")]) - original = state.write_table - calls = [] - - def write(*args): - calls.append(args) - return original(*args) - - monkeypatch.setattr(state, "write_table", write) - code, out, err = run("unit", "add", "--input", "units.json") - assert code == 0 and not err and len(calls) == 1 - response = json.loads(out) - assert response["status"] == "added" - assert [(u["id"], u["after"], u["status"]) for u in response["units"]] == [ - ("U2", "U1", "todo"), ("U3", "U2", "todo")] - assert len(read_table(str(folder / "units.tsv"), UNIT_HEADER)) == 3 - - -def test_dry_run_leaves_all_mission_files_unchanged(sample): - root, folder, run = sample - save(root, [unit("U2")]) - before = {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in folder.parent.rglob("*") if p.is_file()} - code, out, err = run("unit", "add", "--input", "units.json", "--dry-run") - assert code == 0 and not err and json.loads(out)["status"] == "valid" - assert before == {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in folder.parent.rglob("*") if p.is_file()} - - -@pytest.mark.parametrize("items", [ - [unit("U2"), unit("U2")], - [unit("U2", after="U3"), unit("U3", after="U2")], - [unit("U2", timebox=True)], - [unit("U2", files=["widget.py"])], -]) -def test_invalid_batch_does_not_change_state(sample, items): - root, folder, run = sample - save(root, items) - before = (folder / "units.tsv").read_bytes() - assert run("unit", "add", "--input", "units.json")[0] == 1 - assert (folder / "units.tsv").read_bytes() == before - - -def test_json_and_flags_cannot_silently_override_each_other(sample): - root, _, run = sample - save(root, [unit("U2")]) - assert run("unit", "add", "U3", "--input", "units.json")[0] == 1 - assert run("unit", "add", "--goal", "Other", "--input", "units.json")[0] == 1 - - -def test_resumed_context_keeps_approval_and_unit_pointers(sample): - root, folder, run = sample - before = {p: p.read_bytes() for p in folder.rglob("*") if p.is_file()} - code, out, err = run("context", "--json") - data = json.loads(out) - assert code == 0 and not err and data["active"] == ["U1"] - assert data["unitSource"] == str(folder / "units.tsv") - assert str(folder / "mission.md") in data["approvalSources"] - assert data["semanticApproval"] == "read_original_sources" - assert before == {p: p.read_bytes() for p in folder.rglob("*") if p.is_file()} - - -def test_overdue_brief_returns_replanning_diagnostics_without_dispatch_or_write(sample): - root, folder, run = sample - path = str(folder / "units.tsv") - rows = read_table(path, UNIT_HEADER) - rows[0]["started"] = (datetime.now().astimezone() - timedelta(minutes=40)).isoformat() - write_table(path, UNIT_HEADER, rows) - before = (folder / "units.tsv").read_bytes() - code, out, err = run("brief", "U1") - data = json.loads(out) - assert code == 1 and not err - assert data["dispatch"]["status"] == "needs-replan" - assert data["dispatch"]["elapsedMinutes"] >= 40 - assert data["dispatch"]["timeboxMinutes"] == 30 - assert data["approvalSources"] == [str(folder / "mission.md")] - assert before == (folder / "units.tsv").read_bytes() - assert json.loads(run("context", "--json")[1])["overdue"] == ["U1"] diff --git a/tests/integration/mission/test_usage_report.py b/tests/integration/mission/test_usage_report.py deleted file mode 100644 index 9b8825a..0000000 --- a/tests/integration/mission/test_usage_report.py +++ /dev/null @@ -1,332 +0,0 @@ -import json -import os -from collections import Counter -from pathlib import Path - -import pytest -from chef.infrastructure import configuration, errors -from chef.mission import usage as report -from chef.runtimes.claude import session as claude_session - -from tests.paths import PLUGIN_ROOT - -START = report.timestamp('2026-10-23T00:00:00+09:00') -END = report.timestamp('2026-10-24T00:00:00+09:00') - - -def row(request, at='2026-10-23T00:10:00+09:00', output=7): - return {'type': 'assistant', 'timestamp': at, 'requestId': request, 'effort': 'high', - 'message': {'id': request, 'model': 'claude-sonnet-5-5', 'usage': { - 'input_tokens': 3, 'cache_creation_input_tokens': 11, - 'cache_read_input_tokens': 100, 'output_tokens': output, - 'iterations': [{'type': 'advisor_message', 'input_tokens': 150, 'output_tokens': 9}]}}} - - -def transcript(home, project, rows, child=False): - root = home / 'projects' / claude_session.project_dir_name(str(project)) - path = root / ('s/subagents/agent-a.jsonl' if child else 's.jsonl') - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(''.join(json.dumps(r) + '\n' for r in rows), encoding='utf-8') - return path - - -def test_streaming_duplicates_cache_and_advisor_are_counted_separately(tmp_path): - project = tmp_path / 'game' - first, last = row('one', output=1), row('one', output=7) - transcript(tmp_path, project, [first, last]) - diagnostics = Counter() - records, missing = report.collect_usage([('main', project)], tmp_path, START, END, diagnostics) - result = report.aggregate(records) - assert result['responses'] == 1 and result['advisor_calls'] == 1 - assert result['usage'] == dict(zip(report.TOKEN_FIELDS, (3, 11, 100, 7))) - assert result['advisor_usage'] == dict(zip(report.TOKEN_FIELDS, (150, 0, 0, 9))) - assert not missing and not diagnostics - - -def test_timezone_boundaries_child_role_and_corrupt_tail(tmp_path): - project = tmp_path / 'game' - path = transcript(tmp_path, project, [row('before', '2026-10-22T14:59:59Z'), - row('start', '2026-10-22T15:00:00Z'), row('end', '2026-10-23T15:00:00Z')], True) - path.with_suffix('.meta.json').write_text('{"agentType":"code-reviewer"}', encoding='utf-8') - with path.open('a', encoding='utf-8') as stream: - stream.write('{unfinished') - diagnostics = Counter() - records, _ = report.collect_usage([('slot1', project)], tmp_path, START, END, diagnostics) - assert len(records) == 1 and records[0]['role'] == 'code-reviewer' - assert records[0]['effort'] == 'high' - assert diagnostics['malformed_records'] == 1 - - -def test_missing_metadata_unknown_iteration_and_no_request_id(tmp_path): - project = tmp_path / 'game' - record = row('one') - del record['requestId'] - record['message']['usage']['iterations'].append({'type': 'future_tool'}) - transcript(tmp_path, project, [record], True) - diagnostics = Counter() - records, _ = report.collect_usage([('main', project)], tmp_path, START, END, diagnostics) - assert records[0]['role'] == 'unknown-subagent' - assert diagnostics['fallback_message_keys'] == 1 - assert diagnostics['unknown_iterations'] == 1 - - -def test_quality_retains_unknown_counts_and_marks_legacy_time(tmp_path): - root = tmp_path / 'state' - directory = root / 'm1' / 'verification' - directory.mkdir(parents=True) - legacy = directory / 'M1-review-old.json' - legacy.write_text(json.dumps({'schema': 1, 'unit': 'M1', 'status': 'findings'}), encoding='utf-8') - os.utime(legacy, (START.timestamp(), START.timestamp())) - (directory / 'M1-review-new.json').write_text(json.dumps({ - 'schema': 1, 'unit': 'M1', 'status': 'clean', 'recordedAt': '2026-10-23T05:00:00+09:00', - 'findingsCount': 0, 'fixedCount': 2}), encoding='utf-8') - (root / 'm1' / 'ledger.tsv').write_text('\t'.join(report.LEDGER_HEADER) + - '\n2026-10-23T05:00:00+09:00\tM1\tretry\tpytest-pass\t"literal quote\tsrc.py\n', encoding='utf-8') - quality = report.quality_report([('main', tmp_path)], {'main': root}, START, END, Counter())[0] - assert quality['reviewRounds'] == 2 - assert len(quality['recordedRetries']) == 1 - old = next(r for r in quality['reviews'] if r['timeSource'] == 'file_mtime') - assert old['findingsCount'] == -1 and old['fixedCount'] == -1 - - -def test_quality_keeps_closed_low_status_and_ignores_review_start_records(tmp_path): - root = tmp_path / 'state' - directory = root / 'm1' / 'verification' - directory.mkdir(parents=True) - (directory / 'M1-review-low.json').write_text(json.dumps({ - 'schema': 1, 'unit': 'M1', 'status': 'closed-low', 'recordedAt': '2026-10-23T05:00:00+09:00', - 'findingsCount': 0, 'fixedCount': 1, 'findings': [], 'resolvedIds': ['F1']}), encoding='utf-8') - (directory / 'M1-reviewstart-abc.json').write_text(json.dumps({ - 'schema': 1, 'unit': 'M1', 'recordedAt': '2026-10-23T05:00:00+09:00', 'snapshot': {}}), encoding='utf-8') - (directory / 'M1.review-start.latest.json').write_text(json.dumps({'reviewStart': 'x'}), encoding='utf-8') - diagnostics = Counter() - quality = report.quality_report([('main', tmp_path)], {'main': root}, START, END, diagnostics)[0] - assert [item['status'] for item in quality['reviews']] == ['closed-low'] - assert quality['verificationAttempts'] == [] and not diagnostics['invalid_review_records'] - - -def test_cli_reports_missing_projects_and_does_not_export_content(tmp_path, capsys): - project = tmp_path / 'game' - record = row('one') - record['message']['content'] = [{'type': 'text', 'text': 'private-content-sentinel'}] - transcript(tmp_path, project, [record]) - output = tmp_path / 'report.json' - assert report.main(['--project', f'main={project}', '--project', f'slot={tmp_path / "missing"}', - '--mission-root', f'main={tmp_path / "no-state"}', '--mission-root', f'slot={tmp_path / "no-state"}', - '--claude-home', str(tmp_path), '--start', START.isoformat(), '--end', END.isoformat(), - '--output', str(output)]) == 0 - text = output.read_text(encoding='utf-8') - assert 'private-content-sentinel' not in text - assert len(json.loads(text)['missingTranscriptDirectories']) == 1 - assert 'responses=1' in capsys.readouterr().out - - -def test_timestamp_requires_timezone(): - with pytest.raises(ValueError): - report.timestamp('2026-10-23T00:00:00') - - -def test_missing_adapter_is_reported_without_losing_usage(tmp_path, monkeypatch): - def unavailable(*args): - raise errors.UsageError('missing') - monkeypatch.setattr(configuration, 'locate', unavailable) - quality = report.quality_report([('main', tmp_path)], {}, START, END, Counter()) - assert quality == [{'project': 'main', 'available': False, 'reason': 'UsageError'}] - - -def test_relative_project_path_resolves_to_the_same_transcript_directory(tmp_path, monkeypatch): - project = tmp_path / 'game' - project.mkdir() - transcript(tmp_path, project, [row('one')]) - monkeypatch.chdir(project) - records, missing = report.collect_usage([('main', Path('.'))], tmp_path, START, END, Counter()) - assert len(records) == 1 and not missing - - -def test_invalid_adapter_state_path_keeps_usage_available(tmp_path, monkeypatch): - from types import SimpleNamespace - monkeypatch.setattr(configuration, 'locate', lambda *args: SimpleNamespace(project=str(tmp_path), adapter_path='unused')) - monkeypatch.setattr(configuration, 'read_adapter', lambda *args: {'schema': 1}) - quality = report.quality_report([('main', tmp_path)], {}, START, END, Counter()) - assert quality == [{'project': 'main', 'available': False, 'reason': 'GuardOff'}] - - -def activity_file(tmp_path, activities): - path = tmp_path / 'activities.json' - path.write_text(json.dumps({'schema': 1, 'activities': activities}), encoding='utf-8') - return report.load_activity_map(path) - - -def test_explicit_activity_differs_from_role_and_preserves_all_totals(tmp_path): - project = tmp_path / 'game' - record = row('one') - record['sessionId'] = 'session-one' - record['agentId'] = 'a' - path = transcript(tmp_path, project, [record, row('two')], True) - path.with_suffix('.meta.json').write_text('{"agentType":"reviewer"}', encoding='utf-8') - records, _ = report.collect_usage([('main', project)], tmp_path, START, END, Counter()) - before = report.aggregate(records) - activities = activity_file(tmp_path, [{'sessionId': 'session-one', 'agentId': 'a', - 'taskKind': 'document', 'mission': 'sample-mission', 'unit': 'U1', 'phase': 'draft', 'attempt': 2}]) - report.assign_activities(records, activities) - known = next(item for item in records if item['taskKind'] == 'document') - assert known['role'] == 'reviewer' - assert known['activitySource'] == 'activity-map' - assert known['attempt'] == '2' - assert sum(item['taskKind'] == 'unknown' for item in records) == 1 - assert before == report.aggregate(records) - groups = report.grouped(records, report.ACTIVITY_FIELDS) - assert sum(item['responses'] for item in groups) == before['responses'] - for field in report.TOKEN_FIELDS: - assert sum(item['usage'][field] for item in groups) == before['usage'][field] - assert sum(item['advisor_usage'][field] for item in groups) == before['advisor_usage'][field] - - -def test_concurrent_sessions_and_agents_never_deduplicate_one_another(tmp_path): - project = tmp_path / 'game' - records = [dict(row('same'), sessionId=session) for session in ('first', 'second')] - transcript(tmp_path, project, records) - child = dict(row('same'), sessionId='first', agentId='a') - transcript(tmp_path, project, [child], True) - usage, _ = report.collect_usage([('main', project)], tmp_path, START, END, Counter()) - assert len(usage) == 3 - report.assign_activities(usage, activity_file(tmp_path, [ - {'sessionId': 'first', 'taskKind': 'coordination'}, - {'sessionId': 'first', 'agentId': 'a', 'taskKind': 'verification'}])) - assert {(item['sessionId'], item['agentId'], item['taskKind']) for item in usage} == { - ('first', '', 'coordination'), ('second', '', 'unknown'), ('first', 'a', 'verification')} - - -@pytest.mark.parametrize(('maps', 'metadata', 'status'), [ - ([], '', 'unknown'), - ([{'taskKind': 'review'}, {'taskKind': 'review'}], '', 'ambiguous'), - ([{'taskKind': 'review'}, {'taskKind': 'document'}], '', 'conflict'), - ([{'taskKind': 'review'}], 'implementation', 'conflict'), - ([], 'research', 'assigned'), -]) -def test_activity_missing_ambiguous_conflicting_and_actual_metadata(tmp_path, maps, metadata, status): - project = tmp_path / 'game' - record = dict(row('one'), sessionId='session-one') - if metadata: - record['taskKind'] = metadata - record['message']['content'] = [{'text': 'implementation review document'}] - transcript(tmp_path, project, [record]) - records, _ = report.collect_usage([('main', project)], tmp_path, START, END, Counter()) - activities = activity_file(tmp_path, [dict(item, sessionId='session-one') for item in maps]) - report.assign_activities(records, activities) - assert records[0]['activityStatus'] == status - if status != 'assigned': - assert records[0]['taskKind'] == 'unknown' - else: - assert records[0]['taskKind'] == 'research' - assert records[0]['mission'] == 'unknown' - - -def test_activity_intervals_are_half_open_and_streaming_boundary_is_unknown(tmp_path): - project = tmp_path / 'game' - transcript(tmp_path, project, [dict(row('one'), sessionId='session-one'), - dict(row('two', at='2026-10-23T00:20:00+09:00'), sessionId='session-one')]) - records, _ = report.collect_usage([('main', project)], tmp_path, START, END, Counter()) - activities = activity_file(tmp_path, [{'sessionId': 'session-one', 'taskKind': 'review', - 'startedAt': '2026-10-23T00:10:00+09:00', 'endedAt': '2026-10-23T00:20:00+09:00'}]) - report.assign_activities(records, activities) - assert [item['taskKind'] for item in records] == ['review', 'unknown'] - repeated = dict(row('one', at='2026-10-23T00:20:00+09:00'), sessionId='session-one') - transcript(tmp_path, project, [dict(row('one'), sessionId='session-one'), repeated]) - records, _ = report.collect_usage([('main', project)], tmp_path, START, END, Counter()) - report.assign_activities(records, activities) - assert len(records) == 1 and records[0]['activityStatus'] == 'ambiguous' - - -@pytest.mark.parametrize('activity', [ - {'sessionId': 's'}, {'sessionId': 's', 'taskKind': 'invented'}, - {'sessionId': 's', 'taskKind': 'review', 'attempt': True}, - {'sessionId': 's', 'taskKind': 'review', 'startedAt': '2026-10-23T00:00:00'}, - {'sessionId': 's', 'taskKind': 'review', 'startedAt': END.isoformat(), 'endedAt': START.isoformat()}, -]) -def test_invalid_activity_maps_do_not_invent_classifications(tmp_path, activity): - with pytest.raises(ValueError): - activity_file(tmp_path, [activity]) - - -def test_quality_typed_attempts_reuse_failures_legacy_and_period_boundaries(tmp_path): - root = tmp_path / 'state' - directory = root / 'mission-one' / 'verification' - directory.mkdir(parents=True) - def write(name, value): - path = directory / name - path.write_text(json.dumps(value), encoding='utf-8') - os.utime(path, (START.timestamp(), START.timestamp())) - base = {'schema': 1, 'unit': 'U1', 'recordedAt': START.isoformat(), 'status': 'fail', - 'startedAt': START.isoformat(), 'finishedAt': '2026-10-23T00:00:02+09:00', 'seconds': 2, - 'error': 'raw-failure-sentinel', 'plan': {'commands': [{'argv': ['prompt-sentinel']}]}, - 'executionCounts': {'executed': 1, 'reused': 1}, - 'steps': [{'index': 0, 'status': 'reused', 'seconds': 0}, - {'index': 1, 'status': 'failed', 'seconds': 2, 'exitCode': 1}], - 'failure': {'category': 'command_exit', 'step': 1, 'signature': 'a' * 64, 'repeatCount': 2}} - write('U1-first.json', base) - write('U1-old.json', {'schema': 1, 'unit': 'U1', 'status': 'pass', 'seconds': 1}) - write('U1-end.json', dict(base, recordedAt=END.isoformat())) - write('U1-invalid.json', dict(base, recordedAt='')) - write('U1.latest.json', {'receipt': 'U1-first.json'}) - (root / 'mission-one' / 'ledger.tsv').write_text('\t'.join(report.LEDGER_HEADER) + - '\n' + START.isoformat() + '\tU1\tretry\tpytest-pass\tsame failure\tsource.py\n', encoding='utf-8') - diagnostics = Counter() - quality = report.quality_report([('main', tmp_path)], {'main': root}, START, END, diagnostics)[0] - assert diagnostics['invalid_verification_records'] == 1 - assert quality['verificationSummary'] == {'attempts': 2, 'failed': 1, 'executedSteps': 1, - 'reusedSteps': 1, 'unknownExecutionCounts': 1, - 'retryCounting': 'typed receipt attempts and legacy ledger retries are separate; do not add'} - assert len(quality['recordedRetries']) == 1 - typed = next(item for item in quality['verificationAttempts'] if item['status'] == 'fail') - assert typed['failure']['repeatCount'] == 2 - assert typed['failure']['category'] == 'command_exit' - assert [step['status'] for step in typed['steps']] == ['reused', 'failed'] - assert typed['startedAt'] and typed['finishedAt'] and typed['seconds'] == 2 - legacy = next(item for item in quality['verificationAttempts'] if item['status'] == 'pass') - assert legacy['timeSource'] == 'file_mtime' and legacy['failure']['category'] == 'unknown' - assert 'raw-failure-sentinel' not in json.dumps(quality) - assert 'prompt-sentinel' not in json.dumps(quality) - - -def test_structured_review_counts_only_recorded_identities_and_kinds(): - structured = {'findings': [ - {'id': 'd1', 'kind': 'defect', 'origin': 'new'}, - {'id': 'd2', 'kind': 'defect', 'origin': 'unresolved', 'reason': 'raw-reason-sentinel'}, - {'id': 'd3', 'kind': 'defect', 'origin': 'regression', 'relatedId': 'prior'}, - {'id': 'r1', 'kind': 'rule_violation', 'origin': 'new'}], - 'suggestions': [{'text': 'raw-suggestion-sentinel'}], 'resolvedIds': ['prior'], - 'findingsCount': 400, 'fixedCount': 300} - result = report.review_findings(structured) - assert result == {'identitySource': 'structured', 'byKind': { - 'defect': {'new': 1, 'unresolved': 1, 'regression': 1}, - 'rule_violation': {'new': 1, 'unresolved': 0, 'regression': 0}}, 'suggestions': 1, 'resolved': 1} - assert 'sentinel' not in json.dumps(result) - legacy = report.review_findings({'findingsCount': 4, 'fixedCount': 3}) - assert legacy['identitySource'] == 'unknown' - assert legacy['byKind']['defect']['new'] == -1 - structured['findings'].append(structured['findings'][0]) - assert report.review_findings(structured)['identitySource'] == 'unknown' - - -def test_cli_activity_map_serializes_groups_without_exporting_transcript_content(tmp_path): - project = tmp_path / 'game' - record = dict(row('one'), sessionId='session-one') - record['message']['content'] = [{'text': 'transcript-body-sentinel'}] - record['toolInput'] = {'text': 'tool-input-sentinel'} - transcript(tmp_path, project, [record]) - path = tmp_path / 'activities.json' - path.write_text(json.dumps({'schema': 1, 'activities': [ - {'sessionId': 'session-one', 'taskKind': 'document', 'phase': 'draft'}]}), encoding='utf-8') - output = tmp_path / 'usage.json' - report.main(['--project', f'main={project}', '--mission-root', f'main={tmp_path / "absent"}', - '--claude-home', str(tmp_path), '--start', START.isoformat(), '--end', END.isoformat(), - '--activity-map', str(path), '--output', str(output)]) - serialized = output.read_text(encoding='utf-8') - result = json.loads(serialized) - assert 'sentinel' not in serialized - assert result['byActivity'][0]['taskKind'] == 'document' - assert result['byActivity'][0]['phase'] == 'draft' - assert result['byActivity'][0]['mission'] == 'unknown' - assert result['byActivity'][0]['usage'] == result['total']['usage'] - assert result['activityCoverage'][0]['activitySource'] == 'activity-map' diff --git a/tests/integration/mission/test_verification.py b/tests/integration/mission/test_verification.py deleted file mode 100644 index ac62611..0000000 --- a/tests/integration/mission/test_verification.py +++ /dev/null @@ -1,1985 +0,0 @@ -import json -import os -import subprocess -import sys -import threading -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path - -import pytest -from chef.mission import state as mission_state -from chef.verification import plan as verification_plan -from chef.verification import reviews as verification_reviews -from chef.verification import runner as verification - -from tests.paths import PLUGIN_ROOT - - -@pytest.fixture -def inspect_plan(): - return {"grade": "pytest-pass", "inputs": ["src", "tests"], "environment": {"target": "fictional-secret"}, - "referenceBundle": "references.json", "commands": [ - {"id": "prepare", "argv": ["fictional-tool", "secret-argument"], "reusable": True, "outputs": []}, - {"id": "check", "argv": ["fictional-check"]}, - {"id": "finish", "argv": ["fictional-finish"]}, - ]} - - -@pytest.fixture -def inspect_receipt(inspect_plan): - return {"schema": 1, "runnerVersion": 2, "unit": "M1", "grade": "pytest-pass", "status": "fail", - "plan": inspect_plan, "snapshot": {"src/main.py": "input-hash"}, "results": {}, - "log": "never-open.log", "logHash": "log-hash", "error": "fictional command failure", - "startedAt": "2026-01-01T00:00:00Z", "finishedAt": "2026-01-01T00:00:01Z", "seconds": 1.0, - "executionCounts": {"executed": 1, "reused": 1}, - "failure": {"category": "command_exit", "step": 1, "signature": "failure-signature", - "repeatCount": 3, "previousReceipt": "never-open-previous.json"}, - "priorReceipt": "never-open-previous.json", "priorReceiptHash": "previous-hash", - "steps": [{"index": 0, "id": "prepare", "status": "reused", "sourceReceipt": "never-open-source.json", - "sourceReceiptHash": "source-hash", "sourceStep": 0}, - {"index": 1, "id": "check", "status": "failed", "exitCode": 2}, - {"index": 2, "id": "finish", "status": "not_run"}]} - - -def test_inspect_plan_and_receipt_only_read_source(tmp_path, inspect_plan, inspect_receipt, monkeypatch): - source = tmp_path / "artifact.json" - real_read = Path.read_bytes - opened = [] - - def read(path): - opened.append(path) - assert path == source - return real_read(path) - - def unexpected(*args, **kwargs): - pytest.fail("inspect performed an execution or validity check") - - monkeypatch.setattr(Path, "read_bytes", read) - monkeypatch.setattr(verification.subprocess, "run", unexpected) - monkeypatch.setattr(verification, "validate_plan", unexpected) - monkeypatch.setattr(verification, "validate_receipt", unexpected) - monkeypatch.setattr(verification, "runtime_key", unexpected) - for kind, value in (("plan", inspect_plan), ("receipt", inspect_receipt)): - source.write_text(json.dumps(value), encoding="utf-8") - before = real_read(source) - result = verification.inspect_artifact(source, kind) - assert result["source"] == {"path": str(source.resolve()), "sha256": verification.hashlib.sha256(before).hexdigest()} - assert result["current_validity"] == "not_checked" - assert result["counts"]["inputEntries"] == 2 - assert result["counts"]["referenceBundles"] == 1 - assert result["counts"]["commands"] == 3 - assert result["steps"]["omitted"] == 0 - assert "fictional-secret" not in json.dumps(result) - assert "secret-argument" not in json.dumps(result) - assert "input-hash" not in json.dumps(result) - assert real_read(source) == before - assert opened == [source, source] - assert list(tmp_path.iterdir()) == [source] - assert result["statusCounts"] == {"passed": 0, "failed": 1, "reused": 1, "not_run": 1} - assert result["executionCounts"] == {"executed": 1, "reused": 1} - assert result["failure"]["repeatCount"] == 3 - assert result["failedSteps"]["items"] == [{"index": 1, "id": "check", "exitCode": 2}] - assert result["steps"]["items"][0]["sourceReceipt"] == "never-open-source.json" - assert result["recorded"]["priorReceipt"] == "never-open-previous.json" - - -def test_inspect_recorded_pass_does_not_check_current_inputs(tmp_path, inspect_receipt): - inspect_receipt["status"] = "pass" - inspect_receipt["steps"][1]["status"] = "passed" - inspect_receipt["steps"][2]["status"] = "passed" - inspect_receipt["executionCounts"]["executed"] = 2 - inspect_receipt["error"] = "" - inspect_receipt["failure"] = {"category": "", "step": -1, "repeatCount": 0} - source = tmp_path / "pass.json" - source.write_text(json.dumps(inspect_receipt), encoding="utf-8") - result = verification.inspect_artifact(source, "receipt") - assert result["identity"]["status"] == "pass" - assert result["current_validity"] == "not_checked" - assert result["failedSteps"] == {"items": [], "omitted": 0} - assert not (tmp_path / "never-open.log").exists() - - -def test_inspect_accepts_actual_generated_receipts_and_original_plan(mission): - root, folder, _ = mission - plan = reusable_plan(mission) - assert verification.inspect_artifact(root / "plan.json", "plan")["counts"]["commands"] == 2 - code, first = verify(mission) - assert code == 1 - assert verification.inspect_artifact(first, "receipt")["statusCounts"]["failed"] == 1 - code, second = verify(mission) - assert code == 1 - result = verification.inspect_artifact(second, "receipt") - assert result["executionCounts"] == {"executed": 1, "reused": 1} - assert result["failure"]["repeatCount"] == 2 - plan["commands"][1]["argv"] = [sys.executable, "-c", "pass"] - save_plan(mission) - code, final = verify(mission) - assert code == 0 - assert verification.inspect_artifact(final, "receipt")["identity"]["status"] == "pass" - path, _, _ = verification.record_failure(root, folder, "M1", "fictional invalid plan") - result = verification.inspect_artifact(path, "receipt") - assert result["counts"]["commands"] == 0 - assert result["failure"]["category"] == "plan_invalid" - - -def test_inspect_preflight_failure_and_legacy_absent_steps(tmp_path, inspect_receipt): - source = tmp_path / "fail.json" - inspect_receipt.update(plan={}, steps=[], executionCounts={"executed": 0, "reused": 0}, snapshot={}) - inspect_receipt["failure"].update(category="plan_invalid", step=-1) - source.write_text(json.dumps(inspect_receipt), encoding="utf-8") - result = verification.inspect_artifact(source, "receipt") - assert result["counts"]["commands"] == 0 - assert result["failure"]["category"] == "plan_invalid" - del inspect_receipt["steps"] - del inspect_receipt["executionCounts"] - source.write_text(json.dumps(inspect_receipt), encoding="utf-8") - result = verification.inspect_artifact(source, "receipt") - assert "steps" not in result and "executionCounts" not in result and "statusCounts" not in result - - -@pytest.mark.parametrize("kind,field,value", [ - ("plan", "kind", "receipt"), ("plan", "schema", 2), ("plan", "schema", True), - ("plan", "commands", ["invalid"]), ("plan", "commands", []), ("plan", "inputs", "src"), - ("plan", "environment", []), ("plan", "unit", ["invalid"]), ("plan", "grade", 1), - ("receipt", "kind", "plan"), ("receipt", "schema", "1"), ("receipt", "status", "passed"), - ("receipt", "snapshot", []), ("receipt", "steps", [{}]), ("receipt", "failure", []), - ("receipt", "executionCounts", {"executed": True, "reused": 1}), - ("receipt", "executionCounts", {"executed": 999, "reused": 1}), - ("receipt", "seconds", float("nan")), ("receipt", "plan", []), -]) -def test_inspect_rejects_wrong_artifact_structure(tmp_path, inspect_plan, inspect_receipt, kind, field, value): - artifacts = {"plan": inspect_plan, "receipt": inspect_receipt} - artifacts[kind][field] = value - source = tmp_path / "invalid.json" - source.write_text(json.dumps(artifacts[kind]), encoding="utf-8") - with pytest.raises(verification.VerificationError, match="inspect:"): - verification.inspect_artifact(source, kind) - - -def test_inspect_large_receipt_has_bounded_output_and_late_failure(tmp_path, inspect_receipt): - size = 2000 - long_text = "x" * 10000 - inspect_receipt["plan"]["commands"] = [ - {"id": f"step-{index}-{long_text}", "argv": [long_text]} for index in range(size)] - inspect_receipt["steps"] = [ - {"index": index, "id": f"step-{index}-{long_text}", "status": "reused", "sourceReceipt": long_text, - "sourceReceiptHash": long_text} for index in range(size)] - inspect_receipt["steps"][-1].update(status="failed", exitCode=1) - inspect_receipt["executionCounts"] = {"executed": 1, "reused": size - 1} - inspect_receipt["failure"]["step"] = size - 1 - inspect_receipt["snapshot"] = {f"src/{index}": long_text for index in range(size)} - inspect_receipt["error"] = long_text - source = tmp_path / "large.json" - source.write_text(json.dumps(inspect_receipt), encoding="utf-8") - result = verification.inspect_artifact(source, "receipt") - assert len(json.dumps(result)) < 14000 - assert result["counts"]["snapshotFiles"] == size - assert result["steps"]["omitted"] == size - 8 - assert len(result["steps"]["items"]) == 8 - assert result["failedSteps"]["items"][0]["index"] == size - 1 - assert result["truncatedFields"]["omitted"] > 0 - assert len(result["truncatedFields"]["items"]) == 8 - assert len(result["recorded"]["error"]) == 240 - source.write_text(json.dumps(inspect_receipt["plan"]), encoding="utf-8") - plan_result = verification.inspect_artifact(source, "plan") - assert len(json.dumps(plan_result)) < 4000 - assert plan_result["steps"]["omitted"] == size - 8 - assert len(plan_result["steps"]["items"]) == 8 - assert len(plan_result["truncatedFields"]["items"]) == 8 - - -def resource_settings(tmp_path, *resources): - return {"resourceDir": str(tmp_path / "shared-resources"), "resources": {"pytest-pass": list(resources)}} - - -def allow_command(command): - return command - - -def test_preflight_is_read_only_and_checks_readiness_without_running(mission, monkeypatch): - root, folder, plan = mission - settings = resource_settings(root.parent, "engine") - settings["readiness"] = {"pytest-pass": [{"argv": [sys.executable, "-c", "print('{project}')"]}]} - before = sorted(str(path.relative_to(root)) for path in root.rglob("*")) - def unexpected(*args, **kwargs): - pytest.fail("preflight started a subprocess") - monkeypatch.setattr(verification.subprocess, "run", unexpected) - result = verification.preflight(root, plan, allow_command, settings) - assert json.loads(json.dumps(result)) == result - assert {key: result[key] for key in ("status", "grade", "commandCount", "readinessCount", "resources", "failure")} == { - "status": "pass", "grade": "pytest-pass", "commandCount": 1, - "readinessCount": 1, "resources": ["engine"], "failure": {}} - assert isinstance(result["warnings"], list) - assert result["executionPolicy"]["eligible"] is False - assert result["executionPolicy"]["route"] == "verifier" - assert sorted(str(path.relative_to(root)) for path in root.rglob("*")) == before - assert not (folder / "verification").exists() - assert not Path(settings["resourceDir"]).exists() - - -@pytest.mark.parametrize("change,category", [("cwd", "preflight"), ("executable", "preflight"), - ("control", "preflight"), ("guard", "guard_rejected"), - ("grade", "plan_invalid")]) -def test_preflight_classifies_invalid_plan_and_readiness(mission, change, category): - root, folder, plan = mission - settings = {"grades": ["pytest-pass"], "readiness": {"pytest-pass": [{"argv": [sys.executable, "-c", "pass"]}]}} - command = settings["readiness"]["pytest-pass"][0] - if change == "cwd": - command["cwd"] = "missing" - elif change == "executable": - command["argv"][0] = "fictional-missing-program" - elif change == "control": - command["argv"].append("invalid\nargument") - elif change == "grade": - settings["grades"] = [] - else: - command["argv"].append("forbidden") - def guard(command): - if "forbidden" in command: - raise RuntimeError("fictional guard rejection") - result = verification.preflight(root, plan, guard, settings) - assert result["status"] == "fail" and result["failure"]["category"] == category - assert not (folder / "verification").exists() - - -@pytest.mark.parametrize("names", [["../escape"], ["nested/name"], ["nested\\name"], ["a\nb"], - ["."], ["alpha", "alpha"], ["Alpha", "alpha"], ["CON"], ["lpt1"], [1], "alpha"]) -def test_preflight_rejects_resource_path_injection_and_duplicate_names(mission, names): - root, _, plan = mission - settings = resource_settings(root.parent) - settings["resources"]["pytest-pass"] = names - assert verification.preflight(root, plan, allow_command, settings)["status"] == "fail" - assert not Path(settings["resourceDir"]).exists() - - -@pytest.mark.parametrize("value", ["..", "invalid\nfolder", 0, ""]) -def test_preflight_rejects_invalid_resource_directory(mission, value): - root, _, plan = mission - settings = resource_settings(root.parent, "engine") - settings["resourceDir"] = value - assert verification.preflight(root, plan, allow_command, settings)["failure"]["category"] == "preflight" - - -def test_resources_serialize_distinct_projects_and_release_after_run(mission, tmp_path, monkeypatch): - root, folder, plan = mission - other = tmp_path / "other-project" - other.mkdir() - (other / "src.py").write_text("value = 2\n", encoding="utf-8") - other_plan = {"grade": "pytest-pass", "inputs": ["src.py"], "environment": {"target": "fictional"}, - "commands": [{"argv": [sys.executable, "-c", "pass"]}]} - other_folder = other / "mission" - other_folder.mkdir() - settings = resource_settings(tmp_path, "engine") - entered, finish = threading.Event(), threading.Event() - real_execute = verification.execute_command - def launch(project, command, identity, log): - if project == root: - entered.set() - assert finish.wait(10) - return real_execute(project, command, identity, log) - monkeypatch.setattr(verification, "execute_command", launch) - with ThreadPoolExecutor(max_workers=1) as executor: - first = executor.submit(verification.run, root, folder, "M1", plan, allow_command, settings=settings) - try: - assert entered.wait(10), first.result(timeout=1) - _, busy, reused = verification.run(other, other_folder, "M1", other_plan, allow_command, settings=settings) - assert busy["failure"]["category"] == "resource_busy" and not reused - assert busy["executionCounts"]["executed"] == 0 - assert (Path(settings["resourceDir"]) / "engine.lock").exists() - finally: - finish.set() - assert first.result(timeout=10)[1]["status"] == "pass" - assert not (Path(settings["resourceDir"]) / "engine.lock").exists() - assert verification.run(other, other_folder, "M1", other_plan, allow_command, settings=settings)[1]["status"] == "pass" - - -def test_partial_resource_acquisition_releases_in_sorted_order_without_stale_deletion(mission, tmp_path, monkeypatch): - root, folder, plan = mission - settings = resource_settings(tmp_path, "zeta", "alpha") - directory = Path(settings["resourceDir"]) - directory.mkdir() - blocker = directory / "zeta.lock" - blocker.write_text("999999999\tfictional dead holder\n", encoding="utf-8") - seen = [] - acquire = verification.ResourceLock.acquire - def track(lock): - seen.append(Path(lock.path).stem) - return acquire(lock) - monkeypatch.setattr(verification.ResourceLock, "acquire", track) - record = verification.run(root, folder, "M1", plan, allow_command, settings=settings)[1] - assert record["failure"]["category"] == "resource_busy" - assert seen == ["alpha", "zeta"] - assert not (directory / "alpha.lock").exists() - assert blocker.read_text(encoding="utf-8") == "999999999\tfictional dead holder\n" - assert not (root / "runs").exists() - - -@pytest.mark.parametrize("failure,category", [("exit", "readiness_exit"), ("timeout", "readiness_timeout"), - ("launch", "readiness_launch_error")]) -def test_readiness_failures_do_not_start_validation_and_release_resources(mission, tmp_path, monkeypatch, failure, category): - root, folder, plan = mission - settings = resource_settings(tmp_path, "engine") - settings["readiness"] = {"pytest-pass": [{"argv": [sys.executable, "-c", "pass"], "timeoutSeconds": 1}]} - verification.platform.platform() - def launch(argv, **kwargs): - assert (Path(settings["resourceDir"]) / "engine.lock").is_file() - assert kwargs["stdin"] == subprocess.DEVNULL and kwargs["shell"] is False and kwargs["timeout"] == 1 - if failure == "timeout": - raise subprocess.TimeoutExpired(argv, 1) - if failure == "launch": - raise OSError("fictional readiness launch failure") - return subprocess.CompletedProcess(argv, 7) - monkeypatch.setattr(verification.subprocess, "run", launch) - record = verification.run(root, folder, "M1", plan, allow_command, settings=settings)[1] - assert record["failure"]["category"] == category - assert record["plan"] == plan and record["executionCounts"]["executed"] == 0 - assert all(step["status"] == "not_run" for step in record["steps"]) - assert not (root / "runs").exists() - assert not (Path(settings["resourceDir"]) / "engine.lock").exists() - - -def test_readiness_input_mutation_prevents_validation(mission): - root, folder, plan = mission - settings = {"readiness": {"pytest-pass": [{"argv": [sys.executable, "-c", - "from pathlib import Path; Path('src.py').write_text('changed by readiness')"]}]}} - record = verification.run(root, folder, "M1", plan, allow_command, settings=settings)[1] - assert record["failure"]["category"] == "input_changed" - assert record["cacheIntegrity"]["inputsUnchanged"] is False - assert record["executionCounts"]["executed"] == 0 and not (root / "runs").exists() - - -def test_readiness_runs_before_receipt_reuse_and_only_substitutes_project(mission, tmp_path): - root, folder, plan = mission - settings = resource_settings(tmp_path, "engine") - settings["readiness"] = {"pytest-pass": [{"argv": [sys.executable, "-c", - "import sys; from pathlib import Path; p=Path(sys.argv[1])/'ready-runs'; " - "p.open('a').write('x'); assert sys.argv[2] == '{literal}'", - "{project}", "{literal}"]}]} - first = verification.run(root, folder, "M1", plan, allow_command, settings=settings) - second = verification.run(root, folder, "M1", plan, allow_command, settings=settings) - assert first[1]["status"] == "pass" and second[2] is True and first[0] == second[0] - assert (root / "ready-runs").read_text(encoding="utf-8") == "xx" and (root / "runs").read_text(encoding="utf-8") == "x" - settings["readiness"]["pytest-pass"][0]["argv"] = [sys.executable, "-c", "raise SystemExit(3)"] - failed = verification.run(root, folder, "M1", plan, allow_command, settings=settings) - assert failed[1]["failure"]["category"] == "readiness_exit" and failed[0] != first[0] - assert (root / "runs").read_text(encoding="utf-8") == "x" - - -@pytest.mark.parametrize("explicit", [False, True]) -def test_verification_child_utf8_defaults_preserve_parent_and_explicit_values(mission, monkeypatch, explicit): - root, folder, plan = mission - keys = {"PYTHONUTF8": "0", "PYTHONIOENCODING": "latin-1"} - for key, value in keys.items(): - if explicit: - monkeypatch.setenv(key, value) - else: - monkeypatch.delenv(key, raising=False) - plan["commands"] = [{"argv": [sys.executable, "-c", - "import json,os; from pathlib import Path; " - "Path('child.json').write_text(json.dumps({k:os.environ[k] for k in ['PYTHONUTF8','PYTHONIOENCODING']}))"]}] - before = dict(os.environ) - record = verification.run(root, folder, "M1", plan, allow_command)[1] - assert record["status"] == "pass" and dict(os.environ) == before - expected = {"PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"} - if explicit: - expected = keys - assert json.loads((root / "child.json").read_text(encoding="utf-8")) == expected - - -def test_reference_bundle_preflight_and_receipt_reuse_require_current_sources(mission): - root, folder, plan = mission - source = root / "reference.txt" - source.write_text("fictional rule one", encoding="utf-8") - verification.reference_bundle.snapshot(root, ["reference.txt"], "references.json") - plan["referenceBundle"] = "references.json" - first = verification.run(root, folder, "M1", plan, allow_command) - assert first[1]["status"] == "pass" - source.write_text("fictional rule two", encoding="utf-8") - checked = verification.preflight(root, plan, allow_command) - assert checked["failure"]["category"] == "reference_changed" - with pytest.raises(verification.VerificationError): - verification.validate_receipt(root, folder, "M1", first[1]) - verification.reference_bundle.snapshot(root, ["reference.txt"], "references.json", - expected_sha256=verification.file_hash(root / "references.json")) - second = verification.run(root, folder, "M1", plan, allow_command) - assert second[1]["status"] == "pass" and second[0] != first[0] - assert (root / "runs").read_text(encoding="utf-8") == "xx" - - -def test_reference_bundle_recapture_metadata_invalidates_receipt_and_stage_identity(mission): - root, folder, plan = mission - (root / "reference.txt").write_text("fictional rule", encoding="utf-8") - verification.reference_bundle.snapshot(root, ["reference.txt"], "references.json", revision="first") - plan["referenceBundle"] = "references.json" - plan["commands"][0].update(reusable=True, outputs=[]) - first = verification.run(root, folder, "M1", plan, allow_command) - verification.reference_bundle.snapshot(root, ["reference.txt"], "references.json", revision="second", - expected_sha256=verification.file_hash(root / "references.json")) - second = verification.run(root, folder, "M1", plan, allow_command) - assert first[1]["runner"] != second[1]["runner"] - assert first[1]["steps"][0]["key"] != second[1]["steps"][0]["key"] - assert second[1]["status"] == "pass" and second[1]["executionCounts"] == {"executed": 1, "reused": 0} - - -def test_reference_source_change_during_validation_invalidates_run_integrity(mission): - root, folder, plan = mission - (root / "reference.txt").write_text("fictional original", encoding="utf-8") - verification.reference_bundle.snapshot(root, ["reference.txt"], "references.json") - plan["referenceBundle"] = "references.json" - plan["commands"] = [{"argv": [sys.executable, "-c", - "from pathlib import Path; Path('reference.txt').write_text('fictional changed')"]}] - record = verification.run(root, folder, "M1", plan, allow_command)[1] - assert record["failure"]["category"] == "runtime_changed" - assert record["cacheIntegrity"]["runtimeUnchanged"] is False - assert record["steps"][0]["status"] == "failed" - - -def test_unexpected_runner_exception_still_releases_resources(mission, tmp_path, monkeypatch): - root, folder, plan = mission - settings = resource_settings(tmp_path, "engine") - def launch(*args, **kwargs): - raise RuntimeError("fictional unexpected failure") - monkeypatch.setattr(verification.subprocess, "run", launch) - with pytest.raises(RuntimeError, match="fictional unexpected failure"): - verification.run(root, folder, "M1", plan, allow_command, settings=settings) - assert not (Path(settings["resourceDir"]) / "engine.lock").exists() - - -def readiness_policy(mission): - root, _, _ = mission - (root / "machine-state").write_text("ready", encoding="utf-8") - (root / "readiness.py").write_text( - "from pathlib import Path\nraise SystemExit(int(Path('machine-state').read_text() != 'ready'))\n", - encoding="utf-8", - ) - settings = resource_settings(root.parent, "engine") - settings["readiness"] = {"pytest-pass": [{"argv": [sys.executable, "readiness.py"]}]} - return settings - - -@pytest.mark.parametrize("change", ["resources", "resourceDir", "argv", "timeout", "script"]) -def test_policy_and_readiness_tools_invalidate_receipt_and_stage_reuse(mission, change): - root, folder, plan = mission - settings = readiness_policy(mission) - plan["commands"][0].update(reusable=True, outputs=[]) - first = verification.run(root, folder, "M1", plan, allow_command, settings=settings) - assert first[1]["status"] == "pass" - if change == "resources": - settings["resources"]["pytest-pass"] = ["other-engine"] - elif change == "resourceDir": - settings["resourceDir"] = str(root.parent / "other-resources") - elif change == "argv": - settings["readiness"]["pytest-pass"][0]["argv"].append("extra") - elif change == "timeout": - settings["readiness"]["pytest-pass"][0]["timeoutSeconds"] = 20 - else: - (root / "readiness.py").write_text("raise SystemExit(0)\n", encoding="utf-8") - with pytest.raises(verification.VerificationError): - verification.validate_receipt(root, folder, "M1", first[1], settings=settings) - second = verification.run(root, folder, "M1", plan, allow_command, settings=settings) - assert second[1]["status"] == "pass" and second[2] is False - assert second[1]["executionCounts"] == {"executed": 1, "reused": 0} - assert second[1]["runner"] != first[1]["runner"] - assert second[1]["steps"][0]["key"] != first[1]["steps"][0]["key"] - assert (root / "runs").read_text(encoding="utf-8") == "xx" - - -def test_machine_observation_does_not_invalidate_receipt_or_run_readiness_at_review(mission, monkeypatch): - root, folder, plan = mission - settings = readiness_policy(mission) - path, receipt, _ = verification.run(root, folder, "M1", plan, allow_command, settings=settings) - (root / "machine-state").write_text("closed", encoding="utf-8") - report = root / "review.md" - report.write_text("Fictional independent review", encoding="utf-8") - def unexpected(*args, **kwargs): - pytest.fail("receipt validation reran readiness") - monkeypatch.setattr(verification, "execute_command", unexpected) - verification.validate_receipt(root, folder, "M1", receipt, settings=settings) - verification.validate_receipt(root, folder, "M1", receipt) - review_path = verification.record_review(root, folder, "M1", path, report, "reviewer", "unit", "clean", settings=settings) - verification.validate_review(folder, "M1", path, review_path) - assert verification.review_scope(root, folder, "M1", plan, settings=settings) == [] - - -def test_missing_current_policy_rejects_policy_receipt_but_none_preserves_optional_api(mission): - root, folder, plan = mission - settings = readiness_policy(mission) - _, receipt, _ = verification.run(root, folder, "M1", plan, allow_command, settings=settings) - verification.validate_receipt(root, folder, "M1", receipt, settings=None) - with pytest.raises(verification.VerificationError, match="정책"): - verification.validate_receipt(root, folder, "M1", receipt, settings={}) - _, ordinary, _ = verification.run(root, folder, "M1", plan, allow_command, settings=None) - assert ordinary["status"] == "pass" and "verificationPolicy" not in ordinary - verification.validate_receipt(root, folder, "M1", ordinary, settings=None) - - -@pytest.fixture -def mission(tmp_path, monkeypatch): - root = tmp_path / "project" - adapter = root / ".claude/orchestrator" - adapter.mkdir(parents=True) - (adapter / "adapter.json").write_text(json.dumps({ - "schema": 1, "paths": {"stateDir": "state"}, "verify": {"grades": ["pytest-pass", "editmode-pass"]}, - "guard": {"deny": [{"pattern": "\\bsubmit\\b", "reason": "submit 금지"}]}, - }), encoding="utf-8") - state = root / "state" - state.mkdir() - (state / "ACTIVE").write_text('{"id":"m1","session":"s1"}', encoding="utf-8") - monkeypatch.chdir(root) - monkeypatch.delenv("CLAUDE_PROJECT_DIR", raising=False) - monkeypatch.setenv("HAN_ADAPTERS_DIR", str(tmp_path / "none")) - assert mission_state.main(["init"]) == 0 - assert mission_state.main([ - "unit", "add", "M1", "--goal", "계약", "--files", "src.py", "--done", "동작 보존", - "--verify", "verify", "--timebox", "60", "--forbid", "submit", - ]) == 0 - assert mission_state.main(["unit", "set", "M1", "--status", "doing"]) == 0 - (root / "src.py").write_text("value = 1\n", encoding="utf-8") - script = root / "check.py" - script.write_text("from pathlib import Path\np=Path('runs')\np.write_text(p.read_text()+'x' if p.exists() else 'x')\n", encoding="utf-8") - plan = { - "grade": "pytest-pass", "inputs": ["src.py", "check.py"], "environment": {"target": "test"}, - "commands": [{"argv": [sys.executable, str(script)], "timeoutSeconds": 10}], - } - (root / "plan.json").write_text(json.dumps(plan), encoding="utf-8") - return root, state / "m1", plan - - -def verify(mission): - root, folder, _ = mission - code = mission_state.main(["verify", "M1", "--plan", str(root / "plan.json")]) - path = Path(json.loads((folder / "verification/M1.latest.json").read_text(encoding="utf-8"))["receipt"]) - return code, path - - -def review(mission, receipt, status="clean"): - root, folder, _ = mission - evidence = root / "review.md" - evidence.write_text("독립 리뷰 결과\n", encoding="utf-8") - assert mission_state.main([ - "review", "M1", "--receipt", str(receipt), "--evidence", str(evidence), - "--reviewer", "fresh-reviewer", "--kind", "unit", "--status", status, - ]) == 0 - return Path(json.loads((folder / "verification/M1.review.latest.json").read_text(encoding="utf-8"))["review"]) - - -def test_review_counts_match_status_and_preserve_unknown_legacy_values(mission): - root, folder, _ = mission - _, receipt = verify(mission) - previous = review(mission, receipt) - assert json.loads(previous.read_text(encoding="utf-8"))['findingsCount'] == -1 - args = ['review', 'M1', '--receipt', str(receipt), '--evidence', str(root / 'review.md'), - '--reviewer', 'fresh-reviewer', '--kind', 'unit', '--status', 'clean', - '--findings-count', '0', '--fixed-count', '2'] - assert mission_state.main(args) == 0 - path = Path(json.loads((folder / 'verification/M1.review.latest.json').read_text(encoding="utf-8"))['review']) - record = json.loads(path.read_text(encoding="utf-8")) - assert record['findingsCount'] == 0 and record['fixedCount'] == 2 and record['recordedAt'] - args[args.index('--findings-count') + 1] = '1' - assert mission_state.main(args) == 1 - assert json.loads((folder / 'verification/M1.review.latest.json').read_text(encoding="utf-8"))['review'] == str(path) - - -def test_unchanged_verification_is_reused_and_source_or_environment_change_runs_again(mission): - root, _, plan = mission - first_code, first = verify(mission) - assert first_code == 0 and (root / "runs").read_text(encoding="utf-8") == "x" - assert verify(mission) == (0, first) - assert (root / "runs").read_text(encoding="utf-8") == "x" - (root / "src.py").write_text("value = 2\n") - assert verify(mission)[1] != first - assert (root / "runs").read_text(encoding="utf-8") == "xx" - plan["environment"]["target"] = "other" - (root / "plan.json").write_text(json.dumps(plan)) - verify(mission) - assert (root / "runs").read_text(encoding="utf-8") == "xxx" - - -def test_complete_requires_clean_review_and_current_verification_and_is_idempotent(mission): - root, folder, _ = mission - _, receipt = verify(mission) - findings = review(mission, receipt, "findings") - command = ["complete", "M1", "--receipt", str(receipt), "--review", str(findings), "--done-evidence", "動作確認"] - before = (folder / "ledger.tsv").read_bytes() - assert mission_state.main(command) == 1 - assert (folder / "ledger.tsv").read_bytes() == before - clean = review(mission, receipt) - command[command.index(str(findings))] = str(clean) - assert mission_state.main(command) == 0 - lines = (folder / "ledger.tsv").read_text(encoding="utf-8").splitlines() - assert len(lines) == 2 and "\tpass\tpytest-pass\t" in lines[-1] - assert (folder / "units.tsv").read_text(encoding="utf-8").rstrip().endswith("\tdone") - assert mission_state.main(command) == 0 - assert (folder / "ledger.tsv").read_text(encoding="utf-8").splitlines() == lines - (root / "src.py").write_text("value = 9\n") - assert mission_state.main(command) == 1 - - -def test_verification_command_gets_closed_stdin(mission, monkeypatch): - seen = [] - real_run = verification.subprocess.run - - def spy(*args, **kwargs): - seen.append(kwargs.get("stdin")) - return real_run(*args, **kwargs) - - monkeypatch.setattr(verification.subprocess, "run", spy) - code, _ = verify(mission) - assert code == 0 - assert seen == [verification.subprocess.DEVNULL] - - -def test_failure_is_not_cached_and_guard_rejection_never_runs_command(mission): - root, _, plan = mission - plan["commands"][0]["argv"] = [sys.executable, "-c", "raise SystemExit(7)"] - (root / "plan.json").write_text(json.dumps(plan)) - first_code, first = verify(mission) - assert first_code == 1 and json.loads(first.read_text(encoding="utf-8"))["exitCodes"] == [7] - assert verify(mission)[1] != first - plan["commands"][0]["argv"] = [sys.executable, "-c", "from pathlib import Path; Path('runs').write_text('BAD')", "submit"] - (root / "plan.json").write_text(json.dumps(plan)) - assert mission_state.main(["verify", "M1", "--plan", str(root / "plan.json")]) == 1 - assert not (root / "runs").exists() - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -@pytest.mark.parametrize("latest_status", ["findings", "clean"]) -def test_complete_rejects_superseded_clean_review(mission, runtime, latest_status): - _, folder, _ = mission - _, receipt = verify(mission) - old_clean = review(mission, receipt) - latest = review(mission, receipt, latest_status) - command = [ - "complete", "M1", "--receipt", str(receipt), "--review", str(old_clean), - "--done-evidence", "checked", - ] - before = {name: (folder / name).read_bytes() for name in ("units.tsv", "ledger.tsv")} - assert mission_state.main(command, runtime=runtime) == 1 - assert all((folder / name).read_bytes() == data for name, data in before.items()) - - command[command.index("--review") + 1] = str(latest) - if latest_status == "findings": - assert mission_state.main(command, runtime=runtime) == 1 - assert all((folder / name).read_bytes() == data for name, data in before.items()) - command[command.index("--review") + 1] = str(review(mission, receipt)) - assert mission_state.main(command, runtime=runtime) == 0 - assert (folder / "units.tsv").read_text(encoding="utf-8").rstrip().endswith("\tdone") - - -def test_complete_requires_latest_review_pointer(mission): - _, folder, _ = mission - _, receipt = verify(mission) - clean = review(mission, receipt) - (folder / "verification/M1.review.latest.json").unlink() - before = {name: (folder / name).read_bytes() for name in ("units.tsv", "ledger.tsv")} - assert mission_state.main([ - "complete", "M1", "--receipt", str(receipt), "--review", str(clean), - "--done-evidence", "checked", - ]) == 1 - assert all((folder / name).read_bytes() == data for name, data in before.items()) - - -def test_editmode_rejects_zero_tests_wrong_project_and_stale_result(mission): - root, _, plan = mission - plan["grade"] = "editmode-pass" - plan["results"] = [{ - "path": "result.json", "equals": {"status": "passed"}, "positive": ["tests.0.startedCount"], - "projectField": "projectPath", - }] - for project, count, expected in [(str(root), 0, 1), (str(root.parent), 2, 1), (str(root), 2, 0)]: - payload = {"status": "passed", "projectPath": project, "tests": [{"startedCount": count}]} - plan["commands"][0]["argv"] = [sys.executable, "-c", f"from pathlib import Path; Path('result.json').write_text({json.dumps(payload)!r})"] - (root / "plan.json").write_text(json.dumps(plan)) - assert verify(mission)[0] == expected - plan["commands"][0]["argv"] = [sys.executable, "-c", "pass"] - (root / "plan.json").write_text(json.dumps(plan)) - assert verify(mission)[0] == 1 - - -def test_changed_during_run_and_tampered_results_are_rejected(mission): - root, folder, plan = mission - _, receipt = verify(mission) - data = json.loads(receipt.read_text(encoding="utf-8")) - Path(data["log"]).write_text("changed") - with pytest.raises(verification.VerificationError, match="로그"): - verification.validate_receipt(str(root), str(folder), "M1", data) - plan["commands"][0]["argv"] = [sys.executable, "-c", "from pathlib import Path; Path('src.py').write_text('changed')"] - (root / "plan.json").write_text(json.dumps(plan)) - assert verify(mission)[0] == 1 - - -def test_review_scope_reports_additions_and_deletions(mission): - root, folder, plan = mission - source = root / "src" - source.mkdir() - (source / "a.py").write_text("a") - plan["inputs"] = ["src"] - (root / "plan.json").write_text(json.dumps(plan)) - _, receipt = verify(mission) - review(mission, receipt) - plan["unitBrief"] = json.loads(receipt.read_text(encoding="utf-8"))["plan"]["unitBrief"] - assert verification.review_scope(str(root), str(folder), "M1", plan) == [] - (source / "b.py").write_text("b") - (source / "a.py").unlink() - assert verification.review_scope(str(root), str(folder), "M1", plan) == ["src/a.py", "src/b.py"] - - -def test_context_is_bounded_and_keeps_history_outside_prompt(mission, capsys): - _, folder, _ = mission - for index in range(20): - assert mission_state.main([ - "decision", "add", "--what", f"decision {index}", "--chosen", "x" * 500, - "--why", "reason", "--affects", "M1", - ]) == 0 - capsys.readouterr() - assert mission_state.main(["context"]) == 0 - output = capsys.readouterr().out - assert len(output) < 2200 and "D20" in output and "D1:" not in output - assert str(folder / "mission.md") in output - assert (folder / "decisions.tsv").stat().st_size > 10000 - - -def test_codex_entrypoint_uses_same_receipts(mission): - root, _, _ = mission - assert mission_state.main(["verify", "M1", "--plan", str(root / "plan.json")], runtime="codex") == 0 - assert (root / "runs").read_text(encoding="utf-8") == "x" - assert verify(mission)[0] == 0 and (root / "runs").read_text(encoding="utf-8") == "x" - - -def test_inputs_outside_project_are_rejected(mission): - root, _, plan = mission - plan["inputs"] = ["../secret"] - (root / "plan.json").write_text(json.dumps(plan)) - assert mission_state.main(["verify", "M1", "--plan", str(root / "plan.json")]) == 1 - assert not (root / "runs").exists() - - -def test_complete_rejects_changed_contract_and_review_evidence(mission): - root, _, _ = mission - _, receipt = verify(mission) - checked = review(mission, receipt) - command = ["complete", "M1", "--receipt", str(receipt), "--review", str(checked), "--done-evidence", "checked"] - (root / "review.md").write_text("tampered") - assert mission_state.main(command) == 1 - checked = review(mission, receipt) - command[command.index("--review") + 1] = str(checked) - assert mission_state.main(["unit", "set", "M1", "--done", "새 완료 조건"]) == 0 - assert mission_state.main(command) == 1 - - -def test_later_failed_run_cannot_be_hidden_by_an_older_pass(mission): - root, _, plan = mission - _, receipt = verify(mission) - checked = review(mission, receipt) - plan["commands"][0]["argv"] = [sys.executable, "-c", "raise SystemExit(7)"] - (root / "plan.json").write_text(json.dumps(plan)) - assert verify(mission)[0] == 1 - assert mission_state.main([ - "complete", "M1", "--receipt", str(receipt), "--review", str(checked), "--done-evidence", "old pass", - ]) == 1 - - -def reusable_plan(mission): - root, _, plan = mission - script = root / "build.py" - script.write_text( - "from pathlib import Path\n" - "counter=Path('build_runs')\n" - "counter.write_text(counter.read_text()+'x' if counter.exists() else 'x')\n" - "Path('artifact').mkdir(exist_ok=True)\n" - "Path('artifact/result.json').write_text('{\"status\":\"passed\"}')\n", - encoding="utf-8", - ) - plan.update(inputs=["src.py"], commands=[ - {"id": "build", "argv": [sys.executable, "build.py"], "reusable": True, "outputs": ["artifact"]}, - {"id": "check", "argv": [sys.executable, "-c", "raise SystemExit(7)"]}, - ], results=[{"path": "artifact/result.json", "command": "build", "equals": {"status": "passed"}}]) - save_plan(mission) - return plan - - -def save_plan(mission): - root, _, plan = mission - (root / "plan.json").write_text(json.dumps(plan), encoding="utf-8") - - -def receipt_data(path): - return json.loads(path.read_text(encoding="utf-8")) - - -def test_later_argv_fix_reuses_only_valid_prefix_and_original_result(mission): - root, folder, _ = mission - plan = reusable_plan(mission) - code, first = verify(mission) - assert code == 1 - second = verify(mission)[1] - record = receipt_data(second) - assert [step["status"] for step in record["steps"]] == ["reused", "failed"] - assert record["steps"][0]["sourceReceipt"] == str(first) - assert record["failure"]["repeatCount"] == 2 - assert record["priorReceipt"] == str(first) - plan["commands"][1]["argv"] = [sys.executable, "-c", "pass"] - save_plan(mission) - code, final = verify(mission) - record = receipt_data(final) - assert code == 0 and (root / "build_runs").read_text(encoding="utf-8") == "x" - assert record["executionCounts"] == {"executed": 1, "reused": 1} - assert record["steps"][0]["sourceReceipt"] == str(first) - verification.validate_receipt(root, folder, "M1", record) - assert verify(mission) == (0, final) - - -@pytest.mark.parametrize("change", ["output-add", "output-delete", "output-edit", "input", "environment", - "script", "brief", "original-log", "original-receipt"]) -def test_reuse_invalidates_changed_evidence_and_dependencies(mission, monkeypatch, change): - root, _, _ = mission - plan = reusable_plan(mission) - _, first = verify(mission) - if change == "output-add": - (root / "artifact/extra").write_text("extra") - elif change == "output-delete": - (root / "artifact/result.json").unlink() - elif change == "output-edit": - (root / "artifact/result.json").write_text('{"status":"failed"}') - elif change == "input": - (root / "src.py").write_text("changed") - elif change == "environment": - plan["environment"]["target"] = "changed" - elif change == "script": - script = root / "build.py" - script.write_text(script.read_text(encoding="utf-8") + "\nvalue=2\n", encoding="utf-8") - elif change == "brief": - assert mission_state.main(["unit", "set", "M1", "--done", "new completion condition"]) == 0 - elif change == "original-log": - Path(receipt_data(first)["log"]).write_text("tampered") - else: - verify(mission) - first.write_text(first.read_text(encoding="utf-8") + " ", encoding="utf-8") - plan["commands"][1]["argv"] = [sys.executable, "-c", "pass"] - save_plan(mission) - assert verify(mission)[0] == 0 - assert (root / "build_runs").read_text(encoding="utf-8") == "xx" - - -def runtime_key_in_new_process(mission, cwd, extra): - root, _, _ = mission - code = ("import json, sys; sys.path.insert(0, sys.argv[1]); import verification; " - "print(verification.runtime_key(sys.argv[2], json.load(open(sys.argv[3], encoding='utf-8'))))") - done = subprocess.run( - [sys.executable, "-c", code, str((PLUGIN_ROOT / "skills/mission/scripts")), str(root), str(root / "plan.json")], - cwd=cwd, env={**os.environ, **extra}, capture_output=True, text=True, check=True, - ) - return done.stdout.strip() - - -def test_runtime_key_ignores_session_and_shell_environment_across_processes(mission, tmp_path): - root, _, _ = mission - first = runtime_key_in_new_process(mission, root, {"PWD": str(root), "CLAUDE_SESSION_ID": "session-a"}) - second = runtime_key_in_new_process(mission, tmp_path, { - "PWD": str(tmp_path), "CLAUDE_SESSION_ID": "session-b", "CLAUDE_AGENT_ID": "agent-b", - "SHLVL": "7", "FICTIONAL_CHECK_MODE": "changed", - }) - assert first == second - - -def test_undeclared_environment_change_still_reuses_receipt_and_steps(mission, monkeypatch): - root, _, _ = mission - _, first = verify(mission) - monkeypatch.setenv("PWD", str(root / "elsewhere")) - monkeypatch.setenv("CLAUDE_SESSION_ID", "other-session") - monkeypatch.setenv("FICTIONAL_CHECK_MODE", "changed") - assert verify(mission) == (0, first) - assert (root / "runs").read_text(encoding="utf-8") == "x" - clean = review(mission, first) - assert mission_state.main(["complete", "M1", "--receipt", str(first), "--review", str(clean), - "--done-evidence", "checked"]) == 0 - - plan = reusable_plan(mission) - plan["commands"][1]["argv"] = [sys.executable, "-c", "raise SystemExit(7)"] - save_plan(mission) - verify(mission) - monkeypatch.setenv("FICTIONAL_CHECK_MODE", "changed-again") - record = receipt_data(verify(mission)[1]) - assert [step["status"] for step in record["steps"]] == ["reused", "failed"] - assert (root / "build_runs").read_text(encoding="utf-8") == "x" - - -def test_declared_environment_value_is_part_of_runtime_identity(mission, monkeypatch): - root, _, plan = mission - plan["environmentKeys"] = ["FICTIONAL_CHECK_MODE"] - save_plan(mission) - monkeypatch.delenv("FICTIONAL_CHECK_MODE", raising=False) - _, first = verify(mission) - assert verify(mission) == (0, first) - monkeypatch.setenv("FICTIONAL_CHECK_MODE", "strict") - with pytest.raises(verification.VerificationError, match="런타임"): - verification.validate_receipt(root, mission[1], "M1", receipt_data(first)) - second = verify(mission)[1] - assert second != first and (root / "runs").read_text(encoding="utf-8") == "xx" - assert verify(mission) == (0, second) - monkeypatch.setenv("FICTIONAL_CHECK_MODE", "lenient") - assert verify(mission)[1] != second and (root / "runs").read_text(encoding="utf-8") == "xxx" - - -def test_declared_environment_value_invalidates_reusable_step(mission, monkeypatch): - root, _, _ = mission - plan = reusable_plan(mission) - plan["environmentKeys"] = ["FICTIONAL_CHECK_MODE"] - save_plan(mission) - monkeypatch.setenv("FICTIONAL_CHECK_MODE", "strict") - verify(mission) - monkeypatch.setenv("FICTIONAL_CHECK_MODE", "lenient") - verify(mission) - assert (root / "build_runs").read_text(encoding="utf-8") == "xx" - - -@pytest.mark.parametrize("value", ["PATH", ["A", "A"], [""], ["A=B"], [1], ["A\nB"]]) -def test_environment_keys_must_be_unique_variable_names(mission, value): - root, _, plan = mission - plan["environmentKeys"] = value - save_plan(mission) - assert mission_state.main(["verify", "M1", "--plan", str(root / "plan.json")]) == 1 - assert not (root / "runs").exists() - - -def test_receipt_with_old_runtime_fingerprint_is_not_trusted_and_reruns(mission): - root, folder, _ = mission - _, receipt = verify(mission) - data = receipt_data(receipt) - data.pop("runnerVersion") - receipt.write_text(json.dumps(data), encoding="utf-8") - with pytest.raises(verification.VerificationError, match="다시 실행"): - verification.validate_receipt(root, folder, "M1", data) - evidence = root / "review.md" - evidence.write_text("independent review\n", encoding="utf-8") - assert mission_state.main([ - "review", "M1", "--receipt", str(receipt), "--evidence", str(evidence), - "--reviewer", "fresh-reviewer", "--kind", "unit", "--status", "clean", - ]) == 1 - second = verify(mission)[1] - assert second != receipt and (root / "runs").read_text(encoding="utf-8") == "xx" - assert receipt_data(second)["runnerVersion"] == verification.RUNNER_VERSION - - -def test_force_and_default_nonreusable_steps_execute_again(mission): - root, _, _ = mission - plan = reusable_plan(mission) - plan["commands"][0].pop("reusable") - save_plan(mission) - verify(mission) - verify(mission) - assert (root / "build_runs").read_text(encoding="utf-8") == "xx" - plan["commands"][0]["reusable"] = True - plan["commands"][1]["argv"] = [sys.executable, "-c", "pass"] - save_plan(mission) - assert verify(mission)[0] == 0 - assert mission_state.main(["verify", "M1", "--plan", str(root / "plan.json"), "--force"]) == 0 - assert (root / "build_runs").read_text(encoding="utf-8") == "xxxx" - - -def test_reexecuted_earlier_step_forces_later_reusable_step_to_execute(mission): - root, _, plan = mission - plan["commands"] = [ - {"argv": [sys.executable, "check.py"]}, - {"argv": [sys.executable, "check.py"], "reusable": True, "outputs": []}, - {"argv": [sys.executable, "-c", "raise SystemExit(7)"]}, - ] - save_plan(mission) - verify(mission) - verify(mission) - assert (root / "runs").read_text(encoding="utf-8") == "xxxx" - - -def test_script_after_interpreter_flags_is_part_of_reuse_identity(mission): - root, _, _ = mission - plan = reusable_plan(mission) - plan["commands"][0]["argv"] = [sys.executable, "-B", "build.py"] - save_plan(mission) - verify(mission) - script = root / "build.py" - script.write_text(script.read_text(encoding="utf-8") + "\nvalue=3\n", encoding="utf-8") - verify(mission) - assert (root / "build_runs").read_text(encoding="utf-8") == "xx" - - -@pytest.mark.parametrize("later_exit", [False, True]) -def test_failed_run_with_mutated_input_cannot_reuse_steps_after_source_restoration(mission, later_exit): - root, folder, plan = mission - (root / "src.py").write_text("original", encoding="utf-8") - script = root / "mutating.py" - script.write_text( - "from pathlib import Path\n" - "Path('src.py').write_text('changed')\n" - "Path('artifact').write_text(Path('src.py').read_text())\n", encoding="utf-8", - ) - plan.update(inputs=["src.py", "mutating.py"], commands=[ - {"argv": [sys.executable, "mutating.py"], "reusable": True, "outputs": ["artifact"]}, - ]) - if later_exit: - plan["commands"].append({"argv": [sys.executable, "-c", "raise SystemExit(7)"]}) - save_plan(mission) - code, first = verify(mission) - assert code == 1 and receipt_data(first)["cacheIntegrity"]["status"] == "invalid" - assert receipt_data(first)["failure"]["category"] == "input_changed" - (root / "src.py").write_text("original", encoding="utf-8") - if later_exit: - plan["commands"][1]["argv"] = [sys.executable, "-c", "pass"] - save_plan(mission) - code, second = verify(mission) - record = receipt_data(second) - assert code == 1 and record["executionCounts"]["reused"] == 0 - assert record["failure"]["category"] == "input_changed" - assert (root / "artifact").read_text(encoding="utf-8") == "changed" - with pytest.raises(verification.VerificationError): - verification.validate_receipt(root, folder, "M1", record) - - -def test_later_failing_command_mutation_invalidates_earlier_valid_prefix(mission): - root, _, _ = mission - plan = reusable_plan(mission) - plan["commands"][1]["argv"] = [sys.executable, "-c", - "from pathlib import Path; Path('src.py').write_text('changed'); raise SystemExit(7)"] - save_plan(mission) - code, first = verify(mission) - record = receipt_data(first) - assert code == 1 and record["failure"]["category"] == "input_changed" - assert record["steps"][1]["exitCode"] == 7 and record["cacheIntegrity"]["status"] == "invalid" - (root / "src.py").write_text("value = 1\n", encoding="utf-8") - plan["commands"][1]["argv"] = [sys.executable, "-c", "pass"] - save_plan(mission) - assert verify(mission)[0] == 0 - assert (root / "build_runs").read_text(encoding="utf-8") == "xx" - - -def test_failed_receipt_without_global_integrity_proof_cannot_supply_prefix(mission): - root, _, _ = mission - reusable_plan(mission) - _, first = verify(mission) - record = receipt_data(first) - record.pop("cacheIntegrity") - verification.write_json(first, record) - verify(mission) - assert (root / "build_runs").read_text(encoding="utf-8") == "xx" - - -@pytest.mark.parametrize("flags", [[], ["-B"], ["-X", "utf8", "-W", "ignore"]]) -@pytest.mark.parametrize("declared_result", [False, True]) -def test_legacy_script_output_arguments_do_not_change_runtime_identity(mission, flags, declared_result): - root, _, plan = mission - (root / "writer.py").write_text( - "import sys\nfrom pathlib import Path\nPath(sys.argv[1]).write_text('{\"status\":\"passed\"}')\n", - encoding="utf-8", - ) - plan["inputs"] = ["src.py", "writer.py"] - plan["commands"] = [{"argv": [sys.executable, *flags, "writer.py", "output.json"]}] - if declared_result: - plan["results"] = [{"path": "output.json", "equals": {"status": "passed"}}] - save_plan(mission) - assert verify(mission)[0] == 0 - assert mission_state.main(["verify", "M1", "--plan", str(root / "plan.json"), "--force"]) == 0 - - -@pytest.mark.parametrize("arguments", [["-c", "program", "output.py"], ["-m", "module", "output.py"], - ["-cprogram", "output.py"], ["-mmodule", "output.py"], ["-", "output.py"]]) -def test_python_inline_and_module_arguments_are_not_scripts(mission, arguments): - root, _, _ = mission - (root / "output.py").write_text("first", encoding="utf-8") - command = {"argv": [sys.executable, *arguments]} - first = verification.command_runtime(root, command) - (root / "output.py").write_text("changed", encoding="utf-8") - assert verification.command_runtime(root, command) == first - - -@pytest.mark.parametrize("change", ["missing-outputs", "missing-producer", "wrong-producer", "unowned-result"]) -def test_reusable_result_requires_explicit_producer_and_owned_outputs(mission, change): - root, _, _ = mission - plan = reusable_plan(mission) - if change == "missing-outputs": - plan["commands"][0].pop("outputs") - elif change == "missing-producer": - plan["results"][0].pop("command") - elif change == "wrong-producer": - plan["results"][0]["command"] = "absent" - else: - plan["results"][0]["command"] = 1 - save_plan(mission) - code, path = verify(mission) - assert code == 1 and receipt_data(path)["failure"]["category"] == "plan_invalid" - assert not (root / "build_runs").exists() - - -def test_result_freshness_is_checked_at_its_producer_not_later_command(mission): - root, _, plan = mission - (root / "result.json").write_text('{"status":"passed"}') - plan["commands"] = [ - {"id": "producer", "argv": [sys.executable, "-c", "pass"], "outputs": ["result.json"]}, - {"argv": [sys.executable, "-c", "from pathlib import Path; Path('result.json').write_text('{}')"]}, - ] - plan["results"] = [{"path": "result.json", "command": "producer", "equals": {"status": "passed"}}] - save_plan(mission) - code, path = verify(mission) - record = receipt_data(path) - assert code == 1 and record["failure"]["category"] == "result_invalid" - assert record["steps"][1]["status"] == "not_run" - assert json.loads((root / "result.json").read_text(encoding="utf-8"))["status"] == "passed" - - -@pytest.mark.parametrize("change,category", [("control", "preflight"), ("cwd-missing", "preflight"), - ("cwd-outside", "preflight"), ("executable", "preflight"), - ("plan", "plan_invalid"), ("guard", "guard_rejected")]) -def test_prelaunch_failures_supersede_old_pass_and_never_execute(mission, change, category): - root, folder, plan = mission - _, old = verify(mission) - checked = review(mission, old) - if change == "control": - plan["commands"][0]["argv"].append("bad\nargument") - elif change == "cwd-missing": - plan["commands"][0]["cwd"] = "missing" - elif change == "cwd-outside": - plan["commands"][0]["cwd"] = ".." - elif change == "executable": - plan["commands"][0]["argv"][0] = "fictional-missing-check-program" - elif change == "plan": - plan["commands"] = [] - else: - plan["commands"][0]["argv"].append("submit") - save_plan(mission) - code, path = verify(mission) - record = receipt_data(path) - assert code == 1 and path != old and record["failure"]["category"] == category - assert record["startedAt"] and record["finishedAt"] and record["recordedAt"] - assert (root / "runs").read_text(encoding="utf-8") == "x" - assert mission_state.main(["complete", "M1", "--receipt", str(old), "--review", str(checked), - "--done-evidence", "old proof"]) == 1 - assert receipt_data(folder / "verification/M1.latest.json")["receipt"] == str(path) - - -def test_resolved_executable_is_executed_relative_to_command_cwd(mission, monkeypatch): - root, _, plan = mission - work = root / "work" - work.mkdir() - local = work / Path(sys.executable).name - local.write_bytes(b"fictional executable identity") - local.chmod(0o755) - plan["commands"] = [{"cwd": "work", "argv": [local.name, "-c", "pass"]}] - seen = [] - - def launch(argv, **kwargs): - seen.append((argv, kwargs)) - return verification.subprocess.CompletedProcess(argv, 0) - - monkeypatch.setattr(verification.subprocess, "run", launch) - save_plan(mission) - assert verify(mission)[0] == 0 - assert seen[0][0][0] == str(local.resolve()) - assert seen[0][1]["cwd"] == work.resolve() and seen[0][1]["shell"] is False - - -@pytest.mark.parametrize("failure,category", [("timeout", "timeout"), ("launch", "launch_error"), - ("input", "input_changed"), ("runtime", "runtime_changed")]) -def test_typed_execution_failures(mission, monkeypatch, failure, category): - root, _, plan = mission - if failure in ("timeout", "launch"): - def launch(argv, **kwargs): - if failure == "timeout": - raise verification.subprocess.TimeoutExpired(argv, 1) - raise OSError("fictional launch failure") - monkeypatch.setattr(verification.subprocess, "run", launch) - elif failure == "input": - plan["commands"][0]["argv"] = [sys.executable, "-c", "from pathlib import Path; Path('src.py').write_text('changed')"] - else: - plan["environmentKeys"] = ["FICTIONAL_RUNTIME_MODE"] - real = verification.subprocess.run - def launch(*args, **kwargs): - result = real(*args, **kwargs) - monkeypatch.setenv("FICTIONAL_RUNTIME_MODE", "changed") - return result - monkeypatch.setattr(verification.subprocess, "run", launch) - save_plan(mission) - code, path = verify(mission) - assert code == 1 and receipt_data(path)["failure"]["category"] == category - - -def structured_review(mission, receipt, number, findings, resolved=(), status="findings", **counts): - root, folder, _ = mission - source = root / f"findings-{number}.json" - source.write_text(json.dumps({"schema": 1, "findings": findings, "resolvedIds": list(resolved), - "suggestions": [{"text": "optional fictional improvement"}]}), encoding="utf-8") - evidence = root / f"review-{number}.md" - evidence.write_text(f"Fictional independent review {number}\n", encoding="utf-8") - path = verification.record_review(root, folder, "M1", receipt, evidence, "reviewer", "unit", status, - findings_input=source, **counts) - return Path(path) - - -def finding(identity="F1", kind="defect", origin="new", **fields): - return {"id": identity, "kind": kind, "origin": origin, "reason": "Fictional source contract mismatch", **fields} - - -def test_structured_reviews_preserve_identity_resolution_regression_and_counts(mission): - root, folder, _ = mission - _, receipt = verify(mission) - first = structured_review(mission, receipt, 1, [finding(), finding("F2", "rule_violation")]) - second = structured_review(mission, receipt, 2, [finding(origin="unresolved", relatedId="F1")], ["F2"]) - clean = structured_review(mission, receipt, 3, [], ["F1"], "clean") - record = receipt_data(clean) - assert record["findingsCount"] == 0 and record["fixedCount"] == 1 and record["round"] == 3 - assert record["previousReview"] == str(second) and record["previousReviewHash"] == verification.file_hash(second) - assert record["diagnostics"] == [] and receipt_data(first)["newFindingsCount"] == 2 - verification.validate_review(folder, "M1", receipt, clean) - regression = structured_review(mission, receipt, 4, [finding("F3", origin="regression", relatedId="F1")]) - assert receipt_data(regression)["newFindingsCount"] == 0 and receipt_data(regression)["diagnostics"] - with pytest.raises(verification.VerificationError, match="마지막 리뷰"): - verification.validate_review(folder, "M1", receipt, clean) - - -@pytest.mark.parametrize("invalid", ["new-existing", "unresolved-new", "regression-open", "regression-no-link", - "duplicate", "kind", "missing-reason", "count", "drop", "legacy-drop"]) -def test_structured_reviews_reject_unfounded_identity_and_clean_claims(mission, invalid): - root, folder, _ = mission - _, receipt = verify(mission) - previous = structured_review(mission, receipt, 1, [finding()]) - data = [finding(origin="unresolved", relatedId="F1")] - status, resolved, counts = "findings", [], {} - if invalid == "new-existing": - data = [finding()] - elif invalid == "unresolved-new": - data.append(finding("F2", origin="unresolved")) - elif invalid == "regression-open": - data.append(finding("F2", origin="regression", relatedId="F1")) - elif invalid == "regression-no-link": - data.append(finding("F2", origin="regression")) - elif invalid == "duplicate": - data *= 2 - elif invalid == "kind": - data[0]["kind"] = "suggestion" - elif invalid == "missing-reason": - data.append(finding("F2", reason="")) - elif invalid == "count": - counts["findings_count"] = 2 - elif invalid == "drop": - data, status = [], "clean" - else: - with pytest.raises(verification.VerificationError, match="findings-input"): - verification.record_review(root, folder, "M1", receipt, root / "review-1.md", "reviewer", "unit", "clean") - return - with pytest.raises(verification.VerificationError): - structured_review(mission, receipt, 2, data, resolved, status, **counts) - assert receipt_data(folder / "verification/M1.review.latest.json")["review"] == str(previous) - - -def test_review_cli_accepts_structured_findings_and_rejects_changed_source(mission): - root, folder, _ = mission - _, receipt = verify(mission) - source = root / "findings.json" - source.write_text('{"findings":[],"resolvedIds":[]}', encoding="utf-8") - report = root / "report.md" - report.write_text("Fictional review evidence", encoding="utf-8") - assert mission_state.main(["review", "M1", "--receipt", str(receipt), "--evidence", str(report), - "--reviewer", "reviewer", "--kind", "unit", "--status", "clean", - "--findings-input", str(source)]) == 0 - path = Path(receipt_data(folder / "verification/M1.review.latest.json")["review"]) - source.write_text('{"findings":[{}]}', encoding="utf-8") - with pytest.raises(verification.VerificationError, match="원본"): - verification.validate_review(folder, "M1", receipt, path) - - -def low(identity="F1", kind="defect", **fields): - return finding(identity, kind, severity="low", **fields) - - -def with_unit_brief(mission, receipt): - _, _, plan = mission - return {**plan, "unitBrief": receipt_data(receipt)["plan"]["unitBrief"]} - - -def start_args(mission): - root, _, _ = mission - return ["review-start", "M1", "--plan", str(root / "plan.json")] - - -def review_with_start(mission, receipt, status="clean"): - assert mission_state.main(start_args(mission)) == 0 - return review(mission, receipt, status) - - -def latest_review_pointer(folder): - return (folder / "verification/M1.review.latest.json").read_text(encoding="utf-8") - - -def test_finding_severity_is_optional_and_restricted(mission): - root, folder, _ = mission - _, receipt = verify(mission) - first = structured_review(mission, receipt, 1, [finding(severity="low"), finding("F2", "rule_violation")]) - assert [item.get("severity") for item in receipt_data(first)["findings"]] == ["low", None] - with pytest.raises(verification.VerificationError, match="severity"): - structured_review(mission, receipt, 2, [finding("F3", severity="minor")]) - assert receipt_data(folder / "verification/M1.review.latest.json")["review"] == str(first) - - -def test_closed_low_closes_low_findings_and_passes_complete(mission): - root, folder, _ = mission - _, receipt = verify(mission) - structured_review(mission, receipt, 1, [low(), low("F2", "rule_violation")]) - closed = structured_review(mission, receipt, 2, [], ["F1", "F2"], "closed-low") - record = receipt_data(closed) - assert record["status"] == "closed-low" and record["findingsCount"] == 0 and record["closedLowIds"] == ["F1", "F2"] - verification.validate_review(folder, "M1", receipt, closed) - command = ["complete", "M1", "--receipt", str(receipt), "--review", str(closed), "--done-evidence", "checked fix diff"] - assert mission_state.main(command) == 0 - assert (folder / "units.tsv").read_text(encoding="utf-8").rstrip().endswith("\tdone") - - -@pytest.mark.parametrize("case", [ - "no-history", "prior-clean", "consecutive", "prior-high", "prior-unlabeled", "prior-regression", - "findings-left", "resolved-partial", "count", "unstructured-prior"]) -def test_closed_low_rejects_when_conditions_fail(mission, case): - root, folder, _ = mission - _, receipt = verify(mission) - resolved, data, counts = ["F1"], [], {} - if case == "prior-clean": - structured_review(mission, receipt, 1, [], [], "clean") - elif case == "consecutive": - structured_review(mission, receipt, 1, [low()]) - structured_review(mission, receipt, 2, [], ["F1"], "closed-low") - elif case == "prior-high": - structured_review(mission, receipt, 1, [finding(severity="high")]) - elif case == "prior-unlabeled": - structured_review(mission, receipt, 1, [low(), finding("F2")]) - resolved = ["F1", "F2"] - elif case == "prior-regression": - structured_review(mission, receipt, 1, [low()]) - structured_review(mission, receipt, 2, [], ["F1"], "clean") - structured_review(mission, receipt, 3, [low("F3", origin="regression", relatedId="F1")]) - resolved = ["F3"] - elif case == "findings-left": - structured_review(mission, receipt, 1, [low(), low("F2")]) - data = [low("F2", origin="unresolved")] - elif case == "resolved-partial": - structured_review(mission, receipt, 1, [low(), low("F2")]) - elif case == "count": - structured_review(mission, receipt, 1, [low()]) - counts["findings_count"] = 1 - elif case == "unstructured-prior": - review(mission, receipt, "findings") - pointer = "" - if case != "no-history": - pointer = latest_review_pointer(folder) - with pytest.raises(verification.VerificationError): - structured_review(mission, receipt, 9, data, resolved, "closed-low", **counts) - if pointer: - assert latest_review_pointer(folder) == pointer - - -def test_closed_low_requires_findings_input_and_existing_evidence(mission): - root, folder, _ = mission - _, receipt = verify(mission) - structured_review(mission, receipt, 1, [low()]) - with pytest.raises(verification.VerificationError, match="findings-input"): - verification.record_review(root, folder, "M1", receipt, root / "review-1.md", "reviewer", "unit", "closed-low") - source = root / "closing.json" - source.write_text(json.dumps({"findings": [], "resolvedIds": ["F1"]}), encoding="utf-8") - with pytest.raises(verification.VerificationError, match="리뷰 결과 파일"): - verification.record_review(root, folder, "M1", receipt, root / "absent.md", "reviewer", "unit", "closed-low", - findings_input=source) - - -def test_closed_low_cli_and_schema(mission, capsys): - root, folder, _ = mission - _, receipt = verify(mission) - structured_review(mission, receipt, 1, [low()]) - source = root / "closing.json" - source.write_text(json.dumps({"findings": [], "resolvedIds": ["F1"]}), encoding="utf-8") - args = ["review", "M1", "--receipt", str(receipt), "--evidence", str(root / "review-1.md"), "--reviewer", "lead", - "--kind", "unit", "--status", "closed-low"] - assert mission_state.main(args) == 1 - assert mission_state.main([*args, "--findings-input", str(source)]) == 0 - assert mission_state.main([*args, "--findings-input", str(source)]) == 1 - capsys.readouterr() - assert mission_state.main(["schema"]) == 0 - assert json.loads(capsys.readouterr().out)["reviewStatuses"] == ["clean", "findings", "closed-low"] - - -def test_unified_review_records_first_findings_and_closes_same_ids(mission, capsys, monkeypatch): - import io - from chef.cli.unified import main - - root, folder, _ = mission - _, receipt = verify(mission) - evidence = root / "review.md" - evidence.write_text("# Review\n\nTwo Low findings.", encoding="utf-8") - args = ["review", "M1", "--receipt", str(receipt), "--evidence", str(evidence), - "--reviewer", "reader", "--kind", "unit", "--runtime", "claude"] - assert main([*args, "--status", "findings"]) == 1 - assert "structured --findings-input" in capsys.readouterr().err - findings = [{**low(identity), "evidence": f"src/example.py:{line}"} - for identity, line in (("F1", 7), ("F2", 11))] - monkeypatch.setattr("sys.stdin", io.TextIOWrapper(io.BytesIO(json.dumps({ - "schema": 1, "findings": findings, - }).encode()))) - assert main([*args, "--status", "findings", "--findings-input", "-"]) == 0 - capsys.readouterr() - assert main(["review-open", "M1", "--runtime", "claude"]) == 0 - assert [item["id"] for item in json.loads(capsys.readouterr().out)["findings"]] == ["F1", "F2"] - assert main([*args, "--status", "closed-low", "--resolved-id", "F1"]) == 1 - assert main([*args, "--status", "closed-low", "--resolved-id", "F1", "--resolved-id", "F2"]) == 0 - review = receipt_data(Path(json.loads(latest_review_pointer(folder))["review"])) - assert review["resolvedIds"] == ["F1", "F2"] - assert receipt_data(Path(review["findingsSource"]))["resolvedIds"] == ["F1", "F2"] - - -def test_third_round_diagnostic_points_to_closed_low_or_question(mission): - _, receipt = verify(mission) - structured_review(mission, receipt, 1, [low()]) - structured_review(mission, receipt, 2, [low(origin="unresolved")]) - third = structured_review(mission, receipt, 3, [low(origin="unresolved")]) - text = " ".join(receipt_data(third)["diagnostics"]) - assert "closed-low" in text and "질문" in text - - -def test_complete_rejects_closed_low_record_with_forged_open_findings(mission): - root, folder, _ = mission - _, receipt = verify(mission) - structured_review(mission, receipt, 1, [low()]) - closed = structured_review(mission, receipt, 2, [], ["F1"], "closed-low") - data = receipt_data(closed) - data["findings"] = [low()] - closed.write_text(json.dumps(data), encoding="utf-8") - with pytest.raises(verification.VerificationError, match="미해소 지적"): - verification.validate_review(folder, "M1", receipt, closed) - - -def test_review_start_records_snapshot_copies_and_links_next_review(mission): - root, folder, _ = mission - _, receipt = verify(mission) - assert mission_state.main(start_args(mission)) == 0 - start_path = Path(receipt_data(folder / "verification/M1.review-start.latest.json")["reviewStart"]) - start = receipt_data(start_path) - assert start["snapshot"] == receipt_data(receipt)["snapshot"] and start["previousReview"] == "" - assert sorted(start["copies"]["files"]) == ["check.py", "src.py"] - copy = Path(start["copies"]["dir"]) / start["snapshot"]["src.py"] - assert copy.read_text(encoding="utf-8") == "value = 1\n" - checked = receipt_data(review(mission, receipt)) - assert checked["reviewStart"] == str(start_path) and checked["reviewStartHash"] == verification.file_hash(start_path) - assert checked["snapshot"] == start["snapshot"] and "inputChangedDuringReview" not in checked - again = receipt_data(review(mission, receipt)) - assert "reviewStart" not in again - assert (Path(again["copies"]["dir"]) / again["snapshot"]["src.py"]).is_file() - assert Path(again["copies"]["dir"]) == Path(start["copies"]["dir"]) - - -def test_review_without_start_keeps_legacy_flow_and_copies_at_review(mission): - root, folder, _ = mission - _, receipt = verify(mission) - path = review(mission, receipt) - record = receipt_data(path) - assert "reviewStart" not in record and "inputChangedDuringReview" not in record - assert record["snapshot"] == receipt_data(receipt)["snapshot"] - assert Path(record["copies"]["dir"]).parent == (folder / "verification").resolve() - verification.validate_review(folder, "M1", receipt, path) - - -def test_input_change_during_review_is_recorded_and_blocks_complete_until_rereview(mission): - root, folder, _ = mission - _, first = verify(mission) - assert mission_state.main(start_args(mission)) == 0 - (root / "src.py").write_text("value = 2\n", encoding="utf-8") - _, second = verify(mission) - assert second != first - path = review(mission, second) - record = receipt_data(path) - assert record["inputChangedDuringReview"] == ["src.py"] - assert any("src.py" in line for line in record["diagnostics"]) - assert record["snapshot"]["src.py"] != receipt_data(second)["snapshot"]["src.py"] - command = ["complete", "M1", "--receipt", str(second), "--review", str(path), "--done-evidence", "checked"] - assert mission_state.main(command) == 1 - with pytest.raises(verification.VerificationError, match="src.py"): - verification.validate_review(folder, "M1", second, path) - assert verification.review_scope(root, folder, "M1", with_unit_brief(mission, second)) == ["src.py"] - rereview = review(mission, second) - assert "inputChangedDuringReview" not in receipt_data(rereview) - assert mission_state.main(["complete", "M1", "--receipt", str(second), "--review", str(rereview), - "--done-evidence", "checked"]) == 0 - - -def test_review_start_inputs_must_match_the_verified_plan(mission): - root, folder, plan = mission - _, receipt = verify(mission) - (root / "other.json").write_text(json.dumps({**plan, "inputs": ["src.py"]}), encoding="utf-8") - (root / "review.md").write_text("Fictional independent review", encoding="utf-8") - assert mission_state.main(["review-start", "M1", "--plan", str(root / "other.json")]) == 0 - with pytest.raises(verification.VerificationError, match="inputs"): - verification.record_review(root, folder, "M1", receipt, root / "review.md", "reviewer", "unit", "clean") - - -def test_changed_review_start_record_is_rejected(mission): - root, folder, _ = mission - _, receipt = verify(mission) - path = review_with_start(mission, receipt) - start = Path(receipt_data(path)["reviewStart"]) - start.write_text(start.read_text(encoding="utf-8") + " ", encoding="utf-8") - with pytest.raises(verification.VerificationError, match="시작 기록"): - verification.validate_review(folder, "M1", receipt, path) - - -def test_review_scope_diff_covers_add_modify_delete_and_skips_binary_and_large(mission): - root, folder, plan = mission - source = root / "src" - source.mkdir() - (source / "keep.txt").write_bytes(b"one\ntwo\nthree\n") - (source / "gone.txt").write_text("bye\n", encoding="utf-8") - (source / "data.bin").write_bytes(b"\0\1\2") - (source / "huge.txt").write_text("x" * (verification.COPY_LIMIT + 1), encoding="utf-8") - plan["inputs"] = ["src"] - (root / "plan.json").write_text(json.dumps(plan), encoding="utf-8") - _, receipt = verify(mission) - assert mission_state.main(start_args(mission)) == 0 - start = receipt_data(Path(receipt_data(folder / "verification/M1.review-start.latest.json")["reviewStart"])) - assert start["copies"]["skipped"] == {"src/data.bin": "binary", "src/huge.txt": "large"} - (source / "keep.txt").write_bytes(b"one\n2\nthree\nfour") - (source / "gone.txt").unlink() - (source / "new.txt").write_text("fresh\n", encoding="utf-8") - (source / "data.bin").write_bytes(b"\0\3") - _, receipt = verify(mission) - review(mission, receipt) - changed, diff = verification.review_scope_diff(root, folder, "M1", with_unit_brief(mission, receipt)) - assert changed == ["src/data.bin", "src/gone.txt", "src/keep.txt", "src/new.txt"] - text = Path(diff).read_text(encoding="utf-8") - assert "--- a/src/gone.txt\n+++ /dev/null\n" in text and "-bye\n" in text - assert "--- /dev/null\n+++ b/src/new.txt\n" in text and "+fresh\n" in text - assert "-two\n+2\n" in text and "+four\n\\ No newline at end of file\n" in text - assert "비교 불가" in text and "src/data.bin" in text and "huge.txt" not in text - - -def test_review_scope_diff_compares_only_lines_changed_since_first_review(mission): - root, folder, plan = mission - source = root / "src" - source.mkdir() - (source / "a.txt").write_text("alpha\nbeta\n", encoding="utf-8") - plan["inputs"] = ["src"] - (root / "plan.json").write_text(json.dumps(plan), encoding="utf-8") - _, receipt = verify(mission) - review_with_start(mission, receipt) - (source / "a.txt").write_text("alpha\nbeta\ngamma\n", encoding="utf-8") - changed, diff = verification.review_scope_diff(root, folder, "M1", with_unit_brief(mission, receipt)) - assert changed == ["src/a.txt"] - text = Path(diff).read_text(encoding="utf-8") - assert "+gamma\n" in text and "-alpha" not in text and "+alpha" not in text - - -def test_review_scope_cli_prints_diff_path_and_old_records_get_list_only(mission, capsys): - root, folder, _ = mission - _, receipt = verify(mission) - path = review(mission, receipt) - (root / "src.py").write_text("value = 3\n", encoding="utf-8") - capsys.readouterr() - assert mission_state.main(["review-scope", "M1", "--plan", str(root / "plan.json")]) == 0 - lines = capsys.readouterr().out.splitlines() - assert lines[0].endswith(": 1개") and lines[1] == "src.py" and lines[2].startswith("리뷰 변경 diff: ") - assert "-value = 1" in Path(lines[2].split(": ", 1)[1]).read_text(encoding="utf-8") - legacy = receipt_data(path) - del legacy["copies"] - path.write_text(json.dumps(legacy), encoding="utf-8") - assert mission_state.main(["review-scope", "M1", "--plan", str(root / "plan.json")]) == 0 - assert capsys.readouterr().out.splitlines() == [lines[0], "src.py"] - - -def test_review_scope_diff_marks_only_unreadable_copy_and_keeps_list_and_other_diffs(mission): - root, folder, plan = mission - (root / "data.txt").write_text("d1\n", encoding="utf-8") - plan["inputs"].append("data.txt") - save_plan(mission) - _, receipt = verify(mission) - path = review(mission, receipt) - record = receipt_data(path) - (Path(record["copies"]["dir"]) / record["snapshot"]["src.py"]).write_text("tampered\n", encoding="utf-8") - (root / "src.py").write_text("value = 4\n", encoding="utf-8") - (root / "data.txt").write_text("d2\n", encoding="utf-8") - plan = with_unit_brief(mission, receipt) - changed, diff = verification.review_scope_diff(root, folder, "M1", plan) - assert changed == ["data.txt", "src.py"] - text = Path(diff).read_text(encoding="utf-8") - assert "# 비교 불가(리뷰 시점 사본이 없거나 바뀜): src.py\n" in text - assert "-d1\n+d2\n" in text and "-value = 1" not in text - (Path(record["copies"]["dir"]) / record["snapshot"]["data.txt"]).unlink() - changed, other = verification.review_scope_diff(root, folder, "M1", plan) - assert changed == ["data.txt", "src.py"] and other != diff - assert "# 비교 불가(리뷰 시점 사본이 없거나 바뀜): data.txt\n" in Path(other).read_text(encoding="utf-8") - - -def test_review_scope_diff_marks_unreadable_current_file(mission, monkeypatch): - root, folder, _ = mission - _, receipt = verify(mission) - review(mission, receipt) - (root / "src.py").write_text("value = 5\n", encoding="utf-8") - real = Path.read_bytes - - def failing(self): - if self.name == "src.py": - raise PermissionError("denied") - return real(self) - - monkeypatch.setattr(Path, "read_bytes", failing) - changed, diff = verification.review_scope_diff(root, folder, "M1", with_unit_brief(mission, receipt)) - assert changed == ["src.py"] - assert "# 비교 불가(" in Path(diff).read_text(encoding="utf-8") - - -def test_review_copy_skips_changed_and_non_text_files(mission): - root, folder, _ = mission - (root / "latin.txt").write_bytes("caf\xe9".encode("latin-1")) - files = {"latin.txt": verification.file_hash(root / "latin.txt"), "src.py": "0" * 64, "absent.txt": "missing"} - copies = verification.copy_snapshot_files(root, files, folder / "verification" / "copies") - assert copies["files"] == [] and copies["skipped"] == {"latin.txt": "binary", "src.py": "changed"} - - -def findings_after_input_change(mission): - root, folder, _ = mission - _, first = verify(mission) - assert mission_state.main(start_args(mission)) == 0 - (root / "src.py").write_text("value = 2\n", encoding="utf-8") - _, second = verify(mission) - findings = structured_review(mission, second, 1, [low()]) - assert receipt_data(findings)["inputChangedDuringReview"] == ["src.py"] - return second - - -def test_closed_low_is_rejected_when_the_previous_review_saw_inputs_change(mission): - root, folder, _ = mission - second = findings_after_input_change(mission) - pointer = latest_review_pointer(folder) - with pytest.raises(verification.VerificationError, match="독립 재리뷰"): - structured_review(mission, second, 2, [], ["F1"], "closed-low") - assert latest_review_pointer(folder) == pointer - clean = structured_review(mission, second, 3, [], ["F1"], "clean") - verification.validate_review(folder, "M1", second, clean) - - -def test_complete_rejects_closed_low_after_a_review_that_saw_inputs_change(mission, monkeypatch): - root, folder, _ = mission - second = findings_after_input_change(mission) - monkeypatch.setattr(verification_reviews, "require_closed_low", lambda *args: None) - forged = structured_review(mission, second, 2, [], ["F1"], "closed-low") - with pytest.raises(verification.VerificationError, match="독립 재리뷰"): - verification.validate_review(folder, "M1", second, forged) - assert mission_state.main(["complete", "M1", "--receipt", str(second), "--review", str(forged), - "--done-evidence", "checked"]) == 1 - - -def test_closed_low_is_rejected_for_a_finding_first_recorded_as_regression(mission): - root, folder, _ = mission - _, receipt = verify(mission) - structured_review(mission, receipt, 1, [low()]) - structured_review(mission, receipt, 2, [], ["F1"], "clean") - structured_review(mission, receipt, 3, [low("F3", origin="regression", relatedId="F1")]) - structured_review(mission, receipt, 4, [low("F3", origin="unresolved")]) - pointer = latest_review_pointer(folder) - with pytest.raises(verification.VerificationError, match="회귀가 아닌"): - structured_review(mission, receipt, 5, [], ["F3"], "closed-low") - assert latest_review_pointer(folder) == pointer - - -@pytest.mark.parametrize("later", [{"severity": "low"}, {"severity": "medium"}, {}]) -def test_same_finding_id_cannot_lower_or_drop_severity_between_rounds(mission, later): - root, folder, _ = mission - _, receipt = verify(mission) - structured_review(mission, receipt, 1, [finding(severity="high")]) - pointer = latest_review_pointer(folder) - with pytest.raises(verification.VerificationError, match="severity"): - structured_review(mission, receipt, 2, [finding(origin="unresolved", **later)]) - assert latest_review_pointer(folder) == pointer - kept = structured_review(mission, receipt, 3, [finding(origin="unresolved", severity="high")]) - raised = structured_review(mission, receipt, 4, [finding(origin="unresolved", severity="critical")]) - assert receipt_data(kept)["findings"][0]["severity"] == "high" - assert receipt_data(raised)["findings"][0]["severity"] == "critical" - - -def test_round_three_diagnostic_is_not_attached_to_passing_reviews(mission): - _, receipt = verify(mission) - structured_review(mission, receipt, 1, [low()]) - structured_review(mission, receipt, 2, [low(origin="unresolved")]) - closed = structured_review(mission, receipt, 3, [], ["F1"], "closed-low") - assert receipt_data(closed)["round"] == 3 and receipt_data(closed)["diagnostics"] == [] - again = structured_review(mission, receipt, 4, [low("F4", origin="new")]) - assert any("closed-low" in line for line in receipt_data(again)["diagnostics"]) - - -@pytest.mark.parametrize("failure", ["write", "mkdir"]) -def test_unwritable_review_copies_are_skipped_instead_of_failing_the_review(mission, monkeypatch, failure): - root, folder, _ = mission - _, receipt = verify(mission) - real_write, real_mkdir = Path.write_bytes, Path.mkdir - - def guarded_write(self, data): - if failure == "write" and ".copies" in str(self): - raise OSError(36, "File name too long") - return real_write(self, data) - - def guarded_mkdir(self, *args, **kwargs): - if failure == "mkdir" and self.name.endswith(".copies"): - raise OSError(36, "File name too long") - return real_mkdir(self, *args, **kwargs) - - monkeypatch.setattr(Path, "write_bytes", guarded_write) - monkeypatch.setattr(Path, "mkdir", guarded_mkdir) - assert mission_state.main(start_args(mission)) == 0 - start = receipt_data(Path(receipt_data(folder / "verification/M1.review-start.latest.json")["reviewStart"])) - expected = {"check.py": "unwritable", "src.py": "unwritable"} - assert start["copies"]["files"] == [] and start["copies"]["skipped"] == expected - checked = receipt_data(review(mission, receipt)) - assert checked["copies"]["files"] == [] and checked["copies"]["skipped"] == expected - store = folder / "verification" / "M1.copies" - assert not store.exists() or list(store.iterdir()) == [] - - -def test_review_copies_are_deduplicated_by_content_across_rounds_and_keys(mission): - root, folder, _ = mission - _, receipt = verify(mission) - assert mission_state.main(start_args(mission)) == 0 - review(mission, receipt) - review(mission, receipt) - store = folder / "verification" / "M1.copies" - assert sorted(path.name for path in store.iterdir()) == sorted(set(receipt_data(receipt)["snapshot"].values())) - (root / "twin-a.txt").write_text("same\n", encoding="utf-8") - (root / "twin-b.txt").write_text("same\n", encoding="utf-8") - files = {name: verification.file_hash(root / name) for name in ("twin-a.txt", "twin-b.txt")} - copies = verification.copy_snapshot_files(root, files, folder / "verification" / "twins") - assert copies["files"] == ["twin-a.txt", "twin-b.txt"] and len(list(Path(copies["dir"]).iterdir())) == 1 - - -def test_review_copy_total_is_capped_and_the_rest_is_marked_budget(mission): - root, folder, _ = mission - assert verification.COPY_BUDGET == 64 * 1024 * 1024 - for name in ("one.txt", "two.txt"): - (root / name).write_text("123456", encoding="utf-8") - (root / "two.txt").write_text("654321", encoding="utf-8") - files = {name: verification.file_hash(root / name) for name in ("one.txt", "two.txt")} - copies = verification.copy_snapshot_files(root, files, folder / "verification" / "capped", budget=10) - assert copies["files"] == ["one.txt"] and copies["skipped"] == {"two.txt": "budget"} - - -def inputs_plan(mission): - root, _, plan = mission - (root / "a.txt").write_text("a1\n", encoding="utf-8") - (root / "b.txt").write_text("b1\n", encoding="utf-8") - (root / "step.py").write_text( - "import sys\n" - "from pathlib import Path\n" - "name = sys.argv[1]\n" - "counter = Path('runs_' + name)\n" - "counter.write_text(counter.read_text() + 'x' if counter.exists() else 'x')\n" - "Path('out_' + name).mkdir(exist_ok=True)\n" - "Path('out_' + name, 'result.json').write_text('{\"status\":\"passed\"}')\n", encoding="utf-8") - plan.update(inputs=["a.txt", "b.txt"], commands=[ - {"id": name, "argv": [sys.executable, "step.py", name], "reusable": True, "outputs": [f"out_{name}"], - "inputs": [f"{name}.txt"]} for name in ("a", "b") - ], results=[{"path": f"out_{name}/result.json", "command": name, "equals": {"status": "passed"}} - for name in ("a", "b")]) - save_plan(mission) - return plan - - -def step_statuses(path): - return [step["status"] for step in receipt_data(path)["steps"]] - - -def runs(root, name): - return (root / f"runs_{name}").read_text(encoding="utf-8") - - -def test_declared_step_inputs_reuse_untouched_steps_and_rerun_later_steps_after_an_earlier_rerun(mission): - root, _, _ = mission - inputs_plan(mission) - _, first = verify(mission) - assert step_statuses(first) == ["passed", "passed"] - (root / "b.txt").write_text("b2\n", encoding="utf-8") - _, second = verify(mission) - assert step_statuses(second) == ["reused", "passed"] - assert runs(root, "a") == "x" and runs(root, "b") == "xx" - (root / "a.txt").write_text("a2\n", encoding="utf-8") - _, third = verify(mission) - assert step_statuses(third) == ["passed", "passed"] - assert runs(root, "a") == "xx" and runs(root, "b") == "xxx" - - -@pytest.mark.parametrize("declared", [True, False]) -def test_step_without_inputs_keeps_the_whole_snapshot_in_its_key(mission, declared): - root, _, _ = mission - plan = inputs_plan(mission) - plan["commands"].reverse() - if not declared: - del plan["commands"][0]["inputs"] - save_plan(mission) - verify(mission) - (root / "a.txt").write_text("a2\n", encoding="utf-8") - _, second = verify(mission) - expected = ["reused", "passed"] - if not declared: - expected = ["passed", "passed"] - assert step_statuses(second) == expected - - -def test_step_inputs_accept_folder_and_glob_declarations(mission): - root, _, _ = mission - plan = inputs_plan(mission) - (root / "data/deep").mkdir(parents=True) - (root / "data/deep/x.txt").write_text("x\n", encoding="utf-8") - (root / "data/y.md").write_text("y\n", encoding="utf-8") - plan["inputs"] = ["a.txt", "b.txt", "data"] - for inputs in (["data"], ["data/**/*.txt", "data/*.md"], ["a.txt", "**/x.txt"]): - plan["commands"][0]["inputs"] = inputs - verification.validate_plan(root, plan, ["pytest-pass"]) - before = verification.snapshot(root, plan["inputs"]) - plan["commands"][0]["inputs"] = ["data/**/*.txt"] - assert sorted(verification.step_inputs(root, plan["commands"][0], before)) == ["data/deep/x.txt"] - plan["commands"][0]["inputs"] = ["data"] - assert sorted(verification.step_inputs(root, plan["commands"][0], before)) == ["data/deep/x.txt", "data/y.md"] - del plan["commands"][0]["inputs"] - assert verification.step_inputs(root, plan["commands"][0], before) == before - - -@pytest.mark.parametrize("declared", [ - [], "a.txt", [""], [1], ["other.txt"], ["../a.txt"], ["/abs/a.txt"], ["C:/a.txt"], ["."], ["a.txt\n"], -]) -def test_malformed_or_outside_command_inputs_are_rejected_on_every_load(mission, declared): - root, _, _ = mission - plan = inputs_plan(mission) - (root / "other.txt").write_text("outside\n", encoding="utf-8") - plan["commands"][0]["inputs"] = declared - with pytest.raises(verification.VerificationError): - verification.validate_plan(root, plan, ["pytest-pass"]) - save_plan(mission) - code, path = verify(mission) - assert code == 1 and receipt_data(path)["failure"]["category"] == "plan_invalid" - assert mission_state.main(start_args(mission)) == 1 - assert mission_state.main(["review-scope", "M1", "--plan", str(root / "plan.json")]) == 1 - - -@pytest.mark.parametrize("declared", [["missing/**"], ["*.md"], ["a.txt", "nested/*.txt"]]) -def test_command_inputs_matching_no_plan_input_file_fail_only_the_preflight(mission, declared): - root, _, _ = mission - plan = inputs_plan(mission) - plan["commands"][0]["inputs"] = declared - save_plan(mission) - assert verification.validate_plan(root, plan, ["pytest-pass"]) is plan - with pytest.raises(verification.VerificationError, match="일치하지 않음"): - verification.validate_plan(root, plan, ["pytest-pass"], require_matches=True) - checked = verification.preflight(root, plan, allow_command, require_matches=True) - assert checked["status"] == "fail" and checked["failure"]["category"] == "plan_invalid" - assert verification.preflight(root, plan, allow_command)["status"] == "pass" - assert mission_state.main(["preflight", "M1", "--plan", str(root / "plan.json")]) == 1 - assert verify(mission)[0] == 0 - - -def declared_data_plan(mission, declared): - root, _, plan = mission - inputs_plan(mission) - (root / "data/deep").mkdir(parents=True) - (root / "data/deep/x.txt").write_text("x\n", encoding="utf-8") - plan["inputs"] = ["a.txt", "b.txt", "data"] - plan["commands"][0]["inputs"] = declared - save_plan(mission) - - -def test_deleting_every_file_a_step_declares_keeps_the_same_plan_verifiable_and_the_scope_diff(mission, capsys): - root, _, _ = mission - declared_data_plan(mission, ["data/**/*.txt", "data/*.md"]) - _, first = verify(mission) - assert step_statuses(first) == ["passed", "passed"] - review_with_start(mission, first) - (root / "data/deep/x.txt").unlink() - code, second = verify(mission) - assert code == 0 and step_statuses(second) == ["passed", "passed"] - assert runs(root, "a") == "xx" - plan_path = str(root / "plan.json") - capsys.readouterr() - assert mission_state.main(["review-scope", "M1", "--plan", plan_path]) == 0 - lines = capsys.readouterr().out.splitlines() - assert lines[0].endswith(": 1개") and lines[1] == "data/deep/x.txt" and lines[2].startswith("리뷰 변경 diff: ") - assert "-x\n" in Path(lines[2].split(": ", 1)[1]).read_text(encoding="utf-8") - assert mission_state.main(["review-start", "M1", "--plan", plan_path]) == 0 - assert mission_state.main(["preflight", "M1", "--plan", plan_path]) == 1 - - -@pytest.mark.parametrize("declared", [["data"], ["data/**/*.txt"]]) -def test_adding_or_deleting_files_under_a_declared_folder_or_glob_reruns_the_step(mission, declared): - root, _, _ = mission - declared_data_plan(mission, declared) - verify(mission) - (root / "data/deep/new.txt").write_text("n\n", encoding="utf-8") - assert step_statuses(verify(mission)[1]) == ["passed", "passed"] - assert runs(root, "a") == "xx" - (root / "data/deep/new.txt").unlink() - assert step_statuses(verify(mission)[1]) == ["passed", "passed"] - assert runs(root, "a") == "xxx" - - -def test_adding_a_file_outside_the_declared_glob_reuses_the_step(mission): - root, _, _ = mission - declared_data_plan(mission, ["data/**/*.txt"]) - verify(mission) - (root / "data/y.md").write_text("y\n", encoding="utf-8") - assert step_statuses(verify(mission)[1]) == ["reused", "reused"] - assert runs(root, "a") == "x" - - -def test_glob_matching_ignores_case_only_where_path_inputs_do(monkeypatch): - monkeypatch.setattr(verification_plan, "glob_ignores_case", lambda: True) - assert verification.input_matcher("glob", "src/**/*.cs")("src/A/Foo.CS") is True - monkeypatch.setattr(verification_plan, "glob_ignores_case", lambda: False) - assert verification.input_matcher("glob", "src/**/*.cs")("src/A/Foo.CS") is False - assert verification.input_matcher("glob", "src/**/*.cs")("src/A/Foo.cs") is True - - -def test_review_scope_keeps_the_list_when_the_diff_cannot_be_written(mission, capsys, monkeypatch): - root, _, _ = mission - _, receipt = verify(mission) - review(mission, receipt) - (root / "src.py").write_text("value = 3\n", encoding="utf-8") - real = Path.write_bytes - - def failing(self, data): - if self.suffix == ".diff": - raise PermissionError("denied") - return real(self, data) - - monkeypatch.setattr(Path, "write_bytes", failing) - capsys.readouterr() - assert mission_state.main(["review-scope", "M1", "--plan", str(root / "plan.json")]) == 0 - lines = capsys.readouterr().out.splitlines() - assert lines[1:] == ["src.py", "diff 쓰기 실패: denied"] and lines[0].endswith(": 1개") - - -@pytest.mark.parametrize("pattern,key,expected", [ - ("src/**/*.py", "src/a.py", True), ("src/**/*.py", "src/x/y/a.py", True), ("src/**/*.py", "src/a.txt", False), - ("src/*.py", "src/x/a.py", False), ("data/?.txt", "data/a.txt", True), ("data/?.txt", "data/ab.txt", False), - ("data/[ab].txt", "data/b.txt", True), ("data/[!ab].txt", "data/b.txt", False), - ("data/[!ab].txt", "data/c.txt", True), ("**", "any/thing.txt", True), ("src/**", "src/a/b", True), - ("a.*", "a.b", True), ("a.*", "aXb", False), ("a[", "a[", True), -]) -def test_input_glob_matching_follows_path_segments(pattern, key, expected): - assert verification.input_matcher("glob", pattern)(key) is expected - - -def test_fix_round_reuses_untouched_steps_keeps_scope_and_completes_through_closed_low(mission, capsys): - root, folder, _ = mission - inputs_plan(mission) - _, first = verify(mission) - assert mission_state.main(start_args(mission)) == 0 - findings = structured_review(mission, first, 1, [low()]) - assert "inputChangedDuringReview" not in receipt_data(findings) - (root / "b.txt").write_text("b2\n", encoding="utf-8") - code, second = verify(mission) - assert code == 0 and step_statuses(second) == ["reused", "passed"] - assert receipt_data(second)["executionCounts"] == {"executed": 1, "reused": 1} - capsys.readouterr() - assert mission_state.main(["review-scope", "M1", "--plan", str(root / "plan.json")]) == 0 - lines = capsys.readouterr().out.splitlines() - assert lines[0].endswith(": 1개") and lines[1] == "b.txt" and lines[2].startswith("리뷰 변경 diff: ") - diff = Path(lines[2].split(": ", 1)[1]).read_text(encoding="utf-8") - assert "-b1\n" in diff and "+b2\n" in diff - closed = structured_review(mission, second, 2, [], ["F1"], "closed-low") - assert receipt_data(closed)["status"] == "closed-low" - assert mission_state.main(["complete", "M1", "--receipt", str(second), "--review", str(closed), - "--done-evidence", "checked fix diff"]) == 0 - assert (folder / "units.tsv").read_text(encoding="utf-8").rstrip().endswith("\tdone") diff --git a/tests/integration/mission/test_verification_reuse.py b/tests/integration/mission/test_verification_reuse.py new file mode 100644 index 0000000..e7f3aab --- /dev/null +++ b/tests/integration/mission/test_verification_reuse.py @@ -0,0 +1,32 @@ +"""Reuse stays valid until an input or the command itself changes.""" +import json +import sys + +from tests.support import open_mission, verify_mission + + +def test_input_change_invalidates_reuse(tmp_path, monkeypatch): + root, folder, _ = open_mission(tmp_path, monkeypatch) + code, first = verify_mission(root, folder) + assert code == 0 and (root / "runs").read_text(encoding="utf-8") == "x" + assert verify_mission(root, folder) == (0, first) + assert (root / "runs").read_text(encoding="utf-8") == "x" + (root / "src.py").write_text("value = 2\n", encoding="utf-8") + second = verify_mission(root, folder)[1] + assert second != first + assert (root / "runs").read_text(encoding="utf-8") == "xx" + + +def test_command_change_invalidates_reuse(tmp_path, monkeypatch): + root, folder, plan = open_mission(tmp_path, monkeypatch) + code, first = verify_mission(root, folder) + assert code == 0 + other = root / "other.py" + other.write_text("from pathlib import Path\nPath('runs').write_text('y')\n", encoding="utf-8") + plan["commands"][0]["argv"] = [sys.executable, str(other)] + plan["commands"][0]["outputs"] = [] + plan["inputs"] = ["src.py", "other.py"] + (root / "plan.json").write_text(json.dumps(plan), encoding="utf-8") + changed = verify_mission(root, folder) + assert changed[0] == 0 and changed[1] != first + assert (root / "runs").read_text(encoding="utf-8") == "y" diff --git a/tests/integration/slots/test_dashboard.py b/tests/integration/slots/test_dashboard.py index 3a56ac9..ffefff6 100644 --- a/tests/integration/slots/test_dashboard.py +++ b/tests/integration/slots/test_dashboard.py @@ -1,165 +1,24 @@ +"""Read-only dashboard: path escape, structured pending, and answer rejection.""" import json import os -import re -import shutil -import subprocess -import sys import threading import urllib.error import urllib.request -from html.parser import HTMLParser -from pathlib import Path -from urllib.parse import parse_qs, quote, urljoin, urlsplit +from urllib.parse import quote import pytest -from chef.dashboard import data as dashboard_data from chef.dashboard import server as dashboard -from chef.guards import mission as mission_guard -from chef.infrastructure import configuration -from chef.mission import state as mission_state -from chef.questions import records as question_records from chef.slots import commands as slots -from tests.paths import PLUGIN_ROOT +from tests.integration.mission.test_question_record import publish -UNITS_HEADER = "\t".join(mission_state.UNIT_HEADER) -UNIT_ROW = "M1\t목표\ta.cs\t테스트\tpytest\t60\tsubmit\t-\t-\t123456\t2026-10-19T09:00:00+09:00\tdoing" - -class DetailElement: - def __init__(self, tag, attrs=()): - self.tag = tag - self.attrs = dict(attrs) - self.children = [] - - def elements(self, tag="", **attrs): - found = [] - for child in self.children: - if isinstance(child, DetailElement): - if (not tag or child.tag == tag) and all(child.attrs.get(key, "") == value for key, value in attrs.items()): - found.append(child) - found.extend(child.elements(tag, **attrs)) - return found - - def text(self, visible=False): - if visible and self.tag in ("script", "style"): - return "" - children = self.children - if visible and self.tag == "details" and "open" not in self.attrs: - children = [child for child in children if isinstance(child, DetailElement) and child.tag == "summary"] - pieces = [] - for child in children: - if isinstance(child, DetailElement): - pieces.append(child.text(visible)) - else: - pieces.append(child) - return "".join(pieces) - - -class DetailParser(HTMLParser): - def __init__(self, source): - super().__init__(convert_charrefs=True) - self.root = DetailElement("document") - self.stack = [self.root] - self.feed(source) - - def handle_starttag(self, tag, attrs): - element = DetailElement(tag, attrs) - self.stack[-1].children.append(element) - if tag not in ("area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"): - self.stack.append(element) - - def handle_endtag(self, tag): - for index in range(len(self.stack) - 1, 0, -1): - if self.stack[index].tag == tag: - del self.stack[index:] - break - - def handle_data(self, data): - self.stack[-1].children.append(data) - - -def detail_dom(source): - return DetailParser(source).root - - -def detail_fields(element): - return {term.text(): value.text() for term, value in zip(element.elements("dt"), element.elements("dd"))} - - -def write_detail_records(folder, records): - headers = {name: header for _, name, header in dashboard.TABLES} - for name, rows in records.items(): - mission_state.write_table(str(folder / name), headers[name], rows) - - -def detail_records(): - return { - "units.tsv": [{ - "id": "M7", "goal": '계약 & 원문', - "files": "src/한글 파일.cs;tests/범위.cs", "done": "완료 조건 고유 원문", - "verify": "pytest 계획 고유 원문", "timebox": "45", "forbid": "승인 전 submit 금지", - "human": "확인 B2 승인 필요", "after": "M6", "unit": "CL-427777", - "started": "2026-10-23T09:01:02+09:00", "status": "doing", - }], - "ledger.tsv": [{ - "at": "2026-10-23T10:01:02+09:00", "unit": "M7-review", "status": "pass", - "grade": "needs-human", "evidence": '검증 결과 & 원문', - "files": "snapshot/src.cs;연관 파일.cs", - }], - "decisions.tsv": [{ - "at": "2026-10-23T10:02:03+09:00", "id": "D8", "what": "결정 주제 원문", - "chosen": '선택 "옵션 A"', "why": "이유 & 근거", "affects": "M7, M8 영향", - }], - "sessions.tsv": [{ - "at": "2026-10-23T10:03:04+09:00", "action": "resume", "session": "recorded-session-7", - "transcript": "private/session-7.jsonl", - }], - } - - -def write_question(folder, name, title, items, approval="none", answer="", intro="", body=""): - previous = {} - if question_records.source_path(folder, name).exists(): - previous = question_records.read_document(folder, name) - revision = previous.get("revision", 0) + 1 - record = { - "schema": 1, "id": name[:-3], "revision": revision, "title": title, "intro": intro, "body": body, - "items": [{"id": str(number), "title": item_title, "body": "", "status": "pending", "answer": ""} - for number, (item_title, status) in enumerate(items, 1)], - "approval": previous.get("approval", {"status": "none", "reason": ""}), - "answers": previous.get("answers", []), - } - if "legacy_markdown" in previous: - record["legacy_markdown"] = previous["legacy_markdown"] - elif not previous and (folder / name).exists(): - record["legacy_markdown"] = (folder / name).read_bytes().decode("utf-8") - expected_revision = "" - if previous: - expected_revision = previous["revision"] - if not previous and record['id'].startswith('confirm-A'): - # Existing schema 1 documents remain readable in dashboards after upgrade. - source = question_records.source_path(folder, name) - source.parent.mkdir(exist_ok=True) - source.write_text(json.dumps(record), encoding='utf-8') - question_records.publish_document(folder, record, expected_revision) - reason = "" - if approval == "pending": - reason = "최종 승인 필요" - raw_answer = answer - if not raw_answer: - raw_answer = "Record the fictional question states." - updates = [] - for item, (_, status) in zip(record["items"], items): - value = "" - if status != "pending": - value = answer - updates.append({"id": item["id"], "status": status, "answer": value}) - return question_records.answer_document(folder, name, { - "schema": 1, "id": f"answer-{revision}", "revision": revision, - "at": "2026-10-26T10:00:00+09:00", "text": raw_answer, "updates": updates, - "approval": {"status": approval, "reason": reason}, - }) +def directory_alias(link, target): + if os.name == "nt": + import _winapi + _winapi.CreateJunction(str(target), str(link)) + else: + link.symlink_to(target, target_is_directory=True) class World: @@ -168,15 +27,11 @@ def __init__(self, tmp_path): self.slot_root = tmp_path / "slot_root" adapter_dir = self.main / ".claude" / "orchestrator" adapter_dir.mkdir(parents=True) - adapter = { - "schema": 1, - "project": "FAKE", - "paths": {"vcsRoot": ".", "stateDir": "_My/missions"}, - "slots": {"enabled": True, "names": ["slot1", "slot2"], "client": "fake_{name}", "prepare": []}, - } + adapter = {"schema": 1, "project": "FAKE", "paths": {"vcsRoot": ".", "stateDir": "_My/missions"}, + "slots": {"enabled": True, "names": ["slot1", "slot2"], "client": "fake_{name}", "prepare": []}} (adapter_dir / "adapter.json").write_text(json.dumps(adapter), encoding="utf-8") - local = {"slots": {"root": str(self.slot_root).replace("\\", "/")}} - (adapter_dir / "local.json").write_text(json.dumps(local), encoding="utf-8") + (adapter_dir / "local.json").write_text( + json.dumps({"slots": {"root": str(self.slot_root).replace("\\", "/")}}), encoding="utf-8") self.outside = tmp_path / "outside" self.outside.mkdir() (self.outside / "secret.md").write_text("비밀", encoding="utf-8") @@ -186,30 +41,18 @@ def config(self): located = slots.locate(str(self.main)) return slots.Config(located, slots.read_adapter(located.adapter_path)) - def mission(self, slot, mission_id, state="진행", files=None, shared=()): + def mission(self, slot, mission_id, files=None): base = self.main if slot == "main" else self.slot_root / slot folder = base / "_My" / "missions" / mission_id folder.mkdir(parents=True) (folder / "mission.md").write_text( - f"# 미션 {mission_id}\n\n상태: {state}\n현재 단계: impl\n확인 A: 승인\n확인 A1: 대기\n\n## 목표\n\n{mission_id} 목표 첫 줄\n", encoding="utf-8" - ) - (folder / "report.md").write_text("# 보고\n\n## 지금\n\n보고에만 있는 과거 진행 요약\n\n## 마일스톤\n", encoding="utf-8") - (folder / "units.tsv").write_text(f"{UNITS_HEADER}\n{UNIT_ROW}\n", encoding="utf-8") + f"# 미션 {mission_id}\n\n상태: 진행\n현재 단계: impl\n확인 A: 승인\n\n## 목표\n\n목표\n", encoding="utf-8") for name, text in (files or {}).items(): - (folder / name).parent.mkdir(parents=True, exist_ok=True) - (folder / name).write_text(text, encoding="utf-8") - if shared: - self.share(folder, *shared) + path = folder / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") return folder - def share(self, folder, *names): - rows = {row["path"]: row for row in mission_state.shared_document_rows(str(folder))} - for name in names: - canonical, target = mission_state.canonical_document_path(str(folder), name) - rows[canonical] = {"path": canonical, "sha256": dashboard.digest(Path(target).read_bytes()), "at": "2026-10-26T10:00:00+09:00"} - mission_state.write_table(str(folder / mission_state.SHARED_DOCUMENTS_FILE), mission_state.SHARED_DOCUMENTS_HEADER, [rows[name] for name in sorted(rows)]) - return names - def get(self, target): status, _, body = dashboard.route(self.config, target) return status, body.decode("utf-8", errors="replace") @@ -222,1859 +65,47 @@ def world(tmp_path, monkeypatch): return World(tmp_path) -def test_running_mission_without_active_file_is_collected(world): - world.mission("slot2", "20261015-pet-gacha-server", shared=["report.md"]) - (world.slot_root / "slot1" / "_My" / "missions").mkdir(parents=True) - found = {location.label: location for location in dashboard.collect(world.config)} - mission = found["slot2"].missions[0] - assert (mission.id, mission.state, mission.active) == ("20261015-pet-gacha-server", "진행", False) - status, text = world.get("/") - assert status == 200 - assert "세션 없음" in text and "20261015-pet-gacha-server" in text - assert "

    지금

    " in text and "보고에만 있는 과거 진행 요약" not in text - - -def test_only_running_missions_list_unanswered_questions_on_top(world): - folder = world.mission("slot1", "run-1") - write_question(folder, "ask-1.md", "질문", [("남은 결정", "pending")]) - write_question(folder, "confirm-A.md", "확인", [("완료 결정", "answered")], answer="승인") - world.mission("slot1", "stopped-1", state="중단", files={"ask-9.md": "# 질문\n\n## 답\n"}, shared=["ask-9.md"]) - status, text = world.get("/") - top = text.split('

    02')[0] - assert status == 200 - assert "ask-1.md" in top and "run-1" in top - assert "ask-9.md" not in top and "confirm-A.md" not in top - assert "stopped-1" in text - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_answer_waiting_slot_is_first_on_overview_and_keeps_other_slot_order(world, runtime): - world.mission("main", "main-running") - world.mission("slot1", "slot1-running") - world.mission("slot1", "slot1-stopped", state="중단", files={"ask-9.md": "# 닫힌 질문\n\n답변 대기\n\n## 결정할 것\n\n### 1. 중단 범위\n"}, shared=["ask-9.md"]) - world.mission("slot2", "primary-running") - other = world.mission("slot2", "other-running", files={"ask-2.md": "# 업데이트 전략\n\n답변 대기\n\n## 결정할 것\n\n### 1. 문서 범위\n"}, shared=["ask-2.md"]) - write_question(other, "ask-2.md", "업데이트 전략", [("문서 범위", "pending")]) - (other.parent / "ACTIVE").write_text(json.dumps({"id": "primary-running", "session": "s1"}), encoding="utf-8") - config = runtime_config(world, runtime) - overview = dashboard.route(config, "/")[2].decode("utf-8") - card_order = re.findall(r'
    02')[0] - - def test_view_refuses_paths_outside_allowed_roots(world): inside = world.mission("slot1", "run-1") assert world.get("/view?path=" + quote(str(inside / "mission.md"), safe=""))[0] == 200 assert world.get("/view?path=" + quote(str(world.outside / "secret.md"), safe=""))[0] == 403 - sneaky = str(inside / ".." / ".." / ".." / ".." / ".." / "outside" / "secret.md") - assert world.get("/view?path=" + quote(sneaky, safe=""))[0] == 403 assert world.get("/view?path=" + quote("relative/mission.md", safe=""))[0] == 403 - assert world.get("/view?path=")[0] == 403 - assert world.get("/view?path=" + quote(str(world.slot_root), safe=""))[0] == 403 - - -def test_view_renders_markdown_text_and_images(world): - folder = world.mission("slot1", "run-1") - link = "file:///" + str(folder / "report.md").replace("\\", "/") - (folder / "ask-1.md").write_text(f"# 질문\n\n[보고]({link}#L3)\n", encoding="utf-8") - (folder / "shot.png").write_bytes(b"\x89PNG\r\n") - world.share(folder, "ask-1.md", "report.md", "shot.png") - status, text = world.get("/view?path=" + quote(str(folder / "ask-1.md"), safe="")) - assert status == 200 and "file:///" not in text and "/view?path=" in text and "#L3" in text - status, text = world.get("/view?path=" + quote(str(folder / "units.tsv"), safe="")) - assert status == 200 and 'id="L2"' in text - status, content_type, body = dashboard.route(world.config, "/view?path=" + quote(str(folder / "shot.png"), safe="")) - assert (status, content_type, body) == (200, "image/png", b"\x89PNG\r\n") - - -def test_view_updates_verified_tabular_questions_without_changing_raw_files(world): - folder = world.mission("slot1", "choice-review") - name = "ask-1.md" - write_question(folder, name, "Palette", [("Choose a color", "pending")]) - record = question_records.read_document(folder, name) - record["revision"] += 1 - record["items"][0]["options"] = [{"id": "blue", "label": "Blue", "impact": "Higher contrast."}] - question_records.publish_document(folder, record, 1) - old = question_records.render_document(record, tabular_choices=True).encode("utf-8") - path = folder / name - path.write_bytes(old) - view = dashboard.view_url(path) - source = detail_dom(world.get(view)[1]).elements("script", id="source")[0] - choice = "- Blue \n 영향 · Higher contrast." - assert choice in json.loads(source.text()) - assert b"| id |" in dashboard.route(world.config, dashboard.raw_url(path))[2] - assert path.read_bytes() == old - path.write_bytes(old.replace(b"Higher contrast.", b"Edited outside publication.")) - source = detail_dom(world.get(view)[1]).elements("script", id="source")[0] - assert "| Blue |" in json.loads(source.text()) - assert choice not in json.loads(source.text()) def test_broken_files_do_not_break_the_overview(world): folder = world.mission("slot1", "broken-1") (folder / "units.tsv").write_text("엉터리 헤더\nM1\t하나\n", encoding="utf-8") - (folder / "sessions.tsv").write_bytes(b"\xff\xfe\x00broken") - (world.slot_root / "slot2" / "_My" / "missions" / "no-mission-md").mkdir(parents=True) - bad = world.mission("slot2", "bad-md") - (bad / "mission.md").write_bytes(b"\xff\xfe\x00\x00") status, text = world.get("/") - assert status == 200 - assert "읽기 실패: units.tsv" in text and "broken-1" in text and "bad-md" in text and "no-mission-md" not in text - status, text = world.get("/mission?slot=slot1&id=broken-1") - assert status == 200 and "읽기 실패" in text - - -@pytest.mark.parametrize("suffix", [".html", ".png", ".css"]) -def test_markdown_file_urls_use_raw_routes_for_browser_assets(world, suffix): - folder = world.mission("slot1", "run-1") - asset = folder / ("한글 image" + suffix) - asset.write_text("asset", encoding="utf-8") - reference = "file:///" + quote(str(asset).replace("\\", "/"), safe="/:") - document = folder / "ask-1.md" - document.write_text(f"[파일]({reference}#preview)\n\n![그림]({reference})\n", encoding="utf-8") - world.share(folder, "ask-1.md", asset.name) - status, text = world.get(dashboard.view_url(document)) - assert status == 200 - embedded = text.split('id="source"', 1)[1].split('>', 1)[1].split('', 1)[0] - assert json.loads(embedded).splitlines() == f"[파일]({dashboard.raw_url(asset)}#preview)\n\n![그림]({dashboard.raw_url(asset)})\n".splitlines() - assert world.get(dashboard.raw_url(asset))[0] == 200 - - -def test_markdown_links_use_the_document_location_without_rewriting_source(world): - folder = world.mission("slot1", "한글-1") - (folder / "details").mkdir() - (folder / "details" / "ask-1.md").write_text("# 상세\n\n[사람용](../ask-1.md)\n", encoding="utf-8") - source = "# 질문\n\n[상세](details/ask-1.md#근거)\n\n```text\n[예제](missing.md)\n```\n" - (folder / "ask-1.md").write_text(source, encoding="utf-8") - world.share(folder, "ask-1.md", "details/ask-1.md") - status, text = world.get(dashboard.view_url(folder / "ask-1.md")) - assert status == 200 - assert f'data-url="{dashboard.raw_url(folder / "ask-1.md")}"' in text - embedded = text.split('id="source"', 1)[1].split('>', 1)[1].split('', 1)[0] - assert json.loads(embedded) == (folder / "ask-1.md").read_bytes().decode("utf-8") - assert world.get(dashboard.view_url(folder / "details" / "ask-1.md", "근거"))[0] == 200 - assert world.get(dashboard.view_url(world.outside / "secret.md"))[0] == 403 - - -@pytest.mark.skipif(not shutil.which("node"), reason="Node.js is required to execute the Markdown link renderer") -@pytest.mark.parametrize("slot", ["main", "slot1", "slot2"]) -def test_rendered_markdown_links_open_files_in_the_source_workspace(world, slot): - folder = world.mission(slot, "한글-1") - root = world.main if slot == "main" else world.slot_root / slot - poc = add_poc(folder, root) - image = root / "Wiki" / "한글 image#1.png" - image.write_bytes(b"image") - details = folder / "details" - details.mkdir() - document = details / "confirm.md" - document.write_text("# 확인\n", encoding="utf-8") - (folder / "50%.md").write_text("# 백분율\n", encoding="utf-8") - world.share(folder, "details/confirm.md", "50%.md", "report.md") - status, text = world.get(dashboard.view_url(document)) - assert status == 200 - assert f'data-root="{dashboard.raw_url(root)}/"' in text - links = [ - ("a", "../../../../" + POC_REL, dashboard.raw_url(poc)), - ("a", "/" + POC_REL + "?mode=preview#tree", dashboard.raw_url(poc) + "?mode=preview#tree"), - ("a", "../mission.md#목표", dashboard.view_url(folder / "mission.md") + "#%EB%AA%A9%ED%91%9C"), - ("a", dashboard.raw_url(folder / "report.md"), dashboard.view_url(folder / "report.md")), - ("img", "/Wiki/" + quote(image.name), dashboard.raw_url(image)), - ("img", "../../../../Wiki/" + quote(image.name), dashboard.raw_url(image)), - ("a", "#목표", "#목표"), - ("a", "?mode=preview", "?mode=preview"), - ("a", "/", "/"), - ("a", "/view?path=original", "/view?path=original"), - ("a", "/mission?slot=slot1&id=run-1", "/mission?slot=slot1&id=run-1"), - ("a", "https://example.com/document.md", "https://example.com/document.md"), - ("a", "//example.com/document.md", "//example.com/document.md"), - ("a", "mailto:user@example.com", "mailto:user@example.com"), - ("a", "../50%.md", dashboard.view_url(folder / "50%.md")), - ("a", "../invalid%FF.md", "../invalid%FF.md"), - ("a", "../report.md", dashboard.view_url(folder / "report.md")), - ("img", "../../../../Wiki/" + quote(image.name), dashboard.raw_url(image)), - ] - script = r""" -const fs = require('node:fs'); -const vm = require('node:vm'); -const input = JSON.parse(fs.readFileSync(0, 'utf8')); -const elements = input.links.map(([tag, reference]) => ({ - tag, reference, - getAttribute() { return this.reference; }, - setAttribute(attribute, value) { this.reference = value; } -})); -const source = {textContent: '"# 확인"', dataset: input.dataset}; -const out = {querySelectorAll(selector) { return elements.filter(element => selector.startsWith(element.tag + '[')); }}; -vm.runInNewContext(input.script, { - URL, location: {href: 'http://127.0.0.1:8765/view?path=source'}, - document: {getElementById(id) { return id === 'source' ? source : out; }}, - window: {marked: {use() {}, parse() { return ''; }}} -}); -console.log(JSON.stringify(elements.map(element => element.reference))); -""" - result = subprocess.run( - [shutil.which("node"), "-e", script], - input=json.dumps({"links": links, "dataset": {"url": dashboard.raw_url(document), "root": dashboard.raw_url(root) + "/"}, - "script": dashboard.MARKDOWN_SCRIPT.removeprefix("\n\n")}), - capture_output=True, text=True, encoding="utf-8", check=True, - ) - references = json.loads(result.stdout) - for (tag, original, expected), reference in zip(links, references): - actual = reference.removeprefix("http://127.0.0.1:8765") - if expected.startswith("/view?path="): - actual_path = parse_qs(urlsplit(actual).query)["path"][0] - expected_path = parse_qs(urlsplit(expected).query)["path"][0] - assert slots.normalize(actual_path) == slots.normalize(expected_path), (tag, original) - assert urlsplit(actual).fragment == urlsplit(expected).fragment - else: - assert actual == expected, (tag, original) - for reference in references[:6]: - assert world.get(reference)[0] == 200 - assert world.get(dashboard.view_url(world.outside / "secret.md"))[0] == 403 - - -def test_mission_page_validates_slot_and_id(world): - folder = world.mission("slot1", "run-1") - write_question(folder, "ask-10.md", "질문", [("남은 결정", "pending")]) - write_question(folder, "ask-2.md", "질문", [("완료 결정", "answered")], answer="권장") - status, text = world.get("/mission?slot=slot1&id=run-1") - assert status == 200 - originals = text.split("질문·확인 원문

    ")[1] - assert originals.index("ask-2.md") < originals.index("ask-10.md") and "답 있음" in originals and "전체 1개 · 미답 1개" in originals - assert world.get("/mission?slot=slot1&id=..%2F..")[0] == 400 - assert world.get("/mission?slot=..&id=run-1")[0] == 400 - assert world.get("/mission?slot=slot9&id=run-1")[0] == 404 - assert world.get("/mission?slot=slot1&id=nope")[0] == 404 - assert world.get("/elsewhere")[0] == 404 - - -POC_REL = "Wiki/design/prototypes/x/index.html" - - -def add_poc(folder, root, rel=POC_REL, write=True): - mission_md = folder / "mission.md" - mission_md.write_text(mission_md.read_text(encoding="utf-8").replace("확인 A1: 대기\n", f"확인 A1: 대기\nPoC: {rel}\n"), encoding="utf-8") - poc = root / rel - if write: - poc.parent.mkdir(parents=True) - poc.write_text("", encoding="utf-8") - return poc - - -def raw_get(world, path): - return dashboard.route(world.config, path) - - -def test_mission_page_lists_poc_first_and_links_through_raw(world): - slot_poc = add_poc(world.mission("slot1", "run-1"), world.slot_root / "slot1") - main_poc = add_poc(world.mission("main", "run-2"), world.main) - status, text = world.get("/mission?slot=slot1&id=run-1") - assert status == 200 and f"PoC: {POC_REL}" not in text - assert f'href="{dashboard.raw_url(slot_poc)}"' in text and f"PoC · {POC_REL}" in text - assert text.index(f"PoC · {POC_REL}") < text.index("mission.md") - status, text = world.get("/mission?slot=main&id=run-2") - assert status == 200 and f'href="{dashboard.raw_url(main_poc)}"' in text - - -def test_mission_page_warns_when_poc_file_is_missing(world): - add_poc(world.mission("slot1", "run-1"), world.slot_root / "slot1", write=False) - status, text = world.get("/mission?slot=slot1&id=run-1") - assert status == 200 and f"PoC 파일 없음: {POC_REL}" in text and "/raw/" not in text - world.mission("slot1", "run-2") - assert "PoC" not in world.get("/mission?slot=slot1&id=run-2")[1] - - -def test_raw_serves_file_bytes_with_content_type_by_extension(world): - root = world.slot_root / "slot1" - poc = add_poc(world.mission("slot1", "run-1"), root) - status, content_type, body = raw_get(world, dashboard.raw_url(poc)) - assert (status, content_type, body) == (200, "text/html; charset=utf-8", poc.read_bytes()) - expected = { - "a.png": "image/png", - "a.js": "text/javascript; charset=utf-8", - "a.mjs": "text/javascript; charset=utf-8", - "a.css": "text/css; charset=utf-8", - "a.json": "application/json; charset=utf-8", - "a.svg": "image/svg+xml; charset=utf-8", - "a.woff2": "font/woff2", - "a.ttf": "font/ttf", - "a.txt": "text/plain; charset=utf-8", - "a.unknownext": "application/octet-stream", - } - for name, want in expected.items(): - (root / name).write_bytes(b"x") - assert raw_get(world, dashboard.raw_url(root / name))[:2] == (200, want), name - - -def test_raw_resolves_sibling_assets_from_relative_urls_in_the_page(world): - root = world.slot_root / "slot1" - poc = add_poc(world.mission("slot1", "run-1"), root) - (root / "Unity").mkdir() - (root / "Unity" / "한글 a#1.png").write_bytes(b"\x89PNG\r\n") - page_url = dashboard.raw_url(poc) - sibling = urljoin(page_url, "../../../../Unity/" + quote("한글 a#1.png")) - assert sibling.startswith("/raw/") and "/Wiki/" not in sibling - assert raw_get(world, sibling) == (200, "image/png", b"\x89PNG\r\n") - - -def test_raw_refuses_outside_roots_and_reports_missing_files(world): - root = world.slot_root / "slot1" - poc = add_poc(world.mission("slot1", "run-1"), root) - assert raw_get(world, dashboard.raw_url(world.outside / "secret.md"))[0] == 403 - sneaky = (str(root) + "/../../outside/secret.md").replace("\\", "/") - assert raw_get(world, "/raw/" + quote(sneaky, safe="/:"))[0] == 403 - assert raw_get(world, "/raw/" + quote(sneaky.replace("/..", "/%2e%2e"), safe="/:%"))[0] == 403 - assert raw_get(world, "/raw/relative/index.html")[0] == 403 - assert raw_get(world, "/raw/")[0] == 403 - assert raw_get(world, dashboard.raw_url(world.slot_root))[0] == 403 - assert raw_get(world, dashboard.raw_url(root / "nope.png"))[0] == 404 - assert raw_get(world, dashboard.raw_url(poc.parent))[0] == 404 - - -def test_unanswered_questions_uses_only_structured_status(tmp_path): - write_question(tmp_path, "ask-1.md", "미답", [("결정", "pending")], answer="권장", body="## 부록\n답변 완료") - write_question(tmp_path, "ask-2.md", "완료", [("결정", "answered")], answer="대안", intro="답변 대기") - (tmp_path / "ask-3.md").write_text("# 과거 질문\n\n## 답\n권장\n", encoding="utf-8") - assert mission_state.unanswered_questions(str(tmp_path), {}) == ["ask-1.md"] + assert status == 200 and "읽기 실패" in text and "broken-1" in text -def test_confirm_files_keep_typed_pending_when_mission_header_is_approved(tmp_path): - write_question(tmp_path, "confirm-A2.md", "확인 A2", [("결정", "pending")], answer="조건부 승인") - write_question(tmp_path, "confirm-C.md", "확인 C", [("결정", "answered")], approval="pending", answer="문항 승인") - fields = {"확인 A": "승인", "확인 A2": "승인", "확인 C": "승인"} - assert mission_state.unanswered_questions(str(tmp_path), fields) == ["confirm-A2.md", "confirm-C.md"] - - -def test_skeleton_confirm_is_waiting_and_labelled(world): - skeleton = "# 확인 A2\n\n## 뼈대 — 바꾸는 Model\n\n| 칸 |\n\n## 답\n\n- 2026-10-19 사용자: 이름 일반화\n" - folder = world.mission("slot1", "run-1", files={"confirm-A1.md": "# 확인 A1\n\n## 답\n", "confirm-A2.md": skeleton}, shared=["confirm-A1.md", "confirm-A2.md"]) - write_question(folder, "confirm-A1.md", "확인 A1", [("이전 결정", "answered")], answer="승인") - record = write_question(folder, "confirm-A2.md", "확인 A2", [("뼈대 확인", "pending")], approval="pending", body="## 뼈대 — 바꾸는 Model\n\n| 칸 |") - record["items"][0]["id"] = "scope" - record["answers"][-1]["updates"][0]["id"] = "scope" - (folder / "questions/confirm-A2.json").write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8") - question_records.render_saved_document(folder, "confirm-A2.md") - (folder / "mission.md").write_text("# 미션 run-1\n\n상태: 진행\n현재 단계: poc\n확인 A: A1승인\n", encoding="utf-8") - status, text = world.get("/") - assert status == 200 and "확인 A2 · 뼈대" in text and "confirm-A1.md" not in text - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_server_serves_on_loopback_and_refuses_a_busy_port(world, runtime): - if runtime == "codex": - shutil.copytree(world.main / ".claude", world.main / ".codex") - located = slots.locate(str(world.main), runtime) - config = slots.Config(located, slots.read_adapter(located.adapter_path, runtime), runtime) - folder = world.mission("slot1", "run-1") - poc = add_poc(folder, world.slot_root / "slot1") - server = dashboard.Server(config, 0) - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() +def test_loopback_serves_reads_and_rejects_answer_posts(world): + world.mission("slot1", "run-1") + server = dashboard.Server(world.config, 0) + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() try: host, port = server.server_address assert host == "127.0.0.1" - with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=10) as response: - assert response.status == 200 - with urllib.request.urlopen(f"http://127.0.0.1:{port}" + dashboard.view_url(poc), timeout=10) as response: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=5) as response: assert response.status == 200 - assert urlsplit(response.url).path == dashboard.raw_url(poc) - assert response.read() == poc.read_bytes() - with urllib.request.urlopen(f"http://127.0.0.1:{port}" + dashboard.view_url(folder / "mission.md"), timeout=10) as response: - assert b"const documentUrl" in response.read() with pytest.raises(urllib.error.HTTPError) as caught: - urllib.request.urlopen(f"http://127.0.0.1:{port}/view?path=x", timeout=10) + urllib.request.urlopen(f"http://127.0.0.1:{port}/view?path=x", timeout=5) assert caught.value.code == 403 - with pytest.raises(OSError): - dashboard.Server(world.config, port) - finally: - server.shutdown() - server.server_close() - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_dashboard_is_read_only_and_preserves_answer_history(world, runtime): - folder = world.mission("slot1", "run-1", files={ - "ask-1.md": "# 질문\n\n## 사용자 입력\n\n이전 답변\n\n## 답\n", - ".dashboard-answers/saved.json": '{"answer":"이전 답변"}', - }, shared=["ask-1.md"]) - (folder.parent / "ACTIVE").write_text(json.dumps({"id": folder.name, "session": "session-1"}), encoding="utf-8") - config = runtime_config(world, runtime) - status, _, page = dashboard.route(config, dashboard.view_url(folder / "ask-1.md")) - assert status == 200 - source = page.decode("utf-8").split('id="source"', 1)[1].split('>', 1)[1].split('', 1)[0] - assert "이전 답변" in json.loads(source) - assert all(markup not in page for markup in [b"= 1792452623 - - -def test_grok_running_subagent_without_child_transcript_stays_visible(tmp_path, monkeypatch): - monkeypatch.setenv("GROK_HOME", str(tmp_path / "grok")) - transcript = tmp_path / "example-session" / "updates.jsonl" - transcript.parent.mkdir() - write_lines(transcript, [grok_update("turn_completed", 1792452622000)]) - folder = transcript.parent / "subagents" / "worker-1" - folder.mkdir(parents=True) - (folder / "meta.json").write_text(json.dumps({ - "subagent_id": "worker-1", "parent_session_id": "example-session", "child_session_id": "child-session", "status": "running", - "started_at": "2026-10-20T02:10:23Z", - }), encoding="utf-8") - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(transcript)) - assert mission.background and mission.waiting_input - assert mission.last_activity == dashboard.parse_time("2026-10-20T02:10:23Z") - - -def test_grok_lifecycle_fallback_tracks_running_child_without_transcript(tmp_path, monkeypatch): - monkeypatch.setenv("GROK_HOME", str(tmp_path / "grok")) - transcript = tmp_path / "updates.jsonl" - identity = {"subagent_id": "worker-1", "parent_session_id": "example-session", - "child_session_id": "child-session", "attempt_id": "attempt-1"} - updates = [grok_update("turn_completed", 1792452622000), grok_update("subagent_spawned", 1792452623000, **identity)] - write_lines(transcript, updates) - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(transcript)) - assert mission.background and mission.waiting_input and mission.last_activity == 1792452623 - updates += [grok_update("subagent_finished", 1792452624000, status="completed", **identity)] - write_lines(transcript, updates) - dashboard.read_session(mission, str(transcript)) - assert not mission.background and mission.waiting_input and mission.last_activity == 1792452624 - - -def test_grok_dashboard_reuses_lifecycle_for_ordinary_appends(tmp_path, monkeypatch): - transcript = tmp_path / "updates.jsonl" - identity = {"subagent_id": "child", "child_session_id": "child-session", "attempt_id": "a1"} - spawn = grok_update("subagent_spawned", 1792452623000, **identity) - write_lines(transcript, [spawn]) - parse_children = dashboard_data.grok_transcript.subagent_records - calls = [] - - def count_parse(path): - calls.append(path) - return parse_children(path) - - monkeypatch.setattr(dashboard_data.grok_transcript, "subagent_records", count_parse) - assert dashboard_data.grok_children(str(transcript))[0]["status"] == "running" - with transcript.open("a", encoding="utf-8") as stream: - stream.write(json.dumps(grok_update("agent_message_chunk", 1792452623500)) + "\n") - assert dashboard_data.grok_children(str(transcript))[0]["status"] == "running" - assert len(calls) == 1 - with transcript.open("a", encoding="utf-8") as stream: - stream.write(json.dumps(grok_update("subagent_finished", 1792452624000, status="completed", **identity)) + "\n") - assert dashboard_data.grok_children(str(transcript))[0]["status"] == "completed" - assert len(calls) == 2 - - -def test_transcript_of_finds_grok_native_session(world, tmp_path, monkeypatch): - session = "11111111-2222-4333-8444-555555555555" - grok_home = tmp_path / "native-grok" - monkeypatch.setenv("GROK_HOME", str(grok_home)) - transcript = grok_home / "sessions" / "workspace-hash" / session / "updates.jsonl" - transcript.parent.mkdir(parents=True) - write_lines(transcript, [grok_update("turn_completed", 1792452622000)]) - folder = world.mission("slot1", "run-1") - (folder.parent / "ACTIVE").write_text(json.dumps({"id": folder.name, "session": session}), encoding="utf-8") - location = dashboard.locations(world.config)[1] - mission = dashboard.Mission("slot1", "run-1", str(folder), True) - assert dashboard.transcript_of(location, mission, []) == str(transcript) - - -def test_dashboard_runtime_option_reaches_adapter_and_config(world, monkeypatch): - seen = [] - original_locate, original_read = slots.locate, slots.read_adapter - - def locate(project, runtime): - seen.append(("locate", runtime)) - return original_locate(project, runtime) - - def read(path, runtime): - seen.append(("read", runtime)) - return original_read(path, runtime) - - class FakeServer: - def __init__(self, config, port): - seen.append(("config", config.runtime)) - self.server_address = ("127.0.0.1", port) - - def serve_forever(self): - raise KeyboardInterrupt() - - def server_close(self): - pass - - monkeypatch.setattr(configuration, "locate", locate) - monkeypatch.setattr(configuration, "read_adapter", read) - monkeypatch.setattr(dashboard, "Server", FakeServer) - assert dashboard.main(["--runtime", "grok", "--project", str(world.main)]) == slots.OK - assert seen == [("locate", "grok"), ("read", "grok"), ("config", "grok")] - - -def claude_turn(stop_reason, at="2026-10-20T02:31:42Z"): - return [ - {"type": "user", "timestamp": "2026-10-20T02:30:00Z", "message": {"role": "user", "content": "진행해"}}, - {"type": "assistant", "timestamp": at, "message": {"role": "assistant", "stop_reason": stop_reason, "content": [{"type": "text", "text": "ask-8 올림"}]}}, - {"type": "system", "subtype": "turn_duration", "timestamp": at}, - {"type": "last-prompt"}, - ] - - -def test_read_session_tells_turn_end_from_work_in_progress(tmp_path): - transcript = tmp_path / "s1.jsonl" - write_lines(transcript, claude_turn("end_turn")) - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(transcript)) - assert mission.waiting_input and not mission.background - assert mission.last_activity == dashboard.parse_time("2026-10-20T02:31:42Z") - - write_lines(transcript, claude_turn("tool_use")) - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(transcript)) - assert not mission.waiting_input - - subagents = tmp_path / "s1" / "subagents" - subagents.mkdir(parents=True) - (subagents / "agent-a.jsonl").write_text("{}\n", encoding="utf-8") - write_lines(transcript, claude_turn("end_turn")) - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(transcript)) - assert mission.background - - -def test_read_session_understands_codex_turn_events(tmp_path): - transcript = tmp_path / "rollout-2026-10-20T15-56-23-abc.jsonl" - started = {"timestamp": "2026-10-20T07:00:00Z", "type": "event_msg", "payload": {"type": "task_started"}} - done = {"timestamp": "2026-10-20T07:00:22Z", "type": "event_msg", "payload": {"type": "task_complete"}} - write_lines(transcript, [started, done]) - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(transcript)) - assert mission.waiting_input - write_lines(transcript, [done, started]) - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(transcript)) - assert not mission.waiting_input - - -def test_card_shows_input_waiting_for_active_session(world, tmp_path): - transcript = tmp_path / "s1.jsonl" - write_lines(transcript, claude_turn("end_turn")) - folder = world.mission("slot1", "run-1") - (folder / "units.tsv").write_text(f"{UNITS_HEADER}\n", encoding="utf-8") - header = "\t".join(mission_guard.SESSIONS_HEADER) - (folder / "sessions.tsv").write_text(f"{header}\n2026-10-20T11:00:00+09:00\topen\ts1\t{transcript}\n", encoding="utf-8") - (folder.parent / "ACTIVE").write_text(json.dumps({"id": "run-1", "session": "s1", "openedAt": "2026-10-20T11:00:00+09:00"}), encoding="utf-8") - status, text = world.get("/") - assert status == 200 and "입력 기다림" in text - - -def test_answer_heading_variants_do_not_supply_structured_status(tmp_path): - for number, heading in enumerate(("답변", "답 (2026-10-20)", "답하는 법"), 1): - write_question(tmp_path, f"ask-{number}.md", "질문", [("결정", "pending")], body=f"## {heading}\n권장") - assert mission_state.unanswered_questions(str(tmp_path), {}) == ["ask-1.md", "ask-2.md", "ask-3.md"] - - -def runtime_config(world, runtime): - if runtime == "codex": - shutil.copytree(world.main / ".claude", world.main / ".codex", dirs_exist_ok=True) - located = slots.locate(str(world.main), runtime) - return slots.Config(located, slots.read_adapter(located.adapter_path, runtime), runtime) - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_question_documents_are_automatic_and_other_documents_require_current_sharing(world, runtime): - files = { - "ask-1.md": "# 비공개 질문\n\n## 답\n", - "confirm-B.md": "# 비공개 확인\n\n## 답\n", - "details/evidence.md": "비공개 상세 원문", - "captures/x.png": "비공개 캡처 원문", - "artifact.json": "비공개 생성물 원문", - ".dashboard-answers/secret.json": "비공개 답변 기록", - } - folder = world.mission("slot1", "sharing-1", files=files) - write_question(folder, "ask-1.md", "비공개 질문", [("남은 범위", "pending")]) - write_question(folder, "confirm-B.md", "비공개 확인", [("남은 승인", "pending")]) - config = runtime_config(world, runtime) - def get(url): - status, _, body = dashboard.route(config, url) - return status, body.decode("utf-8", errors="replace") - overview = get("/")[1] - detail = get("/mission?slot=slot1&id=sharing-1")[1] - assert "보고에만 있는 과거 진행 요약" not in overview and "보고에만 있는 과거 진행 요약" not in detail - automatic = {"ask-1.md", "confirm-B.md"} - for name in automatic: - assert name in overview and name in detail - assert get(dashboard.view_url(folder / name))[0] == 200 - assert get(dashboard.raw_url(folder / name))[0] == 200 - for name in ("details/history/ask-1.md", "details/history/confirm-B.md"): - assert name in detail - assert get(dashboard.view_url(folder / name))[0] == 200 - assert get(dashboard.raw_url(folder / name))[0] == 200 - assert get(dashboard.raw_url(folder / "questions/ask-1.json"))[0] == 404 - for name in [name for name in [*files, "report.md"] if name not in automatic]: - assert name not in overview and name not in detail - for url in (dashboard.view_url(folder / name), dashboard.raw_url(folder / name)): - status, body = get(url) - assert status == 404 and "공유되지 않은 문서" in body - assert "비공개" not in body - assert get(dashboard.view_url(folder / "mission.md"))[0] == 200 - assert get(dashboard.raw_url(folder / "units.tsv"))[0] == 200 - published = {"ask-1.md", "report.md", "details/evidence.md", "captures/x.png", "artifact.json"} - world.share(folder, *sorted(published)) - overview = get("/")[1] - detail = get("/mission?slot=slot1&id=sharing-1")[1] - assert "비공개 질문" in overview and "보고에만 있는 과거 진행 요약" not in overview - assert "최근 보고" in detail and "보고에만 있는 과거 진행 요약" in detail - for name in published: - assert name in detail - assert get(dashboard.view_url(folder / name))[0] == 200 - assert get(dashboard.raw_url(folder / name))[0] == 200 - assert "confirm-B.md" in detail - assert mission_state.SHARED_DOCUMENTS_FILE not in detail - assert get(dashboard.raw_url(folder / mission_state.SHARED_DOCUMENTS_FILE))[0] == 404 - for name in published: - (folder / name).write_text("수정한 비공개 원문", encoding="utf-8") - overview = get("/")[1] - detail = get("/mission?slot=slot1&id=sharing-1")[1] - for name in published: - if name in automatic: - assert name in overview and name in detail - assert get(dashboard.view_url(folder / name))[0] == 200 - assert get(dashboard.raw_url(folder / name))[0] == 200 - continue - assert name not in overview and name not in detail - for url in (dashboard.view_url(folder / name), dashboard.raw_url(folder / name)): - status, body = get(url) - assert status == 404 and "수정한 비공개 원문" not in body - assert "보고에만 있는 과거 진행 요약" not in overview and "보고에만 있는 과거 진행 요약" not in detail - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_corrupt_manifest_preserves_auto_questions_and_refuses_other_documents(world, runtime): - folder = world.mission("slot1", "sharing-1", files={"ask-1.md": "비공개 질문", "details/proof.md": "비공개 근거"}) - config = runtime_config(world, runtime) - world.share(folder, "ask-1.md", "details/proof.md") - (folder / mission_state.SHARED_DOCUMENTS_FILE).write_text("잘못된 헤더\n", encoding="utf-8") - for url in (dashboard.view_url(folder / "ask-1.md"), dashboard.raw_url(folder / "ask-1.md")): - assert dashboard.route(config, url)[0] == 200 - for url in (dashboard.view_url(folder / "details/proof.md"), dashboard.raw_url(folder / "details/proof.md")): - assert dashboard.route(config, url)[0] == 404 - status, _, body = dashboard.route(config, "/mission?slot=slot1&id=sharing-1") - assert status == 200 and b"ask-1.md" in body and b"details/proof.md" not in body - assert mission_state.SHARED_DOCUMENTS_FILE in body.decode("utf-8") - assert dashboard.route(config, dashboard.view_url(folder / "mission.md"))[0] == 200 - assert dashboard.route(config, dashboard.raw_url(folder / "units.tsv"))[0] == 200 - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -@pytest.mark.parametrize("slot", ["main", "slot1"]) -def test_auto_questions_and_matching_details_survive_edits_hide_and_manifest_failure(world, runtime, slot): - folder = world.mission(slot, "automatic", files={ - "ask-7.md": "# 배포 범위 선택\n\n## 답\n", - "confirm-B.md": "# 구현 범위 승인\n\n## 답\n", - "details/ask-7.md": "# 질문 상세 근거\n", - "details/confirm-B.md": "# 확인 상세 근거\n", - "details/ask-orphan.md": "비공개 단독 상세", - "nested/ask-private.md": "비공개 중첩 질문", - ".secret/ask-hidden.md": "비공개 숨김 질문", - }) - write_question(folder, "ask-7.md", "배포 범위 선택", [("배포 범위", "pending")]) - write_question(folder, "confirm-B.md", "구현 범위 승인", [("구현 범위", "pending")]) - config = runtime_config(world, runtime) - manifest = folder / mission_state.SHARED_DOCUMENTS_FILE - assert not manifest.exists() - automatic = {"ask-7.md", "confirm-B.md", "details/ask-7.md", "details/confirm-B.md", "details/history/ask-7.md", "details/history/confirm-B.md"} - detail_url = f"/mission?slot={slot}&id=automatic" - - def check_documents(): - overview = dashboard.route(config, "/")[2].decode("utf-8") - detail = dashboard.route(config, detail_url)[2].decode("utf-8") - assert "ask-7.md" in overview and "confirm-B.md" in overview - assert all(name in detail for name in automatic) - for name in automatic: - assert dashboard.route(config, dashboard.view_url(folder / name))[0] == 200 - assert dashboard.route(config, dashboard.raw_url(folder / name))[0] == 200 - for name in ("report.md", "details/ask-orphan.md", "nested/ask-private.md", ".secret/ask-hidden.md"): - assert name not in detail - assert dashboard.route(config, dashboard.view_url(folder / name))[0] == 404 - assert dashboard.route(config, dashboard.raw_url(folder / name))[0] == 404 - return overview, detail - - check_documents() - assert not manifest.exists() - world.share(folder, "ask-7.md", "details/ask-7.md") - write_question(folder, "ask-7.md", "바뀐 배포 범위", [("배포 범위", "pending")]) - (folder / "details/ask-7.md").write_text("# 바뀐 상세 근거\n", encoding="utf-8") - assert "바뀐 배포 범위" in check_documents()[0] - assert dashboard.route(config, dashboard.raw_url(folder / "questions/history/ask-7/1.json"))[0] == 404 - assert "바뀐 상세 근거" in dashboard.route(config, dashboard.raw_url(folder / "details/ask-7.md"))[2].decode("utf-8") - mission_state.hide_documents(str(folder), ["ask-7.md", "details/ask-7.md"]) - check_documents() - manifest.write_text("잘못된 헤더\n", encoding="utf-8") - assert mission_state.SHARED_DOCUMENTS_FILE in check_documents()[1] - write_question(folder, "ask-7.md", "바뀐 배포 범위", [("배포 범위", "answered")], answer="권장안 승인") - location = next(item for item in dashboard.locations(config) if item.label == slot) - mission = dashboard.load_mission(location, "automatic") - assert mission.unanswered == ["confirm-B.md"] and set(mission.questions) == {"ask-7.md", "confirm-B.md"} - assert "ask-7.md" in dashboard.route(config, detail_url)[2].decode("utf-8") - for url in (dashboard.view_url(folder / "ask-7.md"), dashboard.raw_url(folder / "ask-7.md")): - assert dashboard.route(config, url)[0] == 200 - header = folder / "mission.md" - header.write_text(header.read_text(encoding="utf-8").replace("\n## 목표", "\n확인 B: 승인\n\n## 목표"), encoding="utf-8") - assert dashboard.load_mission(location, "automatic").unanswered == ["confirm-B.md"] - - -def directory_alias(link, target): - if os.name == "nt": - import _winapi - _winapi.CreateJunction(str(target), str(link)) - else: - link.symlink_to(target, target_is_directory=True) - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_auto_question_junction_aliases_cannot_publish_private_documents(world, runtime): - folder = world.mission("slot1", "aliases", files={ - "ask-1.md": "# 공개 질문\n", - "private/ask-1.md": "비공개 상세", - "private/secret.md": "비공개 원문", - ".hidden/ask-1.md": "숨김 원문", - }) - config = runtime_config(world, runtime) - directory_alias(folder / "details", folder / "private") - directory_alias(folder / "ask-alias.md", folder / "private") +def test_private_alias_is_not_served(world): + folder = world.mission("slot1", "aliases") directory_alias(folder / "ask-escape.md", world.outside) - directory_alias(folder / ".hidden-alias", folder) - external = world.slot_root / "slot1" / "private-alias" - directory_alias(external, folder) - paths = [folder / "details/ask-1.md", folder / "ask-alias.md/ask-1.md", folder / "ask-alias.md/secret.md", folder / ".hidden-alias/ask-1.md", external / "ask-1.md"] - assert mission_state.auto_question_documents(str(folder)) == {"ask-1.md"} - for path in paths: - for url in (dashboard.view_url(path), dashboard.raw_url(path)): - assert dashboard.route(config, url)[0] == 404 - escape = folder / "ask-escape.md/secret.md" - for url in (dashboard.view_url(escape), dashboard.raw_url(escape)): - assert dashboard.route(config, url)[0] == 403 - assert dashboard.route(config, dashboard.raw_url(folder / "ask-1.md"))[0] == 200 - world.share(folder, "private/secret.md") - assert dashboard.route(config, dashboard.raw_url(external / "private/secret.md"))[0] == 200 - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_nested_mission_questions_do_not_publish_unshared_enclosing_content(world, runtime): - outer = world.mission("slot1", "outer") - inner = outer / "nested" - inner.mkdir() - (inner / "mission.md").write_text("# 중첩 미션\n", encoding="utf-8") - (inner / "ask-1.md").write_text("# 비공개 중첩 질문\n", encoding="utf-8") - config = runtime_config(world, runtime) - assert mission_state.auto_question_documents(str(outer)) == set() - for url in (dashboard.view_url(inner / "ask-1.md"), dashboard.raw_url(inner / "ask-1.md")): - assert dashboard.route(config, url)[0] == 404 - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -@pytest.mark.parametrize("target_kind", ["outside", "private", "mission"]) -def test_mission_root_junctions_cannot_publish_another_directory(world, runtime, target_kind): - original = world.mission("slot1", "original", files={"ask-1.md": "# 기존 미션 질문\n"}) - target = world.outside - if target_kind == "private": - target = original.parents[2] / "private" - target.mkdir() - elif target_kind == "mission": - target = original - if target_kind in ("outside", "private"): - (target / "mission.md").write_text("# 비공개 대상 미션\n\n상태: 진행\n", encoding="utf-8") - (target / "ask-7.md").write_text("# 비공개 대상 질문\n\n## 답\n", encoding="utf-8") - alias = original.parent / "linked" - directory_alias(alias, target) - config = runtime_config(world, runtime) - location = next(item for item in dashboard.locations(config) if item.label == "slot1") - mission = dashboard.load_mission(location, "linked") - assert mission.fields == {} and mission.questions == {} and "미션 폴더 경로" in mission.errors - collected = next(item for item in dashboard.collect(config) if item.label == "slot1") - assert [item.id for item in collected.missions] == ["original"] - overview = dashboard.route(config, "/")[2].decode("utf-8") - assert "비공개 대상" not in overview - assert dashboard.route(config, "/mission?slot=slot1&id=linked")[0] == 404 - for name in ("ask-7.md", "ask-1.md", "mission.md"): - for url in (dashboard.view_url(alias / name), dashboard.raw_url(alias / name)): - assert dashboard.route(config, url)[0] in (403, 404) - assert dashboard.route(config, dashboard.raw_url(original / "ask-1.md"))[0] == 200 - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_configured_parent_state_directory_alias_keeps_automatic_questions(world, runtime): - original = world.mission("slot1", "automatic-parent", files={"ask-1.md": "# 부모 별칭 질문\n\n## 답\n"}) - write_question(original, "ask-1.md", "부모 별칭 질문", [("부모 경로 결정", "pending")]) - state_dir = original.parent - store = original.parents[2] / "mission-store" - state_dir.rename(store) - directory_alias(state_dir, store) - config = runtime_config(world, runtime) - overview = dashboard.route(config, "/")[2].decode("utf-8") - assert "부모 별칭 질문" in overview - assert dashboard.route(config, "/mission?slot=slot1&id=automatic-parent")[0] == 200 - for path in (original / "ask-1.md", store / "automatic-parent/ask-1.md"): - for url in (dashboard.view_url(path), dashboard.raw_url(path)): - assert dashboard.route(config, url)[0] == 200 - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_unshared_mission_documents_cannot_be_downloaded_through_symlinks(world, runtime): - folder = world.mission("slot1", "sharing-1", files={"details/proof.md": "비공개 근거"}) - config = runtime_config(world, runtime) - alias = world.slot_root / "slot1" / "alias.md" - outside = world.slot_root / "slot1" / "Wiki" / "guide.md" - outside.parent.mkdir() - outside.write_text("외부 위키 원문", encoding="utf-8") - escape = folder / "details" / "wiki.md" - try: - alias.symlink_to(folder / "details" / "proof.md") - escape.symlink_to(outside) - except OSError as exc: - pytest.skip(f"symlink unavailable: {exc}") - for path in (alias, escape): - for url in (dashboard.view_url(path), dashboard.raw_url(path)): - status, _, body = dashboard.route(config, url) - assert status == 404 and "공유되지 않은 문서" in body.decode("utf-8") - assert dashboard.route(config, dashboard.view_url(outside))[0] == 200 - world.share(folder, "details/proof.md") - assert dashboard.route(config, dashboard.view_url(alias))[0] == 200 - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_mission_documents_stay_private_while_mission_header_is_missing(world, runtime): - folder = world.mission("slot1", "sharing-1", files={"ask-1.md": "비공개 질문"}) - config = runtime_config(world, runtime) - (folder / "mission.md").unlink() - for url in (dashboard.view_url(folder / "ask-1.md"), dashboard.raw_url(folder / "ask-1.md")): - status, _, body = dashboard.route(config, url) - assert status == 404 and "공유되지 않은 문서" in body.decode("utf-8") - - -def subagent_entries(*, last): - work = [ - {"type": "user", "timestamp": "2026-10-20T08:30:00Z", "message": {"role": "user", "content": "리뷰해"}}, - {"type": "assistant", "timestamp": "2026-10-20T08:30:05Z", "message": {"role": "assistant", "stop_reason": "tool_use", "content": [{"type": "tool_use", "name": "Grep"}]}}, - {"type": "user", "timestamp": "2026-10-20T08:30:06Z", "message": {"role": "user", "content": [{"type": "tool_result", "content": "57:## Data"}]}}, - ] - endings = { - "waiting_model": [{"type": "api-request", "timestamp": "2026-10-20T08:30:07Z"}], - "handed_back": [ - {"type": "assistant", "timestamp": "2026-10-20T08:31:00Z", "message": {"role": "assistant", "stop_reason": "tool_use", "content": [{"type": "tool_use", "name": "SubagentHandback"}]}}, - {"type": "user", "timestamp": "2026-10-20T08:31:01Z", "message": {"role": "user", "content": [{"type": "tool_result", "content": "delivered"}]}}, - ], - "resumed": [ - {"type": "assistant", "timestamp": "2026-10-20T08:31:00Z", "message": {"role": "assistant", "stop_reason": "tool_use", "content": [{"type": "tool_use", "name": "SubagentHandback"}]}}, - {"type": "user", "timestamp": "2026-10-20T08:31:01Z", "message": {"role": "user", "content": [{"type": "tool_result", "content": "delivered"}]}}, - {"type": "user", "timestamp": "2026-10-20T08:40:00Z", "message": {"role": "user", "content": "하나 더 봐 줘"}}, - ], - } - return work + endings[last] - - -@pytest.mark.parametrize("last, notified, background", [ - ("waiting_model", False, True), - ("handed_back", False, False), - ("resumed", False, True), - ("waiting_model", True, False), -]) -def test_subagent_running_is_judged_by_its_own_ending(tmp_path, last, notified, background): - transcript = tmp_path / "s1.jsonl" - main = claude_turn("end_turn", at="2026-10-20T08:29:00Z") - if notified: - notice = "\nabc123\nkilled\n" - main.append({"type": "user", "timestamp": "2026-10-20T08:35:00Z", "message": {"role": "user", "content": notice}}) - main.append({"type": "assistant", "timestamp": "2026-10-20T08:35:05Z", "message": {"role": "assistant", "stop_reason": "end_turn", "content": [{"type": "text", "text": "멈춤"}]}}) - write_lines(transcript, main) - subagents = tmp_path / "s1" / "subagents" - subagents.mkdir(parents=True) - write_lines(subagents / "agent-abc123.jsonl", subagent_entries(last=last)) - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(transcript)) - assert mission.waiting_input and mission.background is background - - -@pytest.mark.parametrize("child_events, background", [ - (["task_started"], True), - (["task_started", "task_complete"], False), -]) -def test_codex_subagent_rollouts_are_found_by_parent_id(tmp_path, child_events, background): - day = tmp_path / "sessions" / dashboard.time.strftime("%Y/%m/%d") - day.mkdir(parents=True) - parent_id = "01a13e0e-f5ad-71f1-9431-954ce57aee7c" - child_id = "01a13e10-ec8f-7a22-923d-8d8922cacfd4" - other_id = "01a13e12-3a68-7623-90b7-48d1bc918e54" - parent = day / f"rollout-2026-10-20T14-35-30-{parent_id}.jsonl" - write_lines(parent, [ - {"timestamp": "2026-10-20T05:35:30Z", "type": "session_meta", "payload": {"id": parent_id, "thread_source": "user"}}, - {"timestamp": "2026-10-20T05:36:00Z", "type": "event_msg", "payload": {"type": "task_complete"}}, - ]) - child = [{"timestamp": "2026-10-20T05:37:39Z", "type": "session_meta", "payload": {"id": child_id, "parent_thread_id": parent_id}}] - child += [{"timestamp": "2026-10-20T05:40:00Z", "type": "event_msg", "payload": {"type": event}} for event in child_events] - write_lines(day / f"rollout-2026-10-20T14-37-39-{child_id}.jsonl", child) - stranger = [{"timestamp": "2026-10-20T05:39:04Z", "type": "session_meta", "payload": {"id": other_id, "parent_thread_id": "someone-else"}}] - write_lines(day / f"rollout-2026-10-20T14-39-04-{other_id}.jsonl", stranger + [{"timestamp": "2026-10-20T05:40:00Z", "type": "event_msg", "payload": {"type": "task_started"}}]) - mission = dashboard.Mission("slot1", "run-1", str(tmp_path), True) - dashboard.read_session(mission, str(parent)) - assert mission.waiting_input and mission.background is background - - -def write_units(folder, *specs): - rows = [] - for spec in specs: - row = dict(zip(mission_state.UNIT_HEADER, UNIT_ROW.split("\t"))) - row.update(spec) - rows.append("\t".join(row[name] for name in mission_state.UNIT_HEADER)) - (folder / "units.tsv").write_text(UNITS_HEADER + "\n" + "\n".join(rows) + "\n", encoding="utf-8") - - -def slot_summary(text, name="slot1"): - return re.search(r']*data-slot="' + name + r'">(.*?)', text, re.S).group(1) - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_slot_summary_keeps_goal_current_remaining_conditions_and_other_missions(world, runtime): - folder = world.mission("slot1", "primary") - goal = "긴 목표를 끊지 않고 전부 보여야 함 " * 12 + "목표 마지막 문장" - header = folder / "mission.md" - header.write_text(header.read_text(encoding="utf-8").replace("primary 목표 첫 줄", goal + "\n목표의 두 번째 줄"), encoding="utf-8") - write_units(folder, - {"id": "M1", "goal": "첫 번째 진행 작업", "status": "doing"}, - {"id": "M2", "goal": "병렬 진행 작업", "status": "doing"}, - {"id": "M3", "goal": "완료한 기반 작업", "status": "done"}, - {"id": "M4", "goal": "승인 조건을 가진 다음 작업", "status": "todo", "after": "M3", "human": "확인 B 승인 필요", "forbid": "사람 승인 전 제출 금지"}, - {"id": "M5", "goal": "선행을 기다리는 작업", "status": "todo", "after": "M2"}, - {"id": "M6", "goal": "보류 상태 작업", "status": "held"}, - {"id": "M7", "goal": "잘못된 선행 기록", "status": "todo", "after": "M99"}, - ) - world.mission("slot1", "another") - (folder.parent / "ACTIVE").write_text(json.dumps({"id": "primary", "session": "s1"}), encoding="utf-8") - config = runtime_config(world, runtime) - overview = dashboard.route(config, "/")[2].decode("utf-8") - card = slot_summary(overview) - assert goal in card and "목표의 두 번째 줄" in card and 'goal clamp' not in card - current = card.split('

    지금

    ')[1].split('')[0] - assert "첫 번째 진행 작업" in current and "병렬 진행 작업" in current - assert "남은 작업 6개 · 진행 중 포함" in card and "다음 후보" in card and "보류 상태 작업" in card - assert "선행 M3 완료" in card and "확인 B 승인 필요" in card and "사람 승인 전 제출 금지" in card - assert "선행 M2 병렬 진행 작업 (진행)" in card - assert "선행 M99: 등록된 작업을 찾을 수 없음 · 의존 상태 미확인" in card - assert '같은 슬롯의 다른 진행 미션 1개' in card and 'id=another' in card - assert overview.index('data-slot="slot1"') < overview.index('class="idle-board"') - assert 'class="board"' in overview and 'grid-template-columns:repeat(2,minmax(0,1fr))' in overview - assert '@media(max-width:800px){.board{grid-template-columns:1fr}}' in overview - assert '
    ' in card - assert 'data-key="current-slot1-primary"' in card and 'data-key="remaining-slot1-primary"' in card - detail = dashboard.route(config, "/mission?slot=slot1&id=primary")[2].decode("utf-8") - assert detail.index('id="current"') < detail.index('id="remaining"') < detail.index('data-key="source-documents"') - completed = re.search(r'
    (.*?)
    ', detail, re.S).group(1) - assert "완료 작업 1개" in completed and "완료한 기반 작업" in completed - assert '
    ask-1.md

    ' in card and '

    confirm-B.md

    ' in card - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -@pytest.mark.parametrize("answer", ["권장", "대안"]) -@pytest.mark.parametrize("name", ["ask-1.md", "confirm-A2.md", "confirm-B.md", "confirm-C.md"]) -def test_complete_structured_answers_leave_decisions_and_remain_in_originals(world, runtime, answer, name): - folder = world.mission("slot1", "answered") - write_question(folder, name, "완료한 결정", [("완료 항목", "answered")], answer=answer) - original = (folder / name).read_bytes() - config = runtime_config(world, runtime) - mission = dashboard.collect(config)[1].missions[0] - assert not mission.unanswered and not mission.question_issues - assert mission.questions[name].count_known and mission.questions[name].total_known - assert "완료한 결정" not in slot_summary(dashboard.route(config, "/")[2].decode("utf-8")) - detail = dashboard.route(config, "/mission?slot=slot1&id=answered")[2].decode("utf-8") - decisions = re.search(r'

    내 결정

    (.*?)
    ', detail, re.S).group(1) - assert "완료한 결정" not in decisions and "답 있음 · 전체 1개" in detail - assert dashboard.route(config, dashboard.view_url(folder / name))[0] == 200 - assert (folder / name).read_bytes() == original - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -@pytest.mark.parametrize("intro", ["답변 완료", "답변 대기", "질문 1 답변 접수 · 승인", "답변 완료 · 승인 대기"]) -@pytest.mark.parametrize("status,approval,pending", [("answered", "none", False), ("pending", "none", True), ("answered", "pending", True), ("withdrawn", "complete", False)]) -def test_typed_status_ignores_prose_and_mission_approval_headers(world, runtime, intro, status, approval, pending): - folder = world.mission("slot1", "typed-status") - write_question(folder, "confirm-A2.md", "문서 답변 상태 회귀", [("범위 결정", status)], approval=approval, answer="조건 확인 후 권장으로", intro=intro) - header = folder / "mission.md" - header.write_text(header.read_text(encoding="utf-8").replace("확인 A1: 대기", "확인 A1: 대기\n확인 A2: 승인"), encoding="utf-8") - config = runtime_config(world, runtime) - before = {path: path.read_bytes() for path in folder.rglob("*") if path.is_file()} - mission = dashboard.collect(config)[1].missions[0] - assert mission.questions["confirm-A2.md"].pending == pending - assert bool(mission.unanswered) == pending and not mission.question_issues - card = slot_summary(dashboard.route(config, "/")[2].decode("utf-8")) - detail = dashboard.route(config, "/mission?slot=slot1&id=typed-status")[2].decode("utf-8") - decisions = re.search(r'

    내 결정

    (.*?)
    ', detail, re.S).group(1) - assert ("문서 답변 상태 회귀" in card) == pending - assert ("문서 답변 상태 회귀" in decisions) == pending - assert {path: path.read_bytes() for path in folder.rglob("*") if path.is_file()} == before - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_partial_and_conditional_answers_keep_typed_pending_counts(world, runtime): - folder = world.mission("slot1", "partial") - write_question(folder, "ask-1.md", "부분 결정", [("끝난 결정", "answered"), ("조건부 결정", "pending"), ("남은 결정", "pending")], answer="1은 권장, 2는 조건 확인 후 진행") - write_question(folder, "ask-2.md", "철회 결정", [("철회 항목", "withdrawn")], answer="이 항목은 철회") - write_question(folder, "confirm-B.md", "최종 승인", [("답한 항목", "answered")], approval="pending", answer="문항만 승인") - config = runtime_config(world, runtime) - mission = dashboard.collect(config)[1].missions[0] - assert dashboard.decision_badge([mission]) == "답변 필요 2건" - assert dashboard.waiting_text(mission) == "대기 문서 2개 · 미답 항목 2개 · 전체 승인 확인 대기 1문서" - card = slot_summary(dashboard.route(config, "/")[2].decode("utf-8")) - assert "조건부 결정" in card and "남은 결정" in card and "끝난 결정" not in card - assert "철회 결정" not in card and "전체 승인 확인 대기" in card - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -@pytest.mark.parametrize("problem", ["legacy", "malformed", "malformed-source-only", "missing-markdown", "changed-markdown", "wrong-source-id"]) -def test_invalid_question_records_are_separate_from_pending_and_answered(world, runtime, problem): - folder = world.mission("slot1", "record-issues") - write_question(folder, "ask-1.md", "유효한 미답", [("남은 정책", "pending")]) - write_question(folder, "ask-2.md", "오류 문서", [("이미 답한 정책", "answered")], answer="권장") - source = folder / "questions/ask-2.json" - if problem == "legacy": - source.unlink() - elif problem in ("malformed", "malformed-source-only"): - source.write_text("{invalid", encoding="utf-8") - if problem == "malformed-source-only": - (folder / "ask-2.md").unlink() - elif problem == "missing-markdown": - (folder / "ask-2.md").unlink() - elif problem == "changed-markdown": - (folder / "ask-2.md").write_text("# 변경한 원문\n\n답변 완료\n- 답: 대안\n", encoding="utf-8") - else: - record = json.loads(source.read_text(encoding="utf-8")) - record["id"] = "ask-9" - source.write_text(json.dumps(record), encoding="utf-8") - config = runtime_config(world, runtime) - before = {path: path.read_bytes() for path in folder.rglob("*") if path.is_file()} - mission = dashboard.collect(config)[1].missions[0] - assert mission.unanswered == ["ask-1.md"] and set(mission.questions) == {"ask-1.md"} - assert set(mission.question_issues) == {"ask-2.md"} - overview = dashboard.route(config, "/")[2].decode("utf-8") - card = slot_summary(overview) - assert 'title="답변 필요 1건"' in card and 'title="기록 확인 필요 1건"' in card - assert "

    내 결정

    " in card and "

    기록 확인 필요

    " in card - assert "기록 확인 필요" in overview - detail = dashboard.route(config, "/mission?slot=slot1&id=record-issues")[2].decode("utf-8") - decisions = re.search(r'

    내 결정

    (.*?)
    ', detail, re.S).group(1) - issues = detail_dom(detail).elements("section", id="question-issues")[0] - assert "ask-2.md" not in decisions and "ask-2.md" in issues.text() - assert "답 있음" not in issues.text() and "답 있음" not in detail - if problem == "legacy": - assert "정형 전환 필요" in issues.text() - if problem not in ("missing-markdown", "malformed-source-only"): - assert dashboard.route(config, dashboard.view_url(folder / "ask-2.md"))[0] == 200 - assert dashboard.route(config, dashboard.raw_url(folder / "ask-2.md"))[0] == 200 - assert {path: path.read_bytes() for path in folder.rglob("*") if path.is_file()} == before - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -@pytest.mark.parametrize("problem", ["directory-file", "external-directory", "invalid-source-name"]) -def test_question_source_directory_errors_remain_visible(world, runtime, problem): - folder = world.mission("slot1", "source-errors") - if problem == "directory-file": - (folder / "questions").write_text("invalid source directory", encoding="utf-8") - elif problem == "external-directory": - directory_alias(folder / "questions", world.outside) - else: - (folder / "questions").mkdir() - (folder / "questions/unknown.json").write_text("{}", encoding="utf-8") - config = runtime_config(world, runtime) - mission = dashboard.collect(config)[1].missions[0] - assert mission.questions == {} and mission.unanswered == [] and mission.question_issues - overview = dashboard.route(config, "/")[2].decode("utf-8") - detail = dashboard.route(config, "/mission?slot=slot1&id=source-errors")[2].decode("utf-8") - assert "기록 확인 필요 1건" in overview and 'id="question-issues"' in detail - assert "비밀" not in overview and "비밀" not in detail - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -@pytest.mark.parametrize("state", ["중단", "닫힘"]) -def test_closed_legacy_questions_remain_available_as_originals(world, runtime, state): - folder = world.mission("slot1", "closed-legacy", state=state, files={"ask-1.md": "# 과거 질문\n\n- 답: 권장\n"}) - config = runtime_config(world, runtime) - assert "과거 질문" not in dashboard.route(config, "/")[2].decode("utf-8").split('data-key="mission-index"')[0] - detail = dashboard.route(config, "/mission?slot=slot1&id=closed-legacy")[2].decode("utf-8") - assert "이전 형식의 질문 원문" in detail and "ask-1.md" in detail - assert 'id="question-issues"' not in detail - assert dashboard.route(config, dashboard.view_url(folder / "ask-1.md"))[0] == 200 - assert "- 답: 권장" in dashboard.route(config, dashboard.raw_url(folder / "ask-1.md"))[2].decode("utf-8") - assert not (folder / "questions").exists() - - -@pytest.mark.parametrize("evidence", ["current-header", "history", "questions-directory"]) -def test_archived_question_with_structured_record_evidence_still_warns(world, evidence): - files = {"ask-1.md": "# Archived question\n\nUse the blue palette.\n"} - if evidence == "current-header": - files["ask-1.md"] += "\n문서: `ask-1` · 개정: 1\n" - if evidence == "history": - files["details/history/ask-1.md"] = "# Recorded revisions\n" - folder = world.mission("slot1", "closed-missing-source", state="닫힘", files=files) - if evidence == "questions-directory": - (folder / "questions").mkdir() - detail = world.get("/mission?slot=slot1&id=closed-missing-source")[1] - assert 'id="question-issues"' in detail and "정형 전환 필요" in detail - assert "이전 형식의 질문 원문" not in detail - - -def test_reports_remain_dated_history_and_do_not_change_work_or_session_freshness(world): - folder = world.mission("slot1", "freshness", shared=["report.md"]) - state_time = dashboard.parse_time("2026-10-20T03:00:00Z") - report_time = dashboard.parse_time("2026-10-18T03:00:00Z") - for name in ("mission.md", "units.tsv"): - os.utime(folder / name, (state_time, state_time)) - os.utime(folder / "report.md", (report_time, report_time)) - transcript = folder / "session.jsonl" - write_lines(transcript, claude_turn("end_turn", at="2026-10-22T03:00:00Z")) - (folder / "sessions.tsv").write_text("\t".join(mission_guard.SESSIONS_HEADER) + f"\n2026-10-22T12:00:00+09:00\topen\ts1\t{transcript}\n", encoding="utf-8") - (folder.parent / "ACTIVE").write_text(json.dumps({"id": "freshness", "session": "s1"}), encoding="utf-8") - mission = dashboard.collect(world.config)[1].missions[0] - assert mission.state_updated == state_time and mission.report_updated == report_time - assert mission.last_activity > mission.state_updated - card = slot_summary(world.get("/")[1]) - assert "보고에만 있는 과거 진행 요약" not in card and "세션: 입력 기다림" in card - card_meta = re.search(r'
    (.*?)
    ', card, re.S).group(1) - assert f'업무 자료 갱신 {dashboard.dated(state_time)}' in card_meta - detail = world.get("/mission?slot=slot1&id=freshness")[1] - report = re.search(r'
    (.*?)
    ', detail, re.S).group(1) - assert "최근 보고" in report and dashboard.dated(report_time) in report and "보고에만 있는 과거 진행 요약" in report - assert "보고에만 있는 과거 진행 요약" not in detail.split('data-key="recent-report"')[0] - - -def test_summary_escapes_work_and_flags_changed_question_markdown(world, monkeypatch): - folder = world.mission("slot1", "escaping") - write_question(folder, "ask-1.md", '', [("범위", "pending")]) - write_units(folder, {"goal": '', "human": "A & B"}) - card = slot_summary(world.get("/")[1]) - assert '질문' not in card and '<script>질문</script>' in card - assert 'A & B' in card - original = dashboard.read_shared_text - def concurrent_update(root, path): - if Path(path).name == "ask-1.md": - Path(path).write_text("# 변경한 제목\n", encoding="utf-8") - return original(root, path) - monkeypatch.setattr(dashboard_data, "read_shared_text", concurrent_update) - overview = world.get("/")[1] - assert "기록 확인 필요 1건" in overview and "<script>질문" not in overview - assert "생성 Markdown과 질문 JSON 불일치" in overview - - -@pytest.mark.parametrize("runtime", ["claude", "codex"]) -def test_one_unreadable_shared_question_does_not_answer_other_questions(world, runtime): - folder = world.mission("slot1", "unreadable", files={"ask-1.md": ""}) - write_question(folder, "confirm-B.md", "정상 승인 질문", [("아직 결정할 배포 범위", "pending")]) - write_question(folder, "ask-2.md", "정상 일반 질문", [("정상 미답", "pending")]) - (folder / "ask-1.md").write_bytes(b"\xff\xfe") - config = runtime_config(world, runtime) - card = slot_summary(dashboard.route(config, "/")[2].decode("utf-8")) - assert "정상 승인 질문" in card and "아직 결정할 배포 범위" in card - assert "정상 일반 질문" in card and 'title="답변 필요 2건"' in card - assert 'title="기록 확인 필요 1건"' in card and "ask-1.md" in card - - -def test_reshared_question_pending_is_computed_from_the_single_verified_snapshot(world, monkeypatch): - folder = world.mission("slot1", "snapshot") - write_question(folder, "ask-1.md", "정책 결정", [("이전 정책", "answered")], answer="승인") - read_text = dashboard.read_shared_text - calls = [] - def reshare_before_read(root, path): - if Path(path).name == "ask-1.md": - calls.append(path) - write_question(folder, "ask-1.md", "새 정책 결정", [("재검토할 정책", "pending")]) - world.share(folder, "ask-1.md") - return read_text(root, path) - monkeypatch.setattr(dashboard_data, "read_shared_text", reshare_before_read) - card = slot_summary(world.get("/")[1]) - assert len(calls) == 1 - assert "새 정책 결정" in card and "재검토할 정책" in card and "답변 필요 1건" in card - - -def test_question_titles_and_answer_badge_cover_all_running_missions(world): - primary = world.mission("slot1", "primary", files={"ask-1.md": "# 질문 1 · 보관 기간\n\n질문 1 답변 대기\n\n## 결정할 것\n\n### 1. 보관 기간\n"}, shared=["ask-1.md"]) - other = world.mission("slot1", "other", files={"ask-2.md": "# 질문 2\n\n질문 1 답변 대기 · 질문 2 답변 대기\n\n## 결정할 것\n\n### 1. 배포 범위\n\n### 2. 검증 범위\n"}, shared=["ask-2.md"]) - write_question(primary, "ask-1.md", "질문 1 · 보관 기간", [("보관 기간", "pending")]) - write_question(other, "ask-2.md", "질문 2", [("배포 범위", "pending"), ("검증 범위", "pending")]) - (primary.parent / "ACTIVE").write_text(json.dumps({"id": "primary", "session": "s1"}), encoding="utf-8") - card = slot_summary(world.get("/")[1]) - assert 'title="답변 필요 3건"' in card - assert "질문 1 · 보관 기간" in card and "질문 2 · 배포 범위 외 1개" in card - assert '

    ask-2.md · other

    ' in card - detail = world.get("/view?path=" + quote(str(other / "ask-2.md"), safe=""))[1] - assert "질문 2 · 배포 범위 외 1개" in detail - confirmation = world.mission("slot2", "confirmation", files={"confirm-B2.md": "# 확인 B2\n\n질문 1 답변 대기 · 질문 2 답변 대기\n\n## 결정할 것\n\n### 1. 서버 범위\n\n### 2. 데이터 범위\n"}, shared=["confirm-B2.md"]) - write_question(confirmation, "confirm-B2.md", "확인 B2", [("서버 범위", "pending"), ("데이터 범위", "pending")]) - detail = world.get("/view?path=" + quote(str(confirmation / "confirm-B2.md"), safe=""))[1] - assert "확인 B2 · 서버 범위 외 1개" in detail - - -def test_overview_previews_one_candidate_and_questions_without_repeating_doing(world): - items = "\n\n".join(f"### {number}. 결정할 항목 {number}" for number in range(1, 7)) - question = "# 여섯 가지 결정\n\n답변 대기\n\n## 결정할 것\n\n" + items - folder = world.mission("slot1", "compact", files={"ask-1.md": question}, shared=["ask-1.md"]) - write_question(folder, "ask-1.md", "여섯 가지 결정", [(f"결정할 항목 {number}", "pending") for number in range(1, 7)]) - write_units(folder, - {"id": "M1", "goal": "진행 작업은 현재에만", "status": "doing"}, - {"id": "M2", "goal": "첫 후보", "status": "todo", "after": "M1"}, - {"id": "M3", "goal": "보류 후보", "status": "held"}, - {"id": "M4", "goal": "세 번째 후보", "status": "todo"}, - ) - card = slot_summary(world.get("/")[1]) - card_root = detail_dom(card) - next_section = [node for node in card_root.elements("section") if any(heading.text() == "다음" for heading in node.elements("h3"))][0] - preview = next_section.text(visible=True) - assert "첫 후보" in preview and "보류 후보" not in preview and "세 번째 후보" not in preview - assert "진행 작업은 현재에만" not in preview - assert "남은 4개" in preview and "진행 중 포함" not in preview - remaining = next_section.elements("details", **{"data-key": "remaining-slot1-compact"})[0].text() - assert "남은 작업 4개 · 진행 중 포함" in remaining - assert "첫 후보" in remaining and "보류 후보" in remaining and "세 번째 후보" in remaining - decisions = card.split('

    내 결정

    ')[1] - question_preview = decisions.split('
    .*?
    ', decisions, re.S).group(0) - assert "미답 6개 펼치기" in question_details - assert all(f"결정할 항목 {number}" in question_details for number in range(1, 7)) - keys = re.findall(r'
    ]*>(.*?)
    ', card, re.S).group(1) - summary = re.search(r'(.*?)', details, re.S).group(1) - assert summary == '첫 줄 목표목표 접기' - assert f'

    {goal}

    ' in details - assert 'data-key="goal-slot1-goal"' in card - - -def test_embedded_document_uses_shared_renderer_and_access_rules(world): - folder = world.mission("slot1", "preview", files={"ask-1.md": "# Preview\n\n[Details](details.md)"}, shared=["ask-1.md"]) - direct = dashboard.view_url(folder / "ask-1.md") - status, text = world.get(direct + "&embedded=1") - assert status == 200 - assert 'id="source"' in text and 'id="out"' in text - assert '
    ' not in text and '