from __future__ import annotations import asyncio import json from datetime import datetime, timezone from pathlib import Path import pytest import aura.agents.aegis.tools as aegis import aura.agents.atlas.tools as atlas import aura.agents.iris.tools as iris import aura.agents.logos.tools as logos import aura.agents.phantom.tools as phantom import aura.browser.hermes.tools as hermes from aura.core.config import AppConfig, EnsembleSettings, FeatureFlags, ModelSettings, PathsSettings from aura.core.event_bus import EventBus def _config(tmp_path: Path) -> AppConfig: return AppConfig( name="AURA", offline_mode=True, log_level="INFO", primary_model=ModelSettings(provider="ollama", name="llama3:8b", host="http://127.0.0.1:11434"), fallback_models=[], paths=PathsSettings( allowed_roots=[tmp_path], data_dir=tmp_path, log_dir=tmp_path / "logs", memory_dir=tmp_path / "memory", ipc_socket=tmp_path / "aura.sock", ), features=FeatureFlags(hotkey=True, tray=True, ipc=True, api=True), source_path=tmp_path / "config.yaml", ensemble=EnsembleSettings( enabled=True, default_importance_threshold=2, models=["llama3:8b", "mistral:7b"], judge_model="llama3:8b", model_timeout_seconds=5, min_successful_responses=2, fallback_to_single=True, ), ) def test_atlas_file_branches(tmp_path, monkeypatch): config = _config(tmp_path) atlas.set_config(config) target = tmp_path / "latin1.txt" target.write_bytes("café".encode("latin-1")) content = atlas.read_file(str(target)) assert content.encoding == "latin-1" assert content.content == "café" assert atlas._content_snippet("alpha\nbeta", "missing") == "alpha\nbeta"[:200] assert atlas._content_snippet("alpha match", "match") == "alpha match" with pytest.raises(atlas.AtlasError): atlas._validate_allowed(Path("../escape.txt")) with pytest.raises(atlas.AtlasError): atlas.search_files("alpha", str(tmp_path / "missing-root"), "keyword") with pytest.raises(atlas.AtlasError): atlas.search_files("alpha", str(tmp_path), "invalid") original = tmp_path / "note.txt" original.write_text("old", encoding="utf-8") written = atlas.write_file(str(original), "new", mode="overwrite") assert written.success is True assert original.read_text(encoding="utf-8") == "new" appended = atlas.write_file(str(original), "!", mode="append") assert appended.success is True assert original.read_text(encoding="utf-8") == "new!" patched = atlas.write_file(str(original), "---", mode="patch") assert patched.success is False deleted = atlas.delete_file(str(original)) assert deleted.success is True assert (tmp_path / ".aura_trash").exists() renamed = atlas.rename_file(str(tmp_path / "renamed.txt"), "final.txt") assert renamed.success is False def test_logos_router_and_patch_branches(tmp_path, monkeypatch): class Router: async def generate(self, prompt: str): if "bad" in prompt: return type("R", (), {"ok": False, "content": "", "error": "boom"})() return type("R", (), {"ok": True, "content": json.dumps({"generated_code": "print('ok')", "suggested_path": "gen.py", "explanation": "done", "language": "python"})})() async def chat(self, messages, options=None): return {"message": {"content": "chat-answer"}} logos.set_router(Router()) assert logos._as_text_response({"content": "a"}) == "a" assert logos._as_text_response({"message": {"content": "b"}}) == "b" assert logos._as_text_response({"response": "c"}) == "c" assert logos._parse_json_or_fallback("not-json", "orig")["fixed_code"] == "orig" assert logos._parse_code_patch("not-json", "python")["suggested_path"] == "generated.python" ok = asyncio.run(logos._generate_from_router("hello")) assert ok.startswith("{") parsed = asyncio.run(logos.debug_code("print(1)", "error")) assert parsed.fixed_code == "print(1)" assert logos.explain_code("print(1)", mode="line_by_line").mode == "line_by_line" assert logos.run_code("select 1", "sql").exit_code == 0 assert logos.run_code("print(1)", "python").language == "python" with pytest.raises(logos.LogosError): logos.run_code("", "brainfuck") def fake_run(*args, **kwargs): raise OSError("boom") monkeypatch.setattr(logos.subprocess, "run", fake_run) failure = logos._run_bash("echo hi", None) assert failure.exit_code == 1 def test_aegis_and_phantom_branches(tmp_path, monkeypatch): config = _config(tmp_path) aegis.set_config(config) phantom.set_config(config) bus = EventBus() aegis.set_event_bus(bus) phantom.set_event_bus(bus) assert aegis._bytes_to_gb(1024**3) == 1.0 assert aegis._to_datetime(0).tzinfo is not None with pytest.raises(aegis.AegisError): aegis._validate_shell_command("echo hi && rm -rf /") class Proc: def __init__(self): self.pid = 123 self.info = {"pid": 123, "name": "demo", "status": "running", "cpu_percent": 1.0, "memory_info": type("M", (), {"rss": 1024})(), "create_time": 0.0, "username": "u", "cmdline": ["demo"]} monkeypatch.setattr(aegis.psutil, "process_iter", lambda *_args, **_kwargs: [Proc()]) monkeypatch.setattr(aegis.subprocess, "run", lambda *args, **kwargs: __import__("subprocess").CompletedProcess(args=args[0], returncode=0, stdout="out", stderr="")) assert aegis.list_processes(sort_by="pid", limit=1)[0].pid == 123 assert aegis.get_process("demo").name == "demo" assert aegis.run_shell_command("echo hi").exit_code == 0 with pytest.raises(aegis.AegisError): aegis.list_processes(sort_by="invalid") monkeypatch.setattr(aegis, "get_process", lambda name_or_pid: type("P", (), {"pid": 123, "name": "demo"})()) monkeypatch.setattr(aegis, "_kill_pid", lambda pid, force: None) assert aegis.kill_process("123").success is True aegis.set_environment_variable("AURA_TEST", "1") assert aegis.get_environment_variable("AURA_TEST") == "1" assert phantom._task_next_run("hourly", phantom._now()).hour >= phantom._now().hour assert phantom._hash_text("x") assert phantom._initial_watch_hash("value", "text") phantom.pause_all(1) assert phantom.get_phantom_status()["paused"] is True phantom.resume_all() assert phantom.get_phantom_status()["paused"] is False def test_iris_and_hermes_branches(tmp_path, monkeypatch): config = _config(tmp_path) iris.set_config(config) hermes.set_config(config) hermes.set_event_bus(EventBus()) local_page = tmp_path / "page.html" local_page.write_text("
| A |