Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ jobs:
name: Python preflight
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0

- name: Install uv
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
version: "0.13.7"

- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with:
python-version: "3.11"

- name: Install dependencies
run: uv sync --all-extras --dev
run: uv sync --locked --all-extras --dev

- name: Format check
run: uv run ruff format --check agentic_internet tests
Expand All @@ -42,8 +42,10 @@ jobs:
run: python3 .opencode/tools/golden_principles.py

- name: Secret scan
uses: trufflesecurity/trufflehog@main
uses: trufflesecurity/trufflehog@4ef51f69ca6347aaa76a5e64a87eac9c0c909f71 # v3.100.1
with:
path: ./
base: ${{ github.event.repository.default_branch }}
head: HEAD
# Pin the scanner image too; the action otherwise pulls trufflehog:latest.
version: "3.100.1"
2 changes: 1 addition & 1 deletion docs/PLANS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Exec-plans capture non-trivial work before implementation and preserve handoff c

| Plan | Area | Depends on | Status |
|------|------|------------|--------|
| _None_ | - | - | - |
| [Evaluation-Driven Agent Runtime Modernization](exec-plans/active/2026-12-04-evaluation-driven-agent-runtime.md) | Agent execution, orchestration, observability, and evaluation | 001–005 | proposed |

## Status Maps

Expand Down
305 changes: 305 additions & 0 deletions docs/design-docs/2026-12-04-smolagents-behind-reliability-layer.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions docs/design-docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ This directory stores durable architectural decisions and design notes.
| Doc | Status | Summary |
|-----|--------|---------|
| [Core Beliefs](core-beliefs.md) | active | Agent-first operating beliefs for the repository |
| [Keep SmolAgents behind a reliability layer](2026-12-04-smolagents-behind-reliability-layer.md) | proposed | Keep SmolAgents as the execution engine behind a project-owned control plane; framework rewrite and multi-agent-first expansion rejected |

## ADR Template

Expand Down
645 changes: 645 additions & 0 deletions docs/exec-plans/active/2026-12-04-evaluation-driven-agent-runtime.md

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ description = "An intelligent agent system powered by smolagents for autonomous
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"smolagents[mcp]>=0.1.0",
"smolagents[mcp]>=1.21.2",
"transformers>=4.40.0",
"huggingface-hub>=0.23.0",
"torch>=2.0.0",
Expand Down Expand Up @@ -104,6 +104,7 @@ ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"
addopts = "--strict-markers"
markers = [
"integration: marks tests that require external services (deselect with '-m \"not integration\"')",
"integration: marks tests that require external services (deselect with '-m \"not integration\"'); exempt from the default-lane outbound network guard in tests/conftest.py",
]
238 changes: 238 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
"""Shared hermetic test fixtures for the default (deterministic) test lane.

Isolation happens in three layers, in this order:

1. **Import time** (this module body, which pytest imports before collecting any
test module): ``python-dotenv`` loading is replaced with a no-op, provider and
MCP variables are removed from ``os.environ``, and only then is the
``agentic_internet`` package imported. While the package is imported,
``Path.home()`` points at a throwaway directory so the module-level
``settings = Settings()`` creates its cache directory there instead of under
the developer's real ``~/.cache/agentic_internet``.
2. **Per test** (autouse fixtures): provider/MCP variables are cleared again so
a leaking test cannot affect the next one, and outbound network access is
blocked for every test that is not marked ``integration``.
3. **Opt-in** (``fresh_settings``): a brand-new ``Settings`` instance with a
per-test cache directory replaces the shared module-level ``settings``.

Only the standard library and pytest are used. Secret values are never read
into variables, printed, or logged; they are only removed.
"""

from __future__ import annotations

import atexit
import importlib
import ipaddress
import os
import shutil
import socket
import sys
import tempfile
from collections.abc import Iterator
from pathlib import Path
from typing import Any

import dotenv
import dotenv.main
import pytest

# ---------------------------------------------------------------------------
# Layer 1: import-time isolation (must run before any agentic_internet import)
# ---------------------------------------------------------------------------

#: Environment variables that must never reach the default test lane.
PROVIDER_ENV_VARS: tuple[str, ...] = (
"OPENAI_API_KEY",
"ANTHROPIC_API_KEY",
"OPENROUTER_API_KEY",
"HUGGINGFACE_TOKEN",
"HF_TOKEN",
"HUGGING_FACE_HUB_TOKEN",
"SERPAPI_API_KEY",
"EXA_API_KEY",
"BROWSER_USE_API_KEY",
"E2B_API_KEY",
)
#: Any variable with one of these prefixes is removed as well.
ISOLATED_ENV_PREFIXES: tuple[str, ...] = ("MCP_",)

#: True if something imported agentic_internet before this conftest ran, which
#: would mean the isolation below came too late. Asserted by the fixture tests.
PACKAGE_IMPORTED_BEFORE_CONFTEST = any(
name == "agentic_internet" or name.startswith("agentic_internet.") for name in sys.modules
)


def _disabled_load_dotenv(*_args: Any, **_kwargs: Any) -> bool:
"""No-op replacement for ``dotenv.load_dotenv``; reports that nothing loaded."""
return False


_disabled_load_dotenv.__hermetic_guard__ = True # type: ignore[attr-defined]

# ``from dotenv import load_dotenv`` binds whatever the attribute holds at import
# time, so patching both public locations before the package import is enough.
dotenv.load_dotenv = _disabled_load_dotenv
dotenv.main.load_dotenv = _disabled_load_dotenv


def is_isolated_env_var(name: str) -> bool:
"""Return True for provider credentials and MCP configuration variables."""
return name in PROVIDER_ENV_VARS or name.startswith(ISOLATED_ENV_PREFIXES)


def clear_isolated_env() -> None:
"""Remove provider/MCP variables from ``os.environ`` without reading values."""
for name in [key for key in os.environ if is_isolated_env_var(key)]:
del os.environ[name]


clear_isolated_env()

# Redirect Settings' default cache_dir (``Path.home() / ".cache" / ...``) for the
# module-level ``settings`` object created at package import time.
_IMPORT_HOME = Path(tempfile.mkdtemp(prefix="agentic-internet-test-home-"))
atexit.register(shutil.rmtree, _IMPORT_HOME, ignore_errors=True)

_real_path_home = Path.home
Path.home = classmethod(lambda cls: _IMPORT_HOME) # type: ignore[assignment,method-assign]
try:
import agentic_internet # noqa: F401 (import for its side effects, now isolated)

# ``agentic_internet.config.settings`` the *attribute* is the Settings
# instance (re-exported by ``config/__init__``), so fetch the module itself.
settings_module = importlib.import_module("agentic_internet.config.settings")
finally:
Path.home = _real_path_home # type: ignore[method-assign]

#: Cache directory created by the shared module-level settings during import.
IMPORT_CACHE_DIR = settings_module.settings.cache_dir


# ---------------------------------------------------------------------------
# Layer 2: per-test environment and network isolation
# ---------------------------------------------------------------------------

BLOCKED_NETWORK_MESSAGE = "Outbound network access is blocked in the default test lane"


class BlockedNetworkError(RuntimeError):
"""Raised when a non-integration test attempts a non-loopback connection."""


_LOOPBACK_HOSTNAMES = frozenset({"localhost", "localhost.localdomain", "ip6-localhost", "ip6-loopback"})


def _is_loopback_host(host: object) -> bool:
if isinstance(host, bytes):
host = host.decode("ascii", errors="replace")
if not isinstance(host, str):
return False
host = host.strip("[]").split("%", 1)[0].lower()
if host in _LOOPBACK_HOSTNAMES:
return True
try:
address = ipaddress.ip_address(host)
except ValueError:
return False
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
return address.ipv4_mapped.is_loopback
return address.is_loopback


def _is_allowed_address(family: int, address: object) -> bool:
if hasattr(socket, "AF_UNIX") and family == socket.AF_UNIX:
return True
if isinstance(address, tuple) and address:
return _is_loopback_host(address[0])
# Bare strings are AF_UNIX paths on POSIX; anything else is unknown.
return isinstance(address, str | bytes) and family not in (socket.AF_INET, socket.AF_INET6)


def _blocked(target: object) -> BlockedNetworkError:
return BlockedNetworkError(
f"{BLOCKED_NETWORK_MESSAGE}: attempted connection to {target!r}. "
"Use fakes/mocks, or mark the test with @pytest.mark.integration."
)


@pytest.fixture(autouse=True)
def _hermetic_env() -> Iterator[None]:
"""Ensure every test starts without provider credentials or MCP config."""
clear_isolated_env()
yield


@pytest.fixture(autouse=True)
def _block_outbound_network(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""Block non-loopback socket connections unless the test is ``integration``.

Loopback (127.0.0.0/8, ::1, ``localhost``) and AF_UNIX stay allowed so local
servers and pipes (e.g. stdio MCP subprocesses) keep working. The guard only
applies to this Python process; child processes are not patched.
"""
if request.node.get_closest_marker("integration") is not None:
yield
return

real_connect = socket.socket.connect
real_connect_ex = socket.socket.connect_ex
real_create_connection = socket.create_connection
real_getaddrinfo = socket.getaddrinfo

def guarded_connect(self: socket.socket, address: Any) -> None:
if not _is_allowed_address(self.family, address):
raise _blocked(address)
return real_connect(self, address)

def guarded_connect_ex(self: socket.socket, address: Any) -> int:
if not _is_allowed_address(self.family, address):
raise _blocked(address)
return real_connect_ex(self, address)

def guarded_create_connection(address: Any, *args: Any, **kwargs: Any) -> socket.socket:
# Check before name resolution so no DNS query leaves the machine.
if not (isinstance(address, tuple) and address and _is_loopback_host(address[0])):
raise _blocked(address)
return real_create_connection(address, *args, **kwargs)

def guarded_getaddrinfo(host: Any, *args: Any, **kwargs: Any) -> Any:
if host is not None and not _is_loopback_host(host):
raise _blocked(host)
return real_getaddrinfo(host, *args, **kwargs)

for guard in (guarded_connect, guarded_connect_ex, guarded_create_connection, guarded_getaddrinfo):
guard.__hermetic_guard__ = True # type: ignore[attr-defined]

monkeypatch.setattr(socket.socket, "connect", guarded_connect)
monkeypatch.setattr(socket.socket, "connect_ex", guarded_connect_ex)
monkeypatch.setattr(socket, "create_connection", guarded_create_connection)
monkeypatch.setattr(socket, "getaddrinfo", guarded_getaddrinfo)
yield


# ---------------------------------------------------------------------------
# Layer 3: opt-in fresh settings
# ---------------------------------------------------------------------------


@pytest.fixture
def fresh_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> settings_module.Settings:
"""Provide a new ``Settings`` built from the (isolated) current environment.

The instance replaces every already-imported ``agentic_internet`` module
attribute that referenced the shared module-level ``settings`` object (for
example ``config.settings``, ``utils.model_utils``, ``agents.internet_agent``
and ``cli``). Its cache directory lives under ``tmp_path``. Set environment
variables with ``monkeypatch.setenv`` *before* requesting this fixture if a
test needs specific keys.
"""
shared = settings_module.settings
fresh = settings_module.Settings(cache_dir=tmp_path / "agentic_internet_cache")
for name, module in list(sys.modules.items()):
if module is None or not (name == "agentic_internet" or name.startswith("agentic_internet.")):
continue
if getattr(module, "settings", None) is shared:
monkeypatch.setattr(module, "settings", fresh)
return fresh
41 changes: 41 additions & 0 deletions tests/fixtures/mcp_echo_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Minimal, offline stdio MCP server used by the local MCP lifecycle tests.

This script is repository-controlled test infrastructure. It only uses the
installed ``mcp`` package (``mcp.server.fastmcp``), performs no network I/O,
and communicates with its parent exclusively over stdin/stdout pipes.
"""

import os

from mcp.server.fastmcp import FastMCP

server = FastMCP(name="agentic-internet-test-echo", log_level="WARNING")


@server.tool()
def echo(text: str) -> str:
"""Return the given text prefixed with ECHO_PREFIX (default "echo: ")."""
prefix = os.environ.get("ECHO_PREFIX", "echo: ")
return f"{prefix}{text}"


@server.tool()
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b


@server.tool()
def server_pid() -> int:
"""Return the operating-system process id of this server."""
return os.getpid()


@server.tool()
def env_is_set(name: str) -> bool:
"""Report whether an environment variable is present (never its value)."""
return name in os.environ


if __name__ == "__main__":
server.run(transport="stdio")
Loading
Loading