diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eea0e35..2a2512d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ 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 @@ -19,12 +19,12 @@ jobs: 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 @@ -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" diff --git a/docs/PLANS.md b/docs/PLANS.md index aad9208..8ffb2fc 100644 --- a/docs/PLANS.md +++ b/docs/PLANS.md @@ -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 diff --git a/docs/design-docs/2026-12-04-smolagents-behind-reliability-layer.md b/docs/design-docs/2026-12-04-smolagents-behind-reliability-layer.md new file mode 100644 index 0000000..57a0d62 --- /dev/null +++ b/docs/design-docs/2026-12-04-smolagents-behind-reliability-layer.md @@ -0,0 +1,305 @@ +--- +title: "Keep SmolAgents behind a project-owned reliability layer" +status: proposed +date: 2026-12-04 +deciders: maintainers (pending review) +roadmap: ../exec-plans/active/2026-12-04-evaluation-driven-agent-runtime.md +phase: RTM-0 +--- + +# ADR: Keep SmolAgents Behind a Project-Owned Reliability Layer + +## Status + +**Proposed.** Drafted as part of RTM-0 of the +[Evaluation-Driven Agent Runtime Modernization](../exec-plans/active/2026-12-04-evaluation-driven-agent-runtime.md) +roadmap. It becomes **accepted** when a maintainer approves it (tracked as +`agentic-internet-8xh`). The RTM-0 characterization tests it called for have +landed and were re-pinned after the PR #7 merge: behavior PR #7 fixed is now +pinned as fixed, and defects that remain keep their RTM phase tags. Until +acceptance, it constrains planning only; no runtime code changes because of it. + +> **Context refreshed (2026-12-04)** after merging upstream PR #7 +> (stabilization baseline, upstream plans 001–005) at merge commit `55566a7`. +> Code citations now point at the merged code. Defects that PR #7 fixed are +> recorded as fixed rather than as current evidence. The Decision, the rejected +> alternatives, and the proposed status are unchanged. + +## Context + +Agentic Internet grew from experiments into several execution paths that share +SmolAgents but not lifecycle semantics. This ADR was first drafted against +commit `bb2dcd0`. The evidence below was re-verified at merge commit `55566a7`. + +Upstream PR #7 fixed several local contracts with targeted patches: + +- `InternetAgent` now passes `max_steps` and `planning_interval` to both + `ToolCallingAgent` and `CodeAgent`, and an explicit `tools=[]` stays empty + ([internet_agent.py:66](../../agentic_internet/agents/internet_agent.py#L66), + [internet_agent.py:93-126](../../agentic_internet/agents/internet_agent.py#L93-L126)). +- Upstream Plan 004 split the 1,387-line `multi_model_serpapi.py`; it is now + a compatibility re-export of the `agents/multi_model/` package + ([multi_model_serpapi.py](../../agentic_internet/agents/multi_model_serpapi.py)). +- `ModelManager` resolves explicit central aliases exactly. +- LiteLLM is upgraded to 1.108.3, and CI pins setup-uv v10.3.3 by SHA with uv + 0.13.7. + +PR #7 explicitly left execution lifecycle, cancellation, concurrent-execution +safety, provider timeout policy, and model-registry consolidation as follow-ups +([CODEBASE_STATUS.md](../CODEBASE_STATUS.md#L28-L33), +[PLANS.md](../PLANS.md#L38)). As of `55566a7`, these problems remain: + +- **Run limits are not policy-driven across paths.** `InternetAgent` is now + consistent (fixed upstream in PR #7). Multi-model workers still ignore recipe + limits: `CodeAgent` workers get a hardcoded `max_steps=20`, and + `ToolCallingAgent` workers get the SmolAgents default + ([system.py:210-233](../../agentic_internet/agents/multi_model/system.py#L210-L233)). + On the SmolAgents-backed paths, reaching max steps still returns an ordinary + answer rather than a distinct state, because `return_full_result` is unused. +- **Failures are encoded as ordinary strings.** Agent and worker exceptions are + returned as text + ([internet_agent.py:177-191](../../agentic_internet/agents/internet_agent.py#L177-L191), + [basic_agent.py:65-66](../../agentic_internet/agents/basic_agent.py#L65-L66), + [multi_model/tools.py:433-441](../../agentic_internet/agents/multi_model/tools.py#L433-L441)), + so callers, the CLI, and coordinating agents cannot tell success from failure. +- **Timeouts do not stop work.** The multi-model workflow wraps a synchronous run + in `asyncio.wait_for(asyncio.to_thread(...))`; cancelling the await leaves the + thread running. The timeout message also interpolates `timeout` rather than + `effective_timeout`, so it reports `None` when a caller passes no timeout + and the recipe default applies + ([system.py:423-446](../../agentic_internet/agents/multi_model/system.py#L423-L446)). +- **Declared controls are not enforced.** Workers declared `required` can be + skipped with only a log message + ([use_cases.py:21](../../agentic_internet/agents/use_cases.py#L21), + [system.py:136-138](../../agentic_internet/agents/multi_model/system.py#L136-L138), + [system.py:246-247](../../agentic_internet/agents/multi_model/system.py#L246-L247), + [system.py:326-330](../../agentic_internet/agents/multi_model/system.py#L326-L330)). + The `multi` CLI command accepts `--workers` but never forwards it + ([cli.py:184-229](../../agentic_internet/cli.py#L184-L229)). +- **Model resolution is still split.** Upstream Plan 002 made `ModelManager` + resolve explicit central aliases first + ([model_manager.py:79-92](../../agentic_internet/agents/multi_model/model_manager.py#L79-L92)). + `ModelManager` still eagerly builds its own hardcoded model suite and keeps + legacy name and role mappings with fallback + ([model_manager.py:19-72](../../agentic_internet/agents/multi_model/model_manager.py#L19-L72), + [model_manager.py:94-186](../../agentic_internet/agents/multi_model/model_manager.py#L94-L186)). + These sit alongside the settings catalog and `initialize_model()` + ([model_utils.py:66-128](../../agentic_internet/utils/model_utils.py#L66-L128)). +- **Run state is shared.** Search tools hold a back-reference to the system + and mutate its current-run context, which each new run overwrites + ([multi_model/tools.py:86-107](../../agentic_internet/agents/multi_model/tools.py#L86-L107), + [system.py:304-306](../../agentic_internet/agents/multi_model/system.py#L304-L306)). +- **There is no evaluation harness.** Tests pin wiring with fakes; no versioned + outcome datasets, trajectory replay, or single- versus multi-agent comparison + exist. + +The baseline is otherwise healthy. At `bb2dcd0`, 198 tests passed and Ruff and +mypy were clean. The post-merge test count is recorded in the roadmap's +Progress Log. RTM-0 raised the floor to `smolagents[mcp]>=1.21.2` +([pyproject.toml](../../pyproject.toml#L12)), and CI installs from the lockfile +([ci.yml](../../.github/workflows/ci.yml#L26-L27)). `uv.lock` still resolves +SmolAgents **1.21.2** ([uv.lock](../../uv.lock#L2996-L2997)). PR #7 changed only +LiteLLM among direct dependencies. + +Inspection of the installed 1.21.2 API (re-checked after the merge) shows that +most missing reliability features already exist in SmolAgents. Since PR #7, +`InternetAgent` uses `max_steps` and `planning_interval`, but multi-model +workers still do not take their limits from recipes. These features remain +unused here: + +- `step_callbacks` +- `final_answer_checks` +- `managed_agents` (with `name`/`description`/`provide_run_summary`) +- `return_full_result` +- `RunResult`, which carries `output`, `state` (`success` | + `max_steps_error`), `messages`, `token_usage`, and `timing` + +The problem is therefore **inconsistent use of the framework and absent +project-level contracts**, not a missing framework capability. + +## Decision + +1. **Keep SmolAgents as the agent execution engine.** Its ReAct loop, + `ToolCallingAgent`, `CodeAgent`, model adapters, and `Tool` protocol remain the + data plane. The project does not build a second agent loop. + +2. **Add a thin, project-owned reliability layer (control plane)** under a new + `agentic_internet/runtime/` package. It owns: + - typed contracts: `RunRequest`, `RuntimePolicy`, `RunResult`, `WorkerResult`, + `RunEvent`, `RunContext`, and `RunManifest`; + - terminal states: success, partial/max steps, degraded, failed, timed out, + cancelled, and blocked/approval-required; + - budgets, deadlines, cooperative cancellation, and transient-only retries; + - explicit fallback recording (requested versus effective provider/model); + - deterministic enforcement of recipe controls (required workers, per-worker + limits, `max_workers`); + - per-run and per-attempt state isolation; + - redacted, schema-versioned structured events. + +3. **Draw the boundary between deterministic and probabilistic responsibilities.** + + | Control plane (typed Python, deterministic) | Data plane (SmolAgents + prompts, probabilistic) | + |---|---| + | Lifecycle, terminal status, exit codes | Research judgment and source selection | + | Budgets, deadlines, cancellation, retries | Tool choice within permitted tools | + | Output-contract validation | Synthesis and writing | + | Security, approvals, redaction | Delegation among legal worker actions | + | Concurrency and required-worker enforcement | Planning content | + +4. **Confine SmolAgents run-lifecycle APIs to an adapter.** Only + `runtime/smolagents_adapter.py` consumes `RunResult`, `step_callbacks`, + `final_answer_checks`, and `managed_agents`. Agents, tools, and the CLI depend + on project contracts. The `smolagents.Tool` subclassing used by existing tools + stays as-is; it is the tool contract, not run-lifecycle coupling. + +5. **Preserve compatibility through a strangler migration.** + - Public imports in [`agentic_internet/__init__.py`](../../agentic_internet/__init__.py) + and existing CLI commands keep working. + - `InternetAgent.run() -> str`, research dictionaries, search dictionaries, and + multi-model JSON output are produced from `RunResult` by explicit legacy + serializers. Typed results are exposed through new, additive APIs. + - The new runtime is opt-in behind one centralized setting that defaults to + the legacy path until parity tests and evaluation baselines pass. + - Any behavior change — for example, nonzero CLI exit codes for failed runs — + is documented here or in a successor ADR and enabled only at the rollout + boundary. + - Legacy classes are not deleted under this decision; removal requires a + separate deprecation decision. + +6. **Pin the tested framework version.** Raise the SmolAgents floor to the + oldest version verified to provide the APIs above (currently verified against + 1.21.2) and install from the lockfile in CI. SmolAgents upgrades become + intentional changes gated by adapter contract tests. + +## Alternatives Considered + +### A. Rewrite on another agent framework — **Rejected** + +Replace SmolAgents with a different orchestration framework or durable-execution +engine, or write a bespoke agent loop. + +- **Why it is attractive:** some frameworks ship graph orchestration, + checkpointing, or tracing integrations out of the box. +- **Why it is rejected:** + - The diagnosed failures are project-level: unused framework features, missing + contracts, string-encoded errors, and shared state. A new framework would + not fix them; the same contracts would still need to be written. + - SmolAgents 1.21.2 already provides the needed hooks (step callbacks, full + run results, final-answer checks, managed agents, planning intervals). + - A rewrite touches every agent, the CLI, all tools built on `smolagents.Tool`, + Code Mode, MCP integration, and the public import surface at once. The + characterization and regression tests from RTM-0 and PR #7 pin the current + paths. A rewrite would replace all of those paths at once, so every one of + them would need new parity evidence before any could ship. + - It adds a new core dependency, which + [AGENTS.md](../../AGENTS.md) treats as an ask-for-help trigger, and it + conflicts with the no-big-bang-rewrite constraint in the roadmap. + - It loses existing integrations whose behavior is documented and tested, such + as `CodeAgent` executors and MCP tool collections. +- **Revisit when:** the adapter cannot express a required terminal state without + re-implementing the agent loop; SmolAgents is abandoned or its license changes; + or durable, resumable execution becomes a product requirement that a separate + ADR approves. + +### B. Expand multi-agent orchestration first — **Rejected** + +Make the problem "more agents": add worker roles, recipes, hierarchical +coordinators, reflection loops, or persistent memory before fixing the runtime. + +- **Why it is attractive:** specialized workers look like a natural fit for + research, commerce, local, and academic sub-tasks, and the recipe catalog + already models K workers. +- **Why it is rejected:** + - There is no evidence of uplift. No single-agent baseline or paired + evaluation exists, so it cannot be shown that existing recipes outperform one + well-instrumented agent on quality, latency, or cost. + - More workers multiply today's defects: unenforced required workers, unused + `max_workers`, worker failures returned as evidence, abandoned threads after + timeout, and shared mutable run state. + - Each worker adds provider calls and cost that the project cannot yet + attribute, conflicting with the product principle that provider cost and + usage must not be hidden + ([PRODUCT_SENSE.md](../PRODUCT_SENSE.md#L15-L20)). + - Multi-agent handoffs add sources of nondeterminism that require trajectory + evaluation to manage, and that evaluation does not exist yet. +- **Revisit when:** RTM-4 baselines show a recipe produces measurable, repeated + uplift over a same-model single-agent configuration within agreed latency and + cost guardrails. Expansion then proceeds recipe by recipe. + +### C. Keep the status quo with targeted fixes — **Rejected** + +Patch individual bugs (pass `max_steps`, fix the timeout message, forward +`--workers`) without a shared layer. + +- **Why it is attractive:** smallest immediate change. +- **Why it is rejected:** each path would keep its own failure, timeout, and + retry semantics, so fixes would drift again and stay unobservable. The + individual fixes are still valuable and will be delivered as part of the + layer's characterization and migration phases. +- **Evidence since drafting:** upstream PR #7 applied targeted fixes. It made + `InternetAgent` forward `max_steps` and planning and fixed several local + contracts. Lifecycle semantics stayed out of scope. String-encoded failures, + the non-stopping timeout and its message, unenforced required workers, the + unforwarded `--workers` option, and shared run state all remain. Upstream + lists lifecycle and cancellation as follow-ups that need design + ([CODEBASE_STATUS.md](../CODEBASE_STATUS.md#L28-L33)). + +## Consequences + +### Positive + +- One run contract and failure model across single-agent, Code Mode, and + recipe-based execution. +- Automation can rely on typed status and exit codes instead of parsing strings. +- Reliability features come mostly from existing, maintained SmolAgents hooks. +- Structured events and manifests make runs reproducible, auditable, and usable + as evaluation inputs. +- Framework upgrades, or a future replacement, are confined to one adapter. +- Multi-agent investment becomes evidence-driven. + +### Negative and costs + +- A new `runtime/` layer and contracts to maintain, plus legacy serializers for + the duration of the migration. +- Two execution paths coexist until rollout completes, increasing test surface. +- Cooperative cancellation stops only between steps and at tool deadlines. + `asyncio.to_thread()` cannot forcibly stop running Python or an in-flight + provider call; hard stops for untrusted code require a separately reviewed + process or container boundary. +- Tighter SmolAgents version pinning requires deliberate upgrade work. +- Recipe expansion is deliberately slowed until evaluations exist. + +### Neutral + +- Prompt-defined behavior stays prompt-defined; this decision does not move + research judgment into code. +- Security posture is unchanged: URL validation, code execution limits, MCP trust + settings, browser side-effect controls, and secret redaction remain + deterministic and are not relaxed. + +## Compliance and Verification + +This decision is followed when: + +- No module outside `agentic_internet/runtime/` consumes SmolAgents run-lifecycle + APIs (`RunResult`, `step_callbacks`, `final_answer_checks`, + `managed_agents`) once RTM-2 lands. +- Characterization tests from RTM-0 pin legacy return shapes and CLI behavior, + and they continue to pass with the legacy and new backends. +- New execution paths return `RunResult` internally, and max-steps exhaustion is + never reported as success. +- CI installs from the lockfile, and SmolAgents upgrades pass adapter contract + tests before merge. +- No new recipe or worker role merges without a paired single- versus + multi-agent evaluation report. + +## References + +- Roadmap: [Evaluation-Driven Agent Runtime Modernization](../exec-plans/active/2026-12-04-evaluation-driven-agent-runtime.md) +- Architecture: [ARCHITECTURE.md](../ARCHITECTURE.md), [DESIGN.md](../DESIGN.md), + [RELIABILITY.md](../RELIABILITY.md), [SECURITY.md](../SECURITY.md) +- [SmolAgents agent reference](https://huggingface.co/docs/smolagents/en/reference/agents) +- [SmolAgents guided tour](https://huggingface.co/docs/smolagents/main/guided_tour) +- [SmolAgents multi-agent example](https://huggingface.co/docs/smolagents/en/examples/multiagents) +- [Evaluate agent workflows](https://developers.openai.com/api/docs/guides/agent-evals) +- [Evaluation best practices](https://developers.openai.com/api/docs/guides/evaluation-best-practices) diff --git a/docs/design-docs/index.md b/docs/design-docs/index.md index 4d83288..50678d9 100644 --- a/docs/design-docs/index.md +++ b/docs/design-docs/index.md @@ -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 diff --git a/docs/exec-plans/active/2026-12-04-evaluation-driven-agent-runtime.md b/docs/exec-plans/active/2026-12-04-evaluation-driven-agent-runtime.md new file mode 100644 index 0000000..bfb67e0 --- /dev/null +++ b/docs/exec-plans/active/2026-12-04-evaluation-driven-agent-runtime.md @@ -0,0 +1,645 @@ +--- +title: "Evaluation-Driven Agent Runtime Modernization" +area: "Agent execution, orchestration, observability, and evaluation" +status: proposed +risk: high +created: 2026-12-04 +updated: 2026-12-04 +author: agent +base_commit: bb2dcd0 +--- + +# Plan: Evaluation-Driven Agent Runtime Modernization + +## Intent + +Replace the repository's divergent experimental execution paths with one +compatible, observable, evaluation-driven runtime. Keep SmolAgents as the +execution engine, but put a small project-owned control plane around it so every +single-agent and multi-agent run has the same lifecycle, budgets, failure +semantics, trace format, and regression harness. + +This is a strangler migration, not a rewrite. Existing public imports and CLI +commands continue to work while new internals are introduced behind adapters. +Multi-agent orchestration must demonstrate a measured benefit over a +single-agent baseline before it is expanded. + +## Current Evidence + +This plan was written against `bb2dcd0`. Its evidence was re-verified on +2026-12-04 at merge commit `55566a7`, after merging upstream PR #7 +(stabilization baseline, upstream plans 001–005; see +[PLANS.md](../../PLANS.md#L30-L38)). File paths in the table are relative to +`agentic_internet/` unless they start with `tests/`, `pyproject.toml`, or +`.github/`. + +Pre-merge baseline measured at `bb2dcd0`: + +- `198 passed` in 3.75 seconds; total line coverage is 51%. +- Ruff lint/format and mypy pass. +- The golden-principles check failed only because `docs/exec-plans/active/` did + not exist. This plan and upstream Plan 001 (`.gitkeep`) resolved that. +- Installed SmolAgents was 1.21.2, while `pyproject.toml` permitted any version + from 0.1.0 onward. +- There is no first-party `evals/` or `experiments/` tree. This is still true + at `55566a7`. + +Post-merge state at `55566a7`: + +- The SmolAgents floor is `smolagents[mcp]>=1.21.2` (RTM-0 slice 3), and + `uv.lock` still resolves 1.21.2. The installed API still provides + `max_steps`, `planning_interval`, `step_callbacks`, `final_answer_checks`, + `managed_agents`, `name`/`description`/`provide_run_summary`, + `return_full_result`, and `RunResult(output, state, messages, token_usage, + timing)`. +- LiteLLM is 1.108.3 (upstream Plan 005). +- Post-merge gates at `1e52135` (see the Progress Log): 325 passed and 1 + opt-in skip (upstream `master` at `589a0c1`: 250 passed, 1 skip), total line + coverage 72% (`master`: 65%), Ruff, mypy, lockfile, and golden principles + clean. + +| Evidence | Why it matters | +|----------|----------------| +| `agents/internet_agent.py:66,93-126` | **Fixed upstream in PR #7 (Plan 001).** Both `ToolCallingAgent` and `CodeAgent` now receive `max_steps=max_iterations` and `planning_interval` (1 or `None`), and `tools=[]` stays empty. What remains for this plan: max-steps exhaustion is still returned as an ordinary answer. | +| `agents/multi_model/system.py:210-233,403-421` | Multi-model run limits are not policy-driven. `CodeAgent` workers get a hardcoded `max_steps=20`, `ToolCallingAgent` workers get the SmolAgents default, and only the orchestrator uses `recipe.max_steps`. | +| `agents/internet_agent.py:177-191` and `agents/basic_agent.py:23-66` | Model and execution failures become strings, so callers cannot reliably distinguish success, model failure, tool failure, or partial completion. | +| `agents/multi_model/system.py:423-446` | A timeout wraps `asyncio.to_thread`; timing out the await does not kill the underlying thread. The timeout error also interpolates `timeout` instead of `effective_timeout`, so it reports `None` when a library caller relies on the recipe timeout. The `multi` CLI passes `recipe.timeout_seconds` explicitly (`cli.py:222-229`). | +| `agents/multi_model/model_manager.py:19-186` | **Partially addressed upstream (Plan 002).** Explicit central aliases now resolve exactly first (`79-92`). `ModelManager` still eagerly constructs a hardcoded provider suite (`19-72`). It also keeps legacy name/role mappings and fallback (`94-186`) separate from `config/settings.py` and `utils/model_utils.py:66-128`. | +| `agents/multi_model/tools.py:30-107`, `agents/multi_model/system.py:44-73,304-306` | Search tools hold a back-reference to the whole system and mutate shared memory and current-task state. A new run overwrites that state and uses second-resolution IDs, so overlapping runs can contaminate each other's metrics and traces. | +| `agents/use_cases.py:20-21,40-44`, `agents/multi_model/system.py:136-138,246-247,326-330`, and `cli.py:174-229,258-293` | Required-worker degradation, per-worker limits, and routing policy are not enforced. `routing_policy` appears only in the orchestrator prompt and the use-case summary. The `multi` command's `--workers` value is never forwarded, and the `orchestrate` command's `--workers` list is only echoed and saved. Declared controls can differ from actual execution and spend. | +| `agents/multi_model/tools.py:422-441` and `agents/multi_model/system.py:123-247` | A custom `AgentTool` reimplements delegation even though SmolAgents 1.21.2 supports managed agents, full run results, step callbacks, and final-answer checks. Failures are again converted to text. | +| `agents/multi_model/context.py:12-40` | Context "compression" replaces content with a count marker and resets an estimated token count; it does not produce a faithful summary or a resumable checkpoint. | +| `agents/search_orchestrator.py:122-406` | A separate orchestrator implements its own concurrency, prompt routing, history, result aggregation, and an async wrapper marked experimental. | +| `agents/use_cases.py:32-67` and `agents/orchestration_runtime.py:27-123` | Typed recipes and tool resolution are a good foundation, but they describe configuration rather than a shared execution lifecycle. | +| `tests/test_orchestration_runtime.py` and `tests/test_search_orchestrator.py` | Existing tests pin helper and procedure behavior with fakes; there is no versioned outcome dataset, trajectory replay, model/prompt comparison, or cost/latency regression report. | +| `pyproject.toml:11-35` and `.github/workflows/ci.yml:16-27` | **Done.** RTM-0 slice 3 raised the SmolAgents floor (line 12) and made CI install with `uv sync --locked` (line 27). Upstream Plan 005 upgraded LiteLLM to `>=1.108.3,<2` (line 31), pinned setup-uv v10.3.3 by full SHA, and pinned uv 0.13.7 (lines 17-19). Other direct dependencies keep broad floors, so future upgrades remain intentional lockfile changes. | + +## Design Decisions + +1. **One control plane, multiple agent strategies.** `ToolCallingAgent`, + `CodeAgent`, `BasicAgent`, and recipe-based teams are adapters behind one run + contract. Do not build a second ReAct loop. +2. **Deterministic control plane; probabilistic data plane.** Lifecycle, + budgets, validation, retries, approvals, and output schemas stay in typed + Python. Research judgment, source selection, and synthesis stay in prompts. +3. **Native SmolAgents first.** Use `max_steps`, `planning_interval`, + `step_callbacks`, `managed_agents`, `final_answer_checks`, + `return_full_result`, and `RunResult` where they fit. Add an adapter rather + than depending on these APIs throughout the codebase. +4. **Traces before memory; evals before orchestration.** Do not add persistent + memory, self-reflection, or more workers until sanitized traces and baseline + evals show a concrete need. +5. **Outcome tests over exact trajectories.** Assert task outcomes, critical + safety/tool constraints, citations, and terminal state. Permit different + valid reasoning paths. +6. **Security remains deterministic.** Do not relax URL validation, code + execution boundaries, MCP trust settings, browser side-effect controls, or + secret redaction in the name of prompt-native flexibility. +7. **No new framework by default.** A new durable-execution, tracing, or eval + dependency requires a separate ADR and explicit human approval after a + spike demonstrates that the standard library plus current dependencies is + insufficient. +8. **Run state is isolated and bounded.** Each run and attempt gets a unique + context passed explicitly to tools and workers. No tool may mutate a shared + orchestrator's current-run pointer; process-lifetime history must be bounded. +9. **Declared recipe controls are enforceable.** Deterministic fan-out/join is + runner code. For coordinator-delegated recipes, the model chooses among legal + worker actions while the runner enforces required capabilities, per-worker + limits, concurrency, degradation, and budget accounting. + +## Target Architecture + +```mermaid +flowchart LR + User["CLI or library caller"] --> Facade["Existing public facades"] + Facade --> Adapter["Compatibility adapter"] + Adapter --> Runner["AgentRunner"] + Runner --> Policy["RuntimePolicy and budgets"] + Policy --> Engine["SmolAgents adapter"] + Engine --> Models["Lazy model registry"] + Engine --> Tools["Tool registry and capability metadata"] + Engine --> Result["Typed RunResult"] + Runner --> Events["RunEvent stream"] + Events --> Sink["Null, memory, or redacted JSONL sink"] + Events --> Eval["Offline trajectory replay and eval runner"] + Dataset["Versioned eval datasets"] --> Eval + Eval --> Report["Quality, safety, latency, token and cost report"] +``` + +The new `runtime/` layer may import tool contracts and SmolAgents, but tools +must not import runtime services. CLI modules render results and own process +exit codes; they do not infer failure by parsing output strings. + +## Acceptance Criteria + +- [ ] A typed `RunRequest`, `RuntimePolicy`, `RunResult`, `WorkerResult`, + `RunEvent`, `RunManifest`, and terminal-status enum cover success, + degraded/partial completion, max steps, failure, timeout, cancellation, + and blocked/approval-required states. +- [ ] All new execution paths return `RunResult` internally. Existing + `InternetAgent.run() -> str`, research dictionaries, search result + dictionaries, multi-model JSON output, public imports, and CLI output + remain compatible through explicit serializers until a separate + deprecation/release plan. +- [ ] `max_iterations` and planning configuration have consistent, tested + behavior for both `ToolCallingAgent` and `CodeAgent`; max-steps exhaustion + is not reported as success. (`InternetAgent` forwarding was delivered + upstream in PR #7 and is covered by `tests/test_internet_agent.py`; + recipe-driven worker limits and the max-steps terminal state remain.) +- [ ] Timeout behavior is truthful: per-tool deadlines and cooperative + cancellation at step boundaries are tested, and documentation states + that cancelling `asyncio.to_thread()` does not forcibly stop running + Python or an external provider call. +- [ ] Every configured run emits structured, correlated events containing + run/step IDs, status, duration, requested and effective model/provider, + tool outcome, token usage when available, recipe/prompt versions, and a + trace reference. Raw prompts, scraped content, browser data, and secrets + are excluded by default; redaction tests pass. +- [ ] Provider fallback records the requested model, effective model, and + reason. Explicit model selection never silently becomes a different + provider in the new runtime. The new CLI backend maps failed/timed-out + runs to nonzero exit codes; any change from legacy exit behavior is + documented and enabled only at the rollout boundary. +- [ ] Concurrent fake runs on one system cannot overwrite each other's context, + metrics, history, or events. Run/attempt IDs are collision-resistant and + retained history is bounded. +- [ ] Recipe preparation reports missing required capabilities explicitly; + `parallel_then_synthesize` has deterministic fan-out/join, per-worker + limits, and tested `max_workers` enforcement, including the existing CLI + `--workers` option. +- [ ] A versioned seed evaluation suite contains at least 12 cases: normal and + adversarial cases for each built-in recipe, plus timeout, provider/tool + failure, prompt-injection content, and max-steps cases. Offline replay + runs without credentials on every PR; live evals are opt-in and budgeted. +- [ ] An aggregate baseline compares a single agent against each applicable + multi-agent recipe using the same model where possible. Reports include + task success, evidence/citation checks, critical tool constraints, + latency, steps, tokens, and cost labeled as provider-reported or estimated. + Multi-agent expansion requires documented uplift, not intuition. +- [ ] Every experiment has a reproducible manifest with git SHA; hashes of the + lockfile, configuration, prompts, datasets, and judge rubric; actual + model/provider/fallback chain; sampling settings; and dependency versions. +- [ ] Deterministic tests isolate dotenv/environment state and outbound network + access. A real local MCP stdio or HTTP fixture covers process lifecycle + without external credentials; external-service tests use `integration`. +- [ ] Model construction is lazy and uses one configuration-driven registry; + `ModelManager` and `initialize_model()` become adapters rather than + competing sources of model truth. (Upstream Plan 002 added exact + central-alias resolution in `ModelManager`; eager construction and the + legacy name/role mappings remain.) +- [ ] CI uses the lockfile, deterministic offline tests stay credential-free, + live tests are marked `integration`, and existing quality gates pass. + (Lockfile install is done by RTM-0 slice 3. The setup-uv SHA pin, uv + 0.13.7, and the LiteLLM 1.108.3 upgrade are done upstream in Plan 005.) +- [ ] `ARCHITECTURE.md`, `DESIGN.md`, `RELIABILITY.md`, `SECURITY.md`, + `QUALITY_SCORE.md`, README usage, and this plan are updated as phases + land. Any new dependency or public interface change stops for review. + +## Non-Goals + +- No big-bang rewrite, framework migration, hosted control plane, database, + distributed queue, UI, billing, scheduling, or SaaS authentication. +- No persistent long-term memory or self-modifying prompts/code in this plan. +- No always-on evaluator-optimizer/reflection loop. A bounded refinement loop + is a later experiment only if evals show benefit that justifies its cost. +- No new observability vendor or required OpenTelemetry/Langfuse dependency. + The event schema should permit a later adapter without committing to one. +- No autonomous live evals on untrusted pull requests and no credential + requirement for ordinary unit tests. +- No removal of sandboxing, input validation, approval requirements, or MCP + trust controls; no claim that local Python execution is a security boundary. +- No immediate deletion of legacy public classes. Internal removal happens only + after parity, migration documentation, and a separate deprecation decision. + +## Proposed Contracts + +Names are illustrative and must be validated in RTM-1 before implementation: + +- `RunRequest`: task, recipe ID, model selection/overrides, runtime policy, + optional conversation/run ID, and caller metadata. +- `RuntimePolicy`: max steps, timeout, planning interval, transient retry + policy, optional token/cost budget, tool approval policy, and fallback mode. +- `RunResult`: run ID, status, output, typed failure, step count, duration, + requested/effective model and provider, fallback/degradation details, token + usage, recipe/prompt versions, and trace reference. `WorkerResult` carries the + equivalent worker/attempt outcome so failed workers cannot become evidence. +- `RunManifest`: git SHA, lock/config/prompt/dataset/rubric hashes, dependency + versions, sampling settings, resolved model attempts, and reported versus + estimated usage/cost. Raw user content is not required for reproducibility. +- `RunEvent`: schema version, event type, run/step/parent/attempt IDs, timestamp, + duration, safe attributes, and typed error category. +- `RunContext`: unique run/attempt IDs, deadline, cancellation token, bounded + per-run state, and event sink passed explicitly to model/tool adapters. +- `ToolOutcome` (in `tools/contracts.py` if needed): structured value or typed + error, retryability, side-effect class, and safe metadata. Adapt existing + string-returning tools at the runtime boundary before migrating tool APIs. + +Retries are limited to classified transient failures with bounded exponential +backoff and jitter. Never automatically retry non-idempotent browser/code/MCP +side effects. Final-answer validation uses deterministic checks first; an +LLM-as-judge is informational until calibrated against human labels. + +## Task Graph + +| ID | Task | Depends On | Status | +|----|------|------------|--------| +| RTM-0 | Characterization tests, ADR, dependency/API baseline | none | implemented; ADR pending approval | +| RTM-1 | Typed run contracts and compatibility serializers | RTM-0 | proposed | +| RTM-2 | SmolAgents adapter, lifecycle, budgets, failure policy | RTM-1 | proposed | +| RTM-3 | Structured events, redaction, memory/JSONL sinks | RTM-1 | proposed | +| RTM-4 | Eval datasets, deterministic assertions, replay runner | RTM-2, RTM-3 | proposed | +| RTM-5 | Migrate single-agent and chat/research paths | RTM-2, RTM-3 | proposed | +| RTM-6 | Lazy model registry and native managed-agent migration | RTM-4, RTM-5 | proposed | +| RTM-7 | Legacy orchestrator adapters and deprecations | RTM-5 | proposed | +| RTM-8 | CI, locked dependencies, docs, staged rollout | RTM-4 through RTM-7 | proposed | + +## Execution Packaging + +This document is a program roadmap, not one implementation branch or PR. Only +RTM-0 is immediately executable. Its work should land as separate focused +changes for (1) characterization tests and the ADR, (2) hermetic/local MCP test +infrastructure, and (3) dependency/CI immutability. Do not combine those with +runtime refactoring. + +Before each later phase, create a focused child exec-plan linked from this file. +The child plan must include the actual post-dependency API signatures, current +file excerpts, exact files in/out of scope, effort estimate, acceptance tests, +and rollback. Update this roadmap's task status and progress log when that child +plan is approved and when it completes. RTM-2 and RTM-3 may share contracts but +should land separately; RTM-6 must not be bundled with RTM-5. + +## Execution Phases + +### RTM-0 — Freeze behavior and record decisions + +Scope: + +- Add characterization tests for `InternetAgent` construction/run behavior, + default and code-agent max steps, planning configuration, error returns, + chat reset behavior, recipe timeout behavior, and CLI exit/output contracts. +- Add failure tests for model fallback, tool failure, max steps, timeout, + required-worker degradation, concurrent run isolation, and CLI `--workers` + forwarding. Use fakes; do not add live provider calls to unit tests. +- Add shared test fixtures that disable dotenv loading and clear provider/MCP + variables before package imports, construct fresh settings per case, and + block outbound sockets in deterministic lanes. Add a real local MCP stdio or + HTTP server fixture with strict teardown; mark it `integration` if it cannot + run reliably in the default PR lane. +- Record an ADR for the control-plane/data-plane split, compatibility policy, + and decision to keep SmolAgents behind an adapter. Drafted as + [Keep SmolAgents behind a reliability layer](../../design-docs/2026-12-04-smolagents-behind-reliability-layer.md) + (status: proposed, pending maintainer approval). +- Replace deprecated class-based Pydantic `Config` usage with `ConfigDict` as a + small isolated baseline cleanup. +- Set the SmolAgents floor to the oldest version that supports the APIs used by + the adapter, currently verified against 1.21.2, and use a compatible upper + bound only if the project adopts that policy consistently. Run the full + migration tests before changing `pyproject.toml`/`uv.lock`. +- Change CI installation to `uv sync --locked --all-extras --dev` after proving + `uv sync --locked --dry-run --all-extras --dev` is clean. Pin third-party CI + actions, including the secret scanner, to reviewed full commit SHAs. + +Expected files: `tests/test_internet_agent.py`, `tests/conftest.py`, focused +runtime/CLI/MCP tests, `docs/design-docs/`, `pyproject.toml`, `uv.lock`, and +`.github/workflows/ci.yml`. + +Gate: all pre-existing behavior is pinned; any intentionally changed behavior +is called out in the ADR rather than hidden in a refactor. + +Rollback: revert only the dependency/CI commit or characterization commit. No +production runtime path has changed yet. + +Post-merge note (`55566a7`): upstream PR #7 also replaced class-based Pydantic +`Config` with `ConfigDict`. It made `InternetAgent` forward `max_steps` and +`planning_interval` to both agent types and honor `tools=[]`. It also replaced +the setup-uv pin with v10.3.3 and uv 0.13.7. RTM-0 characterization tests that +pinned the pre-merge `InternetAgent` behavior (now in +`tests/test_internet_agent_characterization.py`; upstream owns +`tests/test_internet_agent.py`) were re-pinned to the fixed behavior in +`1404242`, and the multi-model tests were retargeted to +`agents/multi_model/system.py`. The behaviors that the other RTM-0 +characterization tests pin are still present in the merged code: the timeout +message, string failures, skipped required workers, the unforwarded +`--workers`, and shared run state. + +### RTM-1 — Introduce typed run and event contracts + +Scope: + +- Add `agentic_internet/runtime/contracts.py` and + `agentic_internet/runtime/events.py` with schema-versioned Pydantic models. +- Add `runtime/serializers.py` for legacy string/dict/JSON adaptation. +- Add `runtime/sinks.py` with null and in-memory sinks first; add JSONL after + redaction and path handling tests. +- Keep models, agents, tools, and CLI free to depend on contracts, but avoid + circular imports back into concrete agents or CLI modules. +- Test every terminal state and serializer, timestamp/ID uniqueness, safe + metadata serialization, and schema-version rejection behavior. + +Gate: contract unit tests pass without initializing a provider or creating a +cache directory as an import side effect. + +Rollback: remove unused new modules; no caller has been migrated. + +### RTM-2 — Build the SmolAgents execution adapter + +Scope: + +- Add `runtime/smolagents_adapter.py` and `runtime/runner.py`. +- Map SmolAgents `RunResult.state`, token usage, timing, steps, and final answer + into the project contract. Use `final_answer_checks` for deterministic output + contracts and `step_callbacks` for events/cancellation checks. +- Apply max steps and planning consistently. Map max-steps exhaustion to + `partial`, not success. +- Implement transient-only retry and explicit fallback policy in one place. + Preserve legacy fallback behavior only inside legacy serializers/adapters. +- Create collision-resistant run/attempt IDs and pass `RunContext` explicitly. + Remove tool back-references to the orchestrator's mutable current-run state + on the new path; bound any retained history and attribute every event to a + run and attempt. +- Implement timeout at the runner boundary plus tool-specific deadlines where + supported. Add cooperative cancellation between steps; do not claim hard + thread/process termination. Propagate browser cancellation where the SDK + supports it, and route untrusted arbitrary code through a separately reviewed + stoppable process/container boundary before promising hard timeouts. +- Use a fake SmolAgents-compatible agent/model for unit tests. Add a small + contract test against the installed SmolAgents version that does not call a + live model. + +Gate: tests cover success, final-answer rejection then recovery, max steps, +model error, tool error, retry exhausted, fallback used, timeout, cancellation, +event ordering, and two overlapping runs with isolated state/events. +`InternetAgent` still uses the old path until RTM-5. + +Rollback: disable the new runner via construction-time selection; old execution +code remains untouched. + +### RTM-3 — Add safe, useful observability + +Scope: + +- Emit run, step, model, tool, approval, and terminal events from the adapter. +- Default library callers to no persistence; permit in-memory events for evals + and explicit redacted JSONL tracing for CLI/debugging. +- Store local traces under the configured cache directory only when requested; + never write raw traces into the repository by default. +- Add tests with fake API-key-like values, cookies, authorization headers, + prompt-injection text, and large payloads to prove redaction and size limits. +- Document event schema versioning and optional future OpenTelemetry mapping; + do not add that dependency here. + +Gate: a failed fake run can be diagnosed from events alone without raw user +content, and no tested secret marker appears in serialized output. + +Rollback: select the null sink; the runner remains functional without tracing. + +### RTM-4 — Establish evaluation-driven development + +Scope: + +- Add `agentic_internet/evaluation/` for dataset loading, deterministic + assertions, trajectory replay, aggregation, and JSON/Markdown reports. +- Add `evals/datasets/`, `evals/fixtures/`, and `evals/README.md`. Use JSON or + JSONL for the initial dataset format to avoid a YAML dependency. Give every + case a stable ID, tags, and `as_of` date; keep immutable sanitized snapshots + separate from live datasets. +- Create at least 12 seed cases across `research`, + `technical_due_diligence`, and `market_intelligence`, including ambiguous + input, missing tools, provider failure, timeout, max steps, and untrusted + instructions embedded in retrieved content. +- Separate deterministic assertions (status, schema, allowed/forbidden tools, + argument constraints, citation references to fixture evidence, no forbidden + side effect) from rubric judgments (accuracy, completeness, evidence quality, + clarity). +- Replay sanitized recorded model/tool responses for PR tests. Keep live model + runs manual or scheduled, marked `integration`, with explicit case, step, + token/cost, and time budgets. For stochastic live comparisons, use fixed + sampling/provider-supported seeds where available, 3-5 repetitions, paired + per-case results, and distributions rather than one average from one run. +- Compare single-agent and multi-agent configurations on identical cases. + Keep model constant when measuring orchestration uplift; then evaluate model + role assignments separately. Each experiment states a hypothesis, primary + metric, guardrails, and budget, and changes one variable at a time. +- Write a run manifest with code/config/prompt/dataset/rubric identities and + actual model/provider/fallback usage. Commit aggregate baseline summaries; + retain raw redacted traces locally with bounded retention, not in git. +- Start any LLM judge in informational mode. Promote it to a blocking quality + gate only after a documented human-agreement/calibration check. +- Convert every discovered production/live failure into a sanitized regression + case before changing prompts, routing, or tools. + +Gate: offline evals are repeatable without network or keys; two runs over the +same fixtures produce equivalent aggregate assertions. A sample report shows +quality, failures, latency, steps, tokens, and cost where available. + +Rollback: remove the eval job from required CI while retaining unit tests; +runtime rollout is blocked if its baseline comparison is removed. + +### RTM-5 — Migrate single-agent, research, and chat paths + +Scope: + +- Route `InternetAgent` and `ResearchAgent` through `AgentRunner` behind their + existing public methods; expose the typed result through a new additive API + rather than changing `run()`'s return type. +- Make chat reset/continuation explicit. The current `chat_history` list is not + a conversation model; either pass SmolAgents memory intentionally with + `reset=False` or document stateless turns. Test the chosen behavior. +- Move research depth prompts and output contracts into versioned prompt + definitions without changing user-facing depth options. +- Add capability/output checks for research citations and unsupported depth. +- Update specialized agents to inherit the same runtime behavior instead of + creating their own execution policy. + +Gate: legacy return shapes and CLI output match RTM-0 characterization tests; +new typed API passes runtime tests; offline research evals do not regress. + +Rollback: select the legacy backend for these facades. No signature changes are +required for rollback. + +### RTM-6 — Migrate model and multi-model orchestration + +Scope: + +- Extract a lazy, configuration-driven model registry used by both single and + multi-model paths. Preserve model aliases and provider-specific API handling. +- Replace hardcoded capability substring checks with explicit recipe/runtime + capability policy and a documented fallback for unknown models. +- Adapt `MultiModelSerpAPISystem` to the runner. Prefer SmolAgents native + `managed_agents` with `name`, `description`, and run summaries over the custom + `AgentTool` when parity tests show equivalent behavior. +- Keep `UseCaseRecipe` as the declarative source for worker roles, tool bundles, + limits, and output contracts; add prompt/recipe version fields. Compile + `parallel_then_synthesize` into deterministic runner fan-out/join with bounded + `max_workers`. For `coordinator_delegates`, expose only legal typed worker + actions and enforce required-worker degradation, per-worker limits, attempts, + and budgets in the runner rather than relying on prompt instructions. +- Build on the existing package split. Upstream Plan 004 already decomposed + `multi_model_serpapi.py` into `agents/multi_model/` and kept the original + module as a thin compatibility re-export: + - `model_manager.py` + - `schemas.py` + - `context.py` + - `tools.py` + - `system.py` + + Put the model-registry adapter behind `model_manager.py`, runner integration + in `system.py`, run-scoped context policy in `context.py`, and typed + tool/worker outcomes in `tools.py`. Add no logic to the compatibility module. + Keep it until a deliberate major-version migration. See the + [completed split plan](../completed/2026-11-09-split-multi-model.md). +- Replace marker-only context compression with bounded, explicit context policy. + Do not call it a checkpoint or summary unless content is actually preserved + or summarized and tested. +- Run the RTM-4 single-vs-multi comparison before enabling new recipes or more + workers. Record quality/latency/cost tradeoffs in the plan. + +Gate: recipe construction, delegation, fallback, max steps, timeout, event +correlation, legacy JSON serialization, and offline outcome evals pass. +Original-path imports from `agentic_internet.agents.multi_model_serpapi` keep +object identity with `agentic_internet.agents.multi_model` +(`tests/test_multi_model_package.py`). New behavior lives in the owning +package modules, not in the compatibility shim. + +Rollback: use the legacy multi-model facade and model registry. Keep new and +old paths isolated so rollback does not affect single-agent execution. + +### RTM-7 — Converge legacy orchestration and lifecycle policy + +Scope: + +- Adapt `SearchOrchestrator` and `BasicAgent` to shared contracts rather than + maintaining independent failure/concurrency policies. +- Decide from usage and eval evidence whether `SearchOrchestrator` remains a + supported facade, becomes a recipe, or enters deprecation. Do not delete it + in this plan. +- Define approval hooks for browser/code/MCP side effects and blocked/partial + outcomes. Security-sensitive behavior changes require focused review. +- Document checkpoint/resume as out of scope unless a separate durable execution + ADR is approved; event logs alone are not resumable checkpoints. + +Gate: no legacy path silently bypasses the shared failure and event policy; +public behavior remains pinned by tests. + +Rollback: retain legacy facade implementations while sharing only safe contract +utilities. + +### RTM-8 — Release behind staged selection and update docs + +Scope: + +- Add a centralized runtime selection setting, defaulting to legacy during + migration and allowing explicit opt-in to the new runner per phase. +- Switch defaults only after offline parity plus a reviewed live eval report. + Keep a one-release rollback switch before considering legacy deletion. +- Build on what is already in place rather than redoing it. RTM-0 slice 3 added + locked CI installs and SHA-pinned actions. Upstream Plan 005 pinned setup-uv + v10.3.3 by full SHA with uv 0.13.7, upgraded LiteLLM to 1.108.3, and added a + CI-pin regression test (`tests/test_ci_security.py`). +- Split CI into hermetic unit, deterministic trajectory, local-process + integration, provider-contract replay, and opt-in/scheduled live eval lanes. + Add package-build/CLI smoke checks and a Python 3.11 plus newest-supported + version matrix after dependency compatibility is proven. Do not expose + provider keys to untrusted PR code. +- Update architecture Mermaid, runtime configuration, tracing/eval instructions, + failure policy, security classifications, migration guide, and quality scores + with measured evidence. +- File follow-up beads for deferred durable execution, OpenTelemetry export, + persistent memory, reflection loops, and legacy removal rather than expanding + this plan. + +Gate: full verification below passes, rollout/rollback instructions have been + exercised with fake providers, and documentation matches the released path. + +Rollback: set the centralized runtime selection back to `legacy`, disable live + eval schedules, and revert only the failing phase. Preserve traces/eval reports + for diagnosis. + +## Verification + +Baseline and final local gates: + +```bash +uv sync --locked --dry-run --all-extras --dev +uv run --frozen ruff check agentic_internet tests +uv run --frozen ruff format --check agentic_internet tests +uv run --frozen mypy agentic_internet +uv run --frozen pytest -q +uv run --frozen pytest -q --cov=agentic_internet --cov-report=term:skip-covered +python3 .opencode/tools/golden_principles.py +``` + +Planned focused gates (paths/commands become valid in their respective phases): + +```bash +uv run --frozen pytest -q tests/runtime tests/evaluation tests/test_internet_agent.py +uv run --frozen pytest -q -m "not integration" +uv run --frozen python -m agentic_internet.evaluation run --dataset evals/datasets/seed.json --replay +uv run --frozen python -m agentic_internet.evaluation compare --baseline --candidate +``` + +Do not use total coverage as the sole success metric. Require the specified +failure/lifecycle/eval behavior tests, and do not let total coverage fall below +the measured 51% baseline without an explicit explanation and issue. + +## Stop-and-Report Conditions + +Stop and request human review instead of improvising when: + +- A required SmolAgents API differs from 1.21.2 or the adapter cannot express a + terminal state without reimplementing the agent loop. +- A new external dependency, hosted service, persistent store, or public API + break appears necessary. +- Safe cancellation requires killing threads/processes or changing browser, + code execution, MCP, authentication, or sandbox trust boundaries. +- Live evals need unbudgeted provider spend, raw user data, or credentials in + ordinary PR CI. +- Single-agent and multi-agent results cannot be compared fairly, or the judge + has not been calibrated but a blocking quality decision depends on it. +- Characterization tests reveal that existing CLI/library consumers depend on + error strings that cannot be preserved by the compatibility layer. + +## Maintenance Notes + +- Treat run/event/dataset schemas as versioned public contracts. Add migration + tests before changing them. +- Keep prompt, recipe, model, and evaluator versions in every eval report so a + result can be reproduced and compared. +- Mine sanitized failures into eval cases continuously; do not grow the dataset + only with synthetic happy paths. +- Revisit model role assignments from measured task fit, latency, and cost, + not hardcoded provider reputation. +- Keep deterministic safety and output validation in code even when research + behavior moves into prompts. + +## External Pattern References + +Consulted through Exa on 2026-12-04: + +- [SmolAgents agent reference](https://huggingface.co/docs/smolagents/en/reference/agents): + native managed agents, callbacks, final-answer checks, full run results. +- [SmolAgents guided tour](https://huggingface.co/docs/smolagents/main/guided_tour): + termination and final-answer validation behavior. +- [SmolAgents multi-agent example](https://huggingface.co/docs/smolagents/en/examples/multiagents): + manager/managed-agent composition. +- [Evaluate agent workflows](https://developers.openai.com/api/docs/guides/agent-evals): + inspect traces and convert failures into repeatable evaluations. +- [Evaluation best practices](https://developers.openai.com/api/docs/guides/evaluation-best-practices): + task-specific evals, deterministic and human/model grading, continuous + evaluation, and evidence-driven decisions about multi-agent complexity. + +## Progress Log + +| Date | Update | +|------|--------| +| 2026-12-04 | Proposed a high-risk, staged migration based on repository evidence, 198 passing tests with 51% coverage, installed SmolAgents 1.21.2 API inspection, and Exa research. No source code changed. | +| 2026-12-04 | Incorporated parallel runtime/evaluation audits: per-run state isolation, enforceable recipe scheduling, reproducible manifests, hermetic fixtures, local MCP lifecycle coverage, and immutable CI dependencies. | +| 2026-12-04 | Jev review identified breadth as the main execution risk; limited the immediate slice to RTM-0 and required focused child plans for all later phases. | +| 2026-12-04 | RTM-0: drafted the ADR keeping SmolAgents behind a project-owned reliability layer; framework rewrite, multi-agent-first expansion, and status-quo patching recorded as rejected. Status proposed. | +| 2026-12-04 | RTM-0 slice 3: raised the SmolAgents floor to `smolagents[mcp]>=1.21.2` (only verified version; `uv.lock` requirement metadata only, no resolved versions changed), made CI install with `uv sync --locked`, pinned all workflow actions to full commit SHAs (checkout v4.4.0, setup-uv v5.4.2, setup-python v5.6.0, trufflehog v3.100.1 instead of `main`), and replaced deprecated Pydantic class `Config` with `ConfigDict` in settings (no behavior change; 198 tests pass with no deprecation warnings). | +| 2026-12-04 | RTM-0 slice 1: added fake-only characterization tests (`tests/test_internet_agent.py`, `tests/test_cli_characterization.py`, `tests/test_multi_model_characterization.py`) pinning InternetAgent construction (ToolCallingAgent gets no max_steps/planning; CodeAgent gets max_steps only), error-string returns, stateless chat turns, research shape/depth fallback, CLI exit 0 on error strings, `--output`, unforwarded `--workers`, recipe timeout/use-case passthrough, multi-model no-worker/timeout ("None" seconds) JSON errors, AgentTool failure-as-evidence, unenforced required workers, shared `current_task_context`, and keyless ModelManager. Known defects are tagged with their target phase; no source changed. | +| 2026-12-04 | RTM-0 slice 2: added hermetic test fixtures in `tests/conftest.py` (dotenv loading disabled and provider/MCP env vars cleared before the package import, import-time settings cache dir redirected to a temp dir, stdlib socket guard blocking non-loopback connections and DNS for non-`integration` tests, opt-in `fresh_settings`) plus real local stdio MCP lifecycle tests against `tests/fixtures/mcp_echo_server.py` (start, list, call, shutdown, no leaked process; ~1s, default lane). No source or dependency changes; `--strict-markers` enabled. Direct `Settings()` calls in tests still create `~/.cache/agentic_internet` (source fix deferred to RTM-1). | +| 2026-12-04 | RTM-0 integrated: slices 1-3 merged on `rtm-0/runtime-modernization`; combined suite 273 passed with zero deprecation warnings, Ruff, mypy, lock check, and golden principles clean. Follow-ups filed: ADR approval (agentic-internet-8xh), lazy Settings cache dir to remove the conftest `Path.home` patch (agentic-internet-0m2), CI uv version pin (agentic-internet-5d8), RTM-1 child plan (agentic-internet-0za). | +| 2026-12-04 | Evidence refresh after merging upstream PR #7 (stabilization baseline, plans 001–005) at `55566a7`. Re-verified every code citation in this roadmap and the ADR against the merged code. Citations now point to `agents/multi_model/{system,tools,context,model_manager}.py` and current `cli.py`/`internet_agent.py` lines. `InternetAgent` `max_steps`/`planning_interval` forwarding and `tools=[]` are marked fixed upstream. CI lockfile/uv pin and LiteLLM 1.108.3 are marked done; follow-up agentic-internet-5d8 is superseded by Plan 005. ModelManager duplication is marked partially addressed (Plan 002 exact aliases). These remain current: timeout message uses `timeout`, `wait_for(to_thread)`, string failures, silently skipped required workers, unforwarded `--workers`, and shared `current_task_context`. RTM-6 now builds on the Plan 004 package split instead of splitting the module. SmolAgents 1.21.2 API re-inspected. ADR status stays proposed and its decision is unchanged. Post-merge test count: recorded in the next row. Docs only. | +| 2026-12-04 | Post-merge reconciliation (`1404242`, integrated at `1e52135`). Characterization tests re-pinned: `tests/test_internet_agent.py` from slice 1 is now `tests/test_internet_agent_characterization.py` and asserts the PR #7 fixes (both agent types receive `max_steps` and `planning_interval`; `tools=[]` honored; one duplicate of an upstream test dropped and replaced by a `tools=None` test). Multi-model fakes retargeted to `agents/multi_model/system.py` with guards proving the patches apply; remaining defects keep their RTM-5/RTM-6 tags. Hermetic dotenv check moved from the re-export shim to `multi_model.system`; the flaky loopback test was root-caused to a macOS accept-queue overflow with `listen(1)` and unaccepted connections (reproduced without pytest) and fixed by draining connections. Gates: 325 passed + 1 opt-in skip (`master`: 250 + 1), 324 passed in the not-integration lane, 72% coverage (`master`: 65%), Ruff, ruff format, mypy (30 files), `uv lock --check`, locked dry-run, golden principles clean. | +| 2026-12-04 | PR #8 opened; first CI run passed (locked install, 325 passed + 1 skip). Its log showed the SHA-pinned trufflehog action still pulled `trufflehog:latest`, because the action's `version` input defaults to `latest`. Pinned the scanner image with `version: "3.100.1"` (tag verified on GHCR) so the scanner matches the pinned action. | diff --git a/pyproject.toml b/pyproject.toml index 3cad29d..9b6ddf7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", @@ -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", ] diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..8c8cbb1 --- /dev/null +++ b/tests/conftest.py @@ -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 diff --git a/tests/fixtures/mcp_echo_server.py b/tests/fixtures/mcp_echo_server.py new file mode 100644 index 0000000..a6fdbb6 --- /dev/null +++ b/tests/fixtures/mcp_echo_server.py @@ -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") diff --git a/tests/test_cli_characterization.py b/tests/test_cli_characterization.py new file mode 100644 index 0000000..36f5223 --- /dev/null +++ b/tests/test_cli_characterization.py @@ -0,0 +1,223 @@ +"""Characterization tests for CLI exit/output contracts (RTM-0). + +These pin the CLI's current behavior, including known defects, using fake +agents and a fake multi-model system. No live providers, network, or API keys. +``tests/test_cli_use_cases.py`` already covers use-case and worker-override +routing; this module extends coverage to exit codes, output files, timeout and +``--workers`` forwarding. +""" + +import json +from typing import Any, ClassVar + +import pytest +from typer.testing import CliRunner + +from agentic_internet import cli +from agentic_internet.agents.use_cases import get_use_case_recipe + +runner = CliRunner() + + +class _FakeInternetAgent: + instances: ClassVar[list["_FakeInternetAgent"]] = [] + run_result: ClassVar[str] = "fake answer" + + def __init__(self, **kwargs: Any) -> None: + self.init_kwargs = kwargs + self.run_calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = [] + type(self).instances.append(self) + + def run(self, *args: Any, **kwargs: Any) -> str: + self.run_calls.append((args, kwargs)) + return type(self).run_result + + +class _FakeMultiModelSystem: + instances: ClassVar[list["_FakeMultiModelSystem"]] = [] + result: ClassVar[Any] = "fake multi result" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self.init_args = args + self.init_kwargs = kwargs + self.setup_calls: list[dict[str, Any]] = [] + self.execute_calls: list[dict[str, Any]] = [] + type(self).instances.append(self) + + def setup_use_case_workers(self, *args: Any, **kwargs: Any) -> None: + self.setup_calls.append({"args": args, "kwargs": kwargs}) + + async def execute_multi_model_workflow(self, *args: Any, **kwargs: Any) -> Any: + self.execute_calls.append({"args": args, "kwargs": kwargs}) + return type(self).result + + +@pytest.fixture +def fake_internet_agent(monkeypatch: pytest.MonkeyPatch) -> type[_FakeInternetAgent]: + _FakeInternetAgent.instances = [] + _FakeInternetAgent.run_result = "fake answer" + monkeypatch.setattr("agentic_internet.cli.InternetAgent", _FakeInternetAgent) + return _FakeInternetAgent + + +@pytest.fixture +def fake_multi_system(monkeypatch: pytest.MonkeyPatch) -> type[_FakeMultiModelSystem]: + _FakeMultiModelSystem.instances = [] + _FakeMultiModelSystem.result = "fake multi result" + monkeypatch.delenv("SERPAPI_API_KEY", raising=False) + monkeypatch.setattr("agentic_internet.cli.MultiModelSerpAPISystem", _FakeMultiModelSystem) + return _FakeMultiModelSystem + + +def _contains_value(value: Any, needle: Any) -> bool: + """Recursively check whether ``needle`` appears anywhere inside ``value``.""" + if value == needle and type(value) is type(needle): + return True + if isinstance(value, dict): + return any(_contains_value(k, needle) or _contains_value(v, needle) for k, v in value.items()) + if isinstance(value, list | tuple | set): + return any(_contains_value(item, needle) for item in value) + return False + + +class TestRunCommand: + def test_run_constructs_agent_from_options_and_exits_zero(self, fake_internet_agent): + result = runner.invoke(cli.app, ["run", "what is new", "--model", "m1", "--quiet", "-i", "5"]) + + assert result.exit_code == 0, result.output + agent = fake_internet_agent.instances[0] + assert agent.init_kwargs == {"model_id": "m1", "verbose": False, "max_iterations": 5} + assert agent.run_calls == [(("what is new",), {})] + + def test_run_error_string_still_exits_zero(self, fake_internet_agent): + fake_internet_agent.run_result = "Error executing task: provider exploded" + + result = runner.invoke(cli.app, ["run", "task", "--quiet"]) + + # RTM-characterization: current behavior; expected to change in RTM-5 + # InternetAgent.run() swallows failures into a string, so the CLI reports success. + assert result.exit_code == 0, result.output + + def test_run_output_writes_result_text(self, fake_internet_agent, tmp_path): + fake_internet_agent.run_result = "the final answer" + output = tmp_path / "out.txt" + + result = runner.invoke(cli.app, ["run", "task", "--quiet", "--output", str(output)]) + + assert result.exit_code == 0, result.output + assert output.read_text() == "the final answer" + assert "Output saved to" in result.output + + def test_run_output_writes_error_string_as_if_successful(self, fake_internet_agent, tmp_path): + fake_internet_agent.run_result = "Error executing task: boom" + output = tmp_path / "out.txt" + + result = runner.invoke(cli.app, ["run", "task", "--quiet", "-o", str(output)]) + + # RTM-characterization: current behavior; expected to change in RTM-5 + assert result.exit_code == 0, result.output + assert output.read_text() == "Error executing task: boom" + + def test_run_construction_exception_exits_one(self, monkeypatch): + def broken_agent(**kwargs: Any) -> None: + raise RuntimeError("no model") + + monkeypatch.setattr("agentic_internet.cli.InternetAgent", broken_agent) + + result = runner.invoke(cli.app, ["run", "task", "--quiet"]) + + assert result.exit_code == 1 + assert "no model" in result.output + + +class TestResearchCommand: + def test_invalid_depth_exits_one_before_constructing_agent(self, monkeypatch): + constructed: list[dict[str, Any]] = [] + monkeypatch.setattr("agentic_internet.cli.ResearchAgent", lambda **kwargs: constructed.append(kwargs)) + + result = runner.invoke(cli.app, ["research", "topic", "--depth", "exhaustive"]) + + assert result.exit_code == 1 + assert constructed == [] + + +class TestMultiCommand: + def test_workers_option_is_not_forwarded(self, fake_multi_system): + result = runner.invoke(cli.app, ["multi", "assess", "--workers", "7", "--quiet"]) + + assert result.exit_code == 0, result.output + system = fake_multi_system.instances[0] + recorded = { + "init_args": system.init_args, + "init_kwargs": system.init_kwargs, + "setup_calls": system.setup_calls, + "execute_calls": system.execute_calls, + } + # RTM-characterization: current behavior; expected to change in RTM-6 + # --workers/max_workers is declared on the command but never reaches the system. + assert not _contains_value(recorded, 7) + assert not _contains_value(recorded, "max_workers") + assert system.init_kwargs == {"serpapi_key": None, "context_window_size": 16384} + + def test_multi_passes_recipe_timeout_and_use_case(self, fake_multi_system): + recipe = get_use_case_recipe("market_intelligence") + + result = runner.invoke(cli.app, ["multi", "size the market", "-u", "market_intelligence", "--quiet"]) + + assert result.exit_code == 0, result.output + system = fake_multi_system.instances[0] + assert system.setup_calls == [ + { + "args": (), + "kwargs": { + "use_case_id": "market_intelligence", + "default_model": None, + "worker_model_overrides": {}, + }, + } + ] + assert system.execute_calls == [ + { + "args": ("size the market",), + "kwargs": { + "timeout": recipe.timeout_seconds, + "orchestrator_model": recipe.coordinator_model_role, + "use_case_id": "market_intelligence", + }, + } + ] + + def test_multi_default_use_case_is_research(self, fake_multi_system): + recipe = get_use_case_recipe("research") + + result = runner.invoke(cli.app, ["multi", "task", "--quiet"]) + + assert result.exit_code == 0, result.output + call = fake_multi_system.instances[0].execute_calls[0]["kwargs"] + assert call["use_case_id"] == "research" + assert call["timeout"] == recipe.timeout_seconds + + def test_multi_error_json_result_still_exits_zero(self, fake_multi_system, tmp_path): + error_payload = json.dumps({"error": "No workers available.", "task": "task"}) + fake_multi_system.result = error_payload + output = tmp_path / "multi.json" + + result = runner.invoke(cli.app, ["multi", "task", "--quiet", "--output", str(output)]) + + # RTM-characterization: current behavior; expected to change in RTM-6 + # An error payload from the system is reported as a successful run. + assert result.exit_code == 0, result.output + saved = json.loads(output.read_text()) + assert saved == { + "task": "task", + "models": None, + "use_case": "research", + "worker_model_overrides": {}, + "results": error_payload, + } + + def test_multi_unknown_use_case_exits_one(self, fake_multi_system): + result = runner.invoke(cli.app, ["multi", "task", "-u", "does_not_exist", "--quiet"]) + + assert result.exit_code == 1 + assert fake_multi_system.instances == [] diff --git a/tests/test_hermetic_fixtures.py b/tests/test_hermetic_fixtures.py new file mode 100644 index 0000000..a71bb51 --- /dev/null +++ b/tests/test_hermetic_fixtures.py @@ -0,0 +1,208 @@ +"""Tests for the hermetic fixtures defined in tests/conftest.py.""" + +import importlib +import os +import socket +import tempfile +from pathlib import Path + +import dotenv +import dotenv.main +import pytest + +from tests.conftest import ( + BLOCKED_NETWORK_MESSAGE, + IMPORT_CACHE_DIR, + PACKAGE_IMPORTED_BEFORE_CONFTEST, + PROVIDER_ENV_VARS, + is_isolated_env_var, +) + +SETTINGS_MODULE = importlib.import_module("agentic_internet.config.settings") + + +def _listening_socket(family: int, host: str) -> socket.socket: + server = socket.socket(family, socket.SOCK_STREAM) + server.bind((host, 0)) + server.listen(8) + server.settimeout(2) + return server + + +def _accept_and_close(server: socket.socket) -> None: + """Drain one queued connection so the listen backlog never overflows. + + On macOS a full accept queue answers new SYNs with RST, so unaccepted + connections against a tiny backlog fail at random with ECONNRESET (errno 54). + """ + conn, _ = server.accept() + conn.close() + + +class TestEnvironmentIsolation: + def test_conftest_ran_before_package_import(self): + assert PACKAGE_IMPORTED_BEFORE_CONFTEST is False + + @pytest.mark.parametrize("name", PROVIDER_ENV_VARS) + def test_provider_env_vars_absent(self, name): + assert name not in os.environ + + def test_no_mcp_env_vars(self): + assert [key for key in os.environ if key.startswith("MCP_")] == [] + + def test_shared_settings_have_no_provider_keys(self): + shared = SETTINGS_MODULE.settings + for attr in ( + "openai_api_key", + "anthropic_api_key", + "openrouter_api_key", + "huggingface_token", + "browser_use_api_key", + "exa_api_key", + ): + assert getattr(shared, attr) is None, attr + + def test_isolated_env_var_matcher(self): + assert is_isolated_env_var("OPENAI_API_KEY") + assert is_isolated_env_var("MCP_SERVER_1_TYPE") + assert not is_isolated_env_var("PATH") + + def test_leaked_var_is_cleared_for_next_test_part1(self): + # Simulate a badly behaved test that leaks a credential (dummy value). + os.environ["OPENAI_API_KEY"] = "dummy-leaked-value" + + def test_leaked_var_is_cleared_for_next_test_part2(self): + assert "OPENAI_API_KEY" not in os.environ + + +class TestDotenvDisabled: + def test_load_dotenv_is_noop(self, tmp_path, monkeypatch): + env_file = tmp_path / ".env" + env_file.write_text("HERMETIC_DOTENV_PROBE=loaded\nOPENAI_API_KEY=dummy-from-dotenv\n") + monkeypatch.chdir(tmp_path) + + assert dotenv.load_dotenv() is False + assert dotenv.load_dotenv(env_file) is False + assert dotenv.main.load_dotenv(env_file, override=True) is False + assert "HERMETIC_DOTENV_PROBE" not in os.environ + assert "OPENAI_API_KEY" not in os.environ + + def test_package_modules_bound_noop_loader(self): + assert getattr(SETTINGS_MODULE.load_dotenv, "__hermetic_guard__", False) is True + + def test_multi_model_system_bound_noop_loader(self): + # Since PR #7 the multi_model_serpapi shim no longer calls load_dotenv; the + # module-level call moved to agentic_internet.agents.multi_model.system. + module = importlib.import_module("agentic_internet.agents.multi_model.system") + assert getattr(module.load_dotenv, "__hermetic_guard__", False) is True + + +class TestCacheDirIsolation: + def test_import_time_settings_cache_dir_is_temporary(self): + real_cache = Path.home() / ".cache" / "agentic_internet" + assert real_cache != IMPORT_CACHE_DIR + assert Path(tempfile.gettempdir()).resolve() in IMPORT_CACHE_DIR.resolve().parents + + def test_path_home_restored_after_import(self): + assert Path.home() == Path(os.path.expanduser("~")) + + +class TestNetworkGuard: + def test_non_loopback_connect_blocked(self): + with ( + socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock, + pytest.raises(RuntimeError, match=BLOCKED_NETWORK_MESSAGE), + ): + sock.connect(("203.0.113.10", 80)) # TEST-NET-3, never routed + + def test_non_loopback_connect_ex_blocked(self): + with ( + socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock, + pytest.raises(RuntimeError, match=BLOCKED_NETWORK_MESSAGE), + ): + sock.connect_ex(("203.0.113.10", 80)) + + def test_create_connection_blocked_before_dns(self): + with pytest.raises(RuntimeError, match=BLOCKED_NETWORK_MESSAGE): + socket.create_connection(("example.com", 443), timeout=1) + + def test_getaddrinfo_blocked_for_remote_host(self): + with pytest.raises(RuntimeError, match=BLOCKED_NETWORK_MESSAGE): + socket.getaddrinfo("example.com", 443) + + def test_hostname_connect_blocked(self): + with ( + socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock, + pytest.raises(RuntimeError, match=BLOCKED_NETWORK_MESSAGE), + ): + sock.connect(("example.com", 80)) + + def test_ipv4_loopback_allowed(self): + with _listening_socket(socket.AF_INET, "127.0.0.1") as server: + port = server.getsockname()[1] + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client: + client.connect(("127.0.0.1", port)) + _accept_and_close(server) + with socket.create_connection(("localhost", port), timeout=2): + _accept_and_close(server) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client: + assert client.connect_ex(("127.0.0.1", port)) == 0 + _accept_and_close(server) + + @pytest.mark.skipif(not socket.has_ipv6, reason="IPv6 not available") + def test_ipv6_loopback_allowed(self): + try: + server = _listening_socket(socket.AF_INET6, "::1") + except OSError: + pytest.skip("IPv6 loopback not configured") + with server: + port = server.getsockname()[1] + with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as client: + client.connect(("::1", port)) + + @pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="AF_UNIX not available") + def test_unix_socket_allowed(self): + # Short name: AF_UNIX paths are limited to ~104 bytes on macOS. + directory = tempfile.mkdtemp(prefix="ai-sock-") + path = os.path.join(directory, "s") + try: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as server: + server.bind(path) + server.listen(1) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.connect(path) + finally: + if os.path.exists(path): + os.unlink(path) + os.rmdir(directory) + + @pytest.mark.integration + def test_integration_tests_are_exempt(self): + # No connection is attempted; only verify the guard is not installed. + for func in (socket.socket.connect, socket.create_connection, socket.getaddrinfo): + assert not getattr(func, "__hermetic_guard__", False) + + +class TestFreshSettings: + def test_fresh_settings_replaces_shared_instances(self, fresh_settings, tmp_path): + model_utils = importlib.import_module("agentic_internet.utils.model_utils") + internet_agent = importlib.import_module("agentic_internet.agents.internet_agent") + config_package = importlib.import_module("agentic_internet.config") + + assert SETTINGS_MODULE.settings is fresh_settings + assert model_utils.settings is fresh_settings + assert internet_agent.settings is fresh_settings + assert config_package.settings is fresh_settings + assert fresh_settings.cache_dir.is_dir() + assert tmp_path in fresh_settings.cache_dir.parents + + def test_fresh_settings_reads_monkeypatched_env(self, monkeypatch, request): + monkeypatch.setenv("OPENROUTER_API_KEY", "dummy-test-key") + fresh = request.getfixturevalue("fresh_settings") + assert fresh.openrouter_api_key == "dummy-test-key" + assert fresh.get_model_provider("openrouter/anthropic/claude-opus-4.8") == "openrouter" + + def test_shared_settings_restored_after_fresh_settings(self): + model_utils = importlib.import_module("agentic_internet.utils.model_utils") + assert model_utils.settings is SETTINGS_MODULE.settings + assert SETTINGS_MODULE.settings.cache_dir == IMPORT_CACHE_DIR diff --git a/tests/test_internet_agent_characterization.py b/tests/test_internet_agent_characterization.py new file mode 100644 index 0000000..e2d755c --- /dev/null +++ b/tests/test_internet_agent_characterization.py @@ -0,0 +1,278 @@ +"""Characterization tests for ``InternetAgent`` and ``ResearchAgent`` (RTM-0). + +These tests pin what the code does TODAY, including known defects, so later +runtime refactors (RTM-1..RTM-8) can prove they preserve or intentionally change +behavior. They use fakes only: no live providers, network, or API keys. + +Where a test pins a known defect it carries a comment of the form +``# RTM-characterization: current behavior; expected to change in RTM-``. +""" + +from datetime import datetime +from typing import Any, ClassVar + +import pytest + +from agentic_internet.agents import internet_agent as internet_agent_module +from agentic_internet.agents.internet_agent import InternetAgent, ResearchAgent +from agentic_internet.exceptions import ModelInitializationError + + +class _RecordingAgentClass: + """Stand-in for a SmolAgents agent class that records constructor kwargs.""" + + instances: ClassVar[list["_RecordingAgentClass"]] = [] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self.args = args + self.kwargs = kwargs + type(self).instances.append(self) + + +class _RecordingToolCallingAgent(_RecordingAgentClass): + instances: ClassVar[list["_RecordingAgentClass"]] = [] + + +class _RecordingCodeAgent(_RecordingAgentClass): + instances: ClassVar[list["_RecordingAgentClass"]] = [] + + +class _FakeTool: + name = "fake_tool" + description = "A fake tool used only for characterization tests." + + +class _FakeInnerAgent: + """Fake SmolAgents agent exposing ``run`` and recording every call.""" + + def __init__(self, result: Any = "fake result", error: Exception | None = None) -> None: + self.result = result + self.error = error + self.calls: list[tuple[str, dict[str, Any]]] = [] + + def run(self, task: str, **kwargs: Any) -> Any: + self.calls.append((task, kwargs)) + if self.error is not None: + raise self.error + return self.result + + +@pytest.fixture +def patched_agent_classes(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + """Replace model initialization and SmolAgents classes with recorders.""" + _RecordingToolCallingAgent.instances = [] + _RecordingCodeAgent.instances = [] + fake_model = object() + monkeypatch.setattr(internet_agent_module, "initialize_model", lambda model_id, verbose=True: fake_model) + monkeypatch.setattr(internet_agent_module, "ToolCallingAgent", _RecordingToolCallingAgent) + monkeypatch.setattr(internet_agent_module, "CodeAgent", _RecordingCodeAgent) + return {"tool_calling": _RecordingToolCallingAgent, "code": _RecordingCodeAgent, "model": fake_model} + + +def _bare_agent(inner: _FakeInnerAgent, cls: type[InternetAgent] = InternetAgent) -> InternetAgent: + """Build an agent without running ``__init__`` (no model, no tools).""" + agent = cls.__new__(cls) + agent.verbose = False + agent.agent = inner + return agent + + +class TestAgentConstruction: + def test_default_agent_type_is_tool_calling(self, patched_agent_classes): + agent = InternetAgent(tools=[_FakeTool()], verbose=False) + + assert agent.agent_type == "tool_calling" + assert isinstance(agent.agent, _RecordingToolCallingAgent) + assert _RecordingCodeAgent.instances == [] + + # The max_steps/planning_interval values (including planning_enabled=False -> None) and the + # ``tools=[]`` handling are covered by upstream tests/test_internet_agent.py. The tests below + # add the exact constructor contract (no other kwargs, identity of tools/model, imports). + + def test_tool_calling_agent_receives_exact_controls(self, patched_agent_classes): + tools = [_FakeTool()] + agent = InternetAgent(tools=tools, verbose=False, max_iterations=3, planning_enabled=True) + + recorded = agent.agent + assert isinstance(recorded, _RecordingToolCallingAgent) + # Fixed upstream in PR #7 (stabilization baseline): max_iterations and planning_enabled + # are now forwarded to ToolCallingAgent as max_steps and planning_interval. + assert recorded.kwargs == { + "tools": tools, + "model": patched_agent_classes["model"], + "max_steps": 3, + "planning_interval": 1, + } + assert recorded.kwargs["tools"] is tools + assert recorded.kwargs["model"] is patched_agent_classes["model"] + assert recorded.args == () + + def test_code_agent_receives_exact_controls_and_imports(self, patched_agent_classes): + agent = InternetAgent( + tools=[_FakeTool()], + verbose=False, + max_iterations=4, + planning_enabled=True, + agent_type="code", + additional_authorized_imports=["bs4"], + ) + + recorded = agent.agent + assert isinstance(recorded, _RecordingCodeAgent) + assert _RecordingToolCallingAgent.instances == [] + # Fixed upstream in PR #7 (stabilization baseline): planning_enabled now becomes + # planning_interval for CodeAgent as well. + assert set(recorded.kwargs) == { + "tools", + "model", + "max_steps", + "planning_interval", + "additional_authorized_imports", + } + assert recorded.kwargs["max_steps"] == 4 + assert recorded.kwargs["planning_interval"] == 1 + imports = recorded.kwargs["additional_authorized_imports"] + assert imports[-1] == "bs4" + assert {"pandas", "numpy", "json", "requests", "math"} <= set(imports) + + def test_tools_none_loads_default_tools(self, patched_agent_classes, monkeypatch): + sentinel_tools = [_FakeTool()] + monkeypatch.setattr(InternetAgent, "_get_default_tools", lambda self: sentinel_tools) + + agent = InternetAgent(tools=None, verbose=False) + + # Fixed upstream in PR #7 (stabilization baseline): only ``tools=None`` loads defaults; + # an explicit ``tools=[]`` is honored (asserted in upstream tests/test_internet_agent.py). + assert agent.tools is sentinel_tools + assert agent.agent.kwargs["tools"] is sentinel_tools + + def test_missing_model_raises_model_initialization_error(self, monkeypatch): + monkeypatch.setattr(internet_agent_module, "initialize_model", lambda model_id, verbose=True: None) + + with pytest.raises(ModelInitializationError): + InternetAgent(model_id="no-such-model", tools=[_FakeTool()], verbose=False) + + +class TestRun: + def test_success_returns_str_of_result(self): + inner = _FakeInnerAgent(result=42) + agent = _bare_agent(inner) + + assert agent.run("compute") == "42" + assert inner.calls == [("compute", {})] + + def test_extra_kwargs_are_forwarded_to_inner_agent(self): + inner = _FakeInnerAgent(result="ok") + agent = _bare_agent(inner) + + assert agent.run("task", show_result=False, reset=False) == "ok" + # show_result is consumed by InternetAgent.run; everything else passes through. + assert inner.calls == [("task", {"reset": False})] + + def test_exception_is_returned_as_error_string_not_raised(self): + inner = _FakeInnerAgent(error=RuntimeError("provider exploded")) + agent = _bare_agent(inner) + + # RTM-characterization: current behavior; expected to change in RTM-5 + # Failures are flattened into a success-shaped string instead of a typed failed result. + result = agent.run("task") + + assert result == "Error executing task: provider exploded" + assert isinstance(result, str) + + +class TestResearchAgent: + def _research_agent(self, inner: _FakeInnerAgent) -> ResearchAgent: + agent = _bare_agent(inner, ResearchAgent) + assert isinstance(agent, ResearchAgent) + agent.research_history = [] + return agent + + def test_research_returns_expected_shape(self): + inner = _FakeInnerAgent(result="findings text") + agent = self._research_agent(inner) + + entry = agent.research("quantum batteries", depth="quick") + + assert set(entry) == {"topic", "depth", "findings", "timestamp"} + assert entry["topic"] == "quantum batteries" + assert entry["depth"] == "quick" + assert entry["findings"] == "findings text" + datetime.fromisoformat(entry["timestamp"]) + assert inner.calls == [ + ( + "Quickly search for basic information about quantum batteries. Provide a brief summary.", + {}, + ) + ] + assert agent.get_research_history() == [entry] + + def test_unknown_depth_falls_back_to_moderate_prompt(self): + inner = _FakeInnerAgent(result="r") + agent = self._research_agent(inner) + + entry = agent.research("solid state", depth="exhaustive") + + moderate_prompt = ( + "Research solid state. Search for information, find recent news, " + "and provide a comprehensive summary with sources." + ) + assert inner.calls == [(moderate_prompt, {})] + # The unrecognized depth is still recorded verbatim. + assert entry["depth"] == "exhaustive" + + def test_research_error_is_stored_as_findings(self): + inner = _FakeInnerAgent(error=ValueError("no search")) + agent = self._research_agent(inner) + + # RTM-characterization: current behavior; expected to change in RTM-5 + entry = agent.research("topic") + + assert entry["findings"] == "Error executing task: no search" + assert agent.get_research_history() == [entry] + + +class TestChat: + def test_each_turn_calls_run_without_reset_false(self, monkeypatch): + inner = _FakeInnerAgent(result="reply") + agent = _bare_agent(inner) + agent.tools = [_FakeTool()] + inputs = iter(["hello", "tell me more", "exit"]) + monkeypatch.setattr(internet_agent_module.console, "input", lambda prompt="": next(inputs)) + + agent.chat() + + # RTM-characterization: current behavior; expected to change in RTM-5 + # Turns are stateless: no reset=False is passed, so SmolAgents resets memory every turn + # and the local chat_history list is never fed back to the model. + assert inner.calls == [("hello", {}), ("tell me more", {})] + + def test_chat_turns_go_through_internet_agent_run(self, monkeypatch): + agent = _bare_agent(_FakeInnerAgent()) + run_calls: list[str] = [] + + def fake_run(task: str, **kwargs: Any) -> str: + run_calls.append(task) + return "ok" + + agent.run = fake_run # type: ignore[method-assign] + inputs = iter(["first", "help", "quit"]) + monkeypatch.setattr(internet_agent_module.console, "input", lambda prompt="": next(inputs)) + + agent.chat() + + # "help" is handled locally; only real prompts reach run(). + assert run_calls == ["first"] + + def test_chat_ends_on_keyboard_interrupt(self, monkeypatch): + inner = _FakeInnerAgent() + agent = _bare_agent(inner) + + def interrupt(prompt: str = "") -> str: + raise KeyboardInterrupt + + monkeypatch.setattr(internet_agent_module.console, "input", interrupt) + + agent.chat() + + assert inner.calls == [] diff --git a/tests/test_mcp_lifecycle.py b/tests/test_mcp_lifecycle.py new file mode 100644 index 0000000..50abe70 --- /dev/null +++ b/tests/test_mcp_lifecycle.py @@ -0,0 +1,176 @@ +"""Real local MCP process-lifecycle tests (stdio transport, offline). + +These tests start ``tests/fixtures/mcp_echo_server.py`` as a subprocess through +the project's own MCP integration, list its tools, call them end to end, and +verify that the server process is gone after the context manager exits. + +``trust_remote_code=True`` is set explicitly because SmolAgents refuses to load +MCP tools without it. That is safe here: the server is a local, +repository-controlled fixture that performs no network I/O. Stdio MCP uses +pipes only, so the default-lane socket guard stays active during these tests. +""" + +import os +import signal +import socket +import sys +import threading +import time +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +import pytest + +from agentic_internet.tools.mcp_integration import ( + MCPServerManager, + MCPToolIntegration, + is_mcp_available, + mcp_tools, +) + +SERVER_SCRIPT = Path(__file__).parent / "fixtures" / "mcp_echo_server.py" +EXPECTED_TOOLS = {"echo", "add", "server_pid", "env_is_set"} +#: Hard per-test deadline for the whole start/list/call/shutdown cycle. +LIFECYCLE_TIMEOUT_S = 20.0 +#: How long to wait for the server process to disappear after shutdown. +EXIT_TIMEOUT_S = 5.0 + +pytestmark = [ + pytest.mark.skipif(not is_mcp_available(), reason="mcp/smolagents MCP support not installed"), + pytest.mark.skipif(sys.platform == "win32", reason="process liveness checks use POSIX signals"), +] + + +@contextmanager +def _deadline(seconds: float) -> Iterator[None]: + """Raise TimeoutError in the main thread if the block runs longer than ``seconds``.""" + if threading.current_thread() is not threading.main_thread(): + yield + return + + def _on_timeout(signum, frame): + raise TimeoutError(f"MCP lifecycle exceeded {seconds}s") + + previous = signal.signal(signal.SIGALRM, _on_timeout) + signal.setitimer(signal.ITIMER_REAL, seconds) + try: + yield + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, previous) + + +def _is_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + # PID now belongs to another user's process: our server is gone. + return False + return True + + +def _wait_for_exit(pid: int, timeout: float = EXIT_TIMEOUT_S) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if not _is_alive(pid): + return True + time.sleep(0.05) + return not _is_alive(pid) + + +@pytest.fixture +def server_pids() -> Iterator[list[int]]: + """Collect spawned server PIDs and SIGKILL any survivor during teardown.""" + pids: list[int] = [] + yield pids + for pid in pids: + if not _wait_for_exit(pid, timeout=1.0): + os.kill(pid, signal.SIGKILL) + + +def _tools_by_name(tools) -> dict: + return {tool.name: tool for tool in tools} + + +def _stdio_config() -> dict[str, str]: + # Use this interpreter so the subprocess sees the same installed ``mcp``. + return {"path": str(SERVER_SCRIPT), "command": sys.executable} + + +def test_fixture_server_script_exists(): + assert SERVER_SCRIPT.is_file() + + +def test_stdio_server_full_lifecycle(server_pids): + started = time.monotonic() + with ( + _deadline(LIFECYCLE_TIMEOUT_S), + MCPToolIntegration.connect( + _stdio_config(), + transport_type="stdio", + env={"ECHO_PREFIX": "fixture> "}, + trust_remote_code=True, + ) as tools, + ): + # The default-lane network guard is active while the server runs. + assert getattr(socket.socket.connect, "__hermetic_guard__", False) + + by_name = _tools_by_name(tools) + assert set(by_name) == EXPECTED_TOOLS + + pid = int(by_name["server_pid"]()) + server_pids.append(pid) + assert pid != os.getpid() + assert _is_alive(pid) + + assert by_name["echo"](text="hello") == "fixture> hello" + assert str(by_name["add"](a=2, b=3)) == "5" + # Custom env reaches the server; isolated provider keys do not. + assert str(by_name["env_is_set"](name="ECHO_PREFIX")).lower() == "true" + assert str(by_name["env_is_set"](name="OPENAI_API_KEY")).lower() == "false" + + assert _wait_for_exit(pid), f"MCP server process {pid} still running after shutdown" + assert time.monotonic() - started < LIFECYCLE_TIMEOUT_S + + +def test_mcp_tools_convenience_wrapper(server_pids, monkeypatch): + # ``mcp_tools(server_path=...)`` launches plain ``python``; make sure that + # resolves to this interpreter (which has ``mcp`` installed). + monkeypatch.setenv("PATH", os.path.dirname(sys.executable) + os.pathsep + os.environ.get("PATH", "")) + + with ( + _deadline(LIFECYCLE_TIMEOUT_S), + mcp_tools(server_path=str(SERVER_SCRIPT), trust_remote_code=True) as tools, + ): + by_name = _tools_by_name(tools) + assert set(by_name) == EXPECTED_TOOLS + pid = int(by_name["server_pid"]()) + server_pids.append(pid) + assert by_name["echo"](text="ping") == "echo: ping" + + assert _wait_for_exit(pid), f"MCP server process {pid} still running after shutdown" + + +def test_server_manager_connect_all_single_server(server_pids): + manager = MCPServerManager() + manager.add_server("echo", _stdio_config(), trust_remote_code=True) + + with _deadline(LIFECYCLE_TIMEOUT_S), manager.connect_all() as tools: + by_name = _tools_by_name(tools) + assert set(by_name) == EXPECTED_TOOLS + pid = int(by_name["server_pid"]()) + server_pids.append(pid) + + assert _wait_for_exit(pid), f"MCP server process {pid} still running after shutdown" + + +def test_untrusted_server_is_refused(): + with ( + _deadline(LIFECYCLE_TIMEOUT_S), + pytest.raises(ValueError, match="trust_remote_code"), + MCPToolIntegration.connect(_stdio_config(), trust_remote_code=False), + ): + pytest.fail("tools must not load without trust_remote_code=True") diff --git a/tests/test_multi_model_characterization.py b/tests/test_multi_model_characterization.py new file mode 100644 index 0000000..9f00a4b --- /dev/null +++ b/tests/test_multi_model_characterization.py @@ -0,0 +1,266 @@ +"""Characterization tests for ``MultiModelSerpAPISystem`` (RTM-0). + +These pin the multi-model runtime's current behavior, including known defects, +without network access or API keys. SmolAgents agent classes and model lookup +are replaced with fakes; orchestrator runs are kept well under two seconds. + +PR #7 (stabilization baseline) split ``multi_model_serpapi`` into the +``agentic_internet.agents.multi_model`` package and left the old module as a +re-export shim. Fakes are therefore patched where names are looked up now: +``multi_model.system`` (``CodeAgent``/``ToolCallingAgent``) and the per-instance +``ModelManager``. +""" + +import asyncio +import json +import threading +import time +from typing import Any, ClassVar + +import pytest + +from agentic_internet.agents.multi_model import system as mm_system +from agentic_internet.agents.multi_model.model_manager import ModelManager +from agentic_internet.agents.multi_model.system import MultiModelSerpAPISystem +from agentic_internet.agents.multi_model.tools import AgentTool +from agentic_internet.agents.use_cases import UseCaseRecipe, WorkerRecipe, get_use_case_recipe + + +class _FakeModel: + def __init__(self, model_id: str = "openrouter/openai/gpt-fake") -> None: + self.model_id = model_id + + +class _RecordingAgent: + """Stand-in for a SmolAgents worker agent class.""" + + instances: ClassVar[list["_RecordingAgent"]] = [] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self.args = args + self.kwargs = kwargs + type(self).instances.append(self) + + def run(self, task: str) -> str: + return f"worker:{task}" + + +@pytest.fixture +def no_provider_keys(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ("OPENROUTER_API_KEY", "SERPAPI_API_KEY"): + monkeypatch.delenv(name, raising=False) + + +@pytest.fixture +def system(no_provider_keys: None, monkeypatch: pytest.MonkeyPatch) -> MultiModelSerpAPISystem: + instance = MultiModelSerpAPISystem() + # Keep tool construction hermetic: recipes resolve against an empty inventory. + monkeypatch.setattr(instance, "create_use_case_tool_inventory", lambda: []) + return instance + + +def _tiny_recipe(timeout_seconds: float = 600) -> UseCaseRecipe: + return UseCaseRecipe( + id="tiny", + description="Tiny recipe for characterization tests.", + coordinator_model_role="orchestrator", + workers=(WorkerRecipe(name="only_worker", description="Does the work.", model_role="search_researcher"),), + timeout_seconds=timeout_seconds, + ) + + +def _prime_for_orchestration( + system: MultiModelSerpAPISystem, + monkeypatch: pytest.MonkeyPatch, + orchestrator_cls: type, + recipe: UseCaseRecipe, +) -> None: + """Install one fake worker, a fake orchestrator model, and a fake CodeAgent.""" + # Guard against patching a stale module: CodeAgent must be resolved from mm_system's globals. + assert MultiModelSerpAPISystem.execute_multi_model_workflow.__globals__ is vars(mm_system) + system.active_use_case_recipe = recipe + system.active_use_case_tools = None + system.workers = {"only_worker": _RecordingAgent()} # type: ignore[dict-item] + system.worker_tools = {} + monkeypatch.setattr(system.model_manager, "get_model_for_role", lambda role: _FakeModel()) + monkeypatch.setattr(mm_system, "CodeAgent", orchestrator_cls) + + +class TestModelManagerWithoutKeys: + def test_no_openrouter_key_disables_models(self, no_provider_keys): + manager = ModelManager() + + assert manager.models_available is False + assert manager.get_model_for_role("orchestrator") is None + assert manager.get_model_for_role("claude-opus-4.5") is None + # Model attributes are never set when the key is missing. + assert not hasattr(manager, "claude") + + +class TestExecuteWithoutWorkers: + def test_no_workers_returns_error_json(self, system): + payload = json.loads(asyncio.run(system.execute_multi_model_workflow("find things"))) + + assert set(payload) == {"error", "task"} + assert payload["error"] == "No workers available. Please check API keys and configuration." + assert payload["task"] == "find things" + # The task context is still replaced before the early return. + assert system.current_task_context is not None + assert system.current_task_context.objective == "find things" + + +class TestTimeout: + def test_recipe_timeout_message_reports_none(self, system, monkeypatch): + finished = threading.Event() + + class SlowOrchestrator(_RecordingAgent): + def run(self, task: str) -> str: + time.sleep(0.3) # only slightly longer than the recipe timeout + finished.set() + return "too late" + + _prime_for_orchestration(system, monkeypatch, SlowOrchestrator, _tiny_recipe(timeout_seconds=0.05)) + + started = time.monotonic() + payload = json.loads(asyncio.run(system.execute_multi_model_workflow("slow task"))) + elapsed = time.monotonic() - started + + # RTM-characterization: current behavior; expected to change in RTM-6 + # The recipe timeout is enforced (effective_timeout), but the message interpolates the + # `timeout` argument (None). Still present after PR #7 in multi_model/system.py. + assert payload == { + "error": "Multi-model workflow execution exceeded None seconds", + "task": "slow task", + } + # asyncio.run joins the worker thread on shutdown; the thread is not cancelled. + assert finished.is_set() + assert elapsed < 2 + last_episode = system.memory.episodic[-1] + assert last_episode["success"] is False + assert last_episode["agent"] == "multi_model_orchestrator" + + def test_explicit_timeout_is_reported(self, system, monkeypatch): + class SlowOrchestrator(_RecordingAgent): + def run(self, task: str) -> str: + time.sleep(0.3) + return "too late" + + _prime_for_orchestration(system, monkeypatch, SlowOrchestrator, _tiny_recipe()) + + payload = json.loads(asyncio.run(system.execute_multi_model_workflow("slow task", timeout=0.05))) + + assert payload["error"] == "Multi-model workflow execution exceeded 0.05 seconds" + + def test_orchestrator_receives_recipe_max_steps(self, system, monkeypatch): + class QuickOrchestrator(_RecordingAgent): + instances: ClassVar[list[_RecordingAgent]] = [] + + def run(self, task: str) -> str: + return "done" + + recipe = _tiny_recipe() + _prime_for_orchestration(system, monkeypatch, QuickOrchestrator, recipe) + + payload = json.loads(asyncio.run(system.execute_multi_model_workflow("quick task", timeout=5))) + + assert payload["primary_result"] == "done" + assert set(payload) == {"primary_result", "use_case", "search_performance", "cross_engine_analysis"} + orchestrator = QuickOrchestrator.instances[0] + assert orchestrator.kwargs["max_steps"] == recipe.max_steps + + +class TestAgentToolFailureAsEvidence: + def test_worker_exception_becomes_string(self): + class ExplodingAgent: + def run(self, task: str) -> str: + raise RuntimeError("rate limited") + + tool = AgentTool(agent=ExplodingAgent(), agent_name="search_researcher", agent_description="Searches.") + + # RTM-characterization: current behavior; expected to change in RTM-6 + # Worker failures are returned to the orchestrator as ordinary tool output. + assert tool.forward("look up X") == "Agent search_researcher failed: rate limited" + + def test_missing_worker_becomes_string(self): + tool = AgentTool(agent=None, agent_name="ghost_worker", agent_description="Missing.") + + assert tool.forward("anything") == "Agent ghost_worker is not available" + + def test_success_is_stringified(self): + tool = AgentTool(agent=_RecordingAgent(), agent_name="echo_worker", agent_description="Echoes.") + + assert tool.forward("hello") == "worker:hello" + + +class TestSetupUseCaseWorkers: + def test_worker_without_model_is_silently_skipped(self, system, monkeypatch): + recipe = get_use_case_recipe("research") + missing = "ecommerce_analyst" + missing_worker = next(worker for worker in recipe.workers if worker.name == missing) + assert missing_worker.required is True + + monkeypatch.setattr( + system.model_manager, + "get_model_for_role", + lambda role: None if role == missing_worker.model_role else _FakeModel(), + ) + monkeypatch.setattr(mm_system, "ToolCallingAgent", _RecordingAgent) + monkeypatch.setattr(mm_system, "CodeAgent", _RecordingAgent) + + # RTM-characterization: current behavior; expected to change in RTM-6 + # required=True is not enforced: no exception, the worker is just absent. + returned = system.setup_use_case_workers("research") + + assert returned is recipe + assert missing not in system.workers + assert missing not in system.worker_tools + assert set(system.workers) == set(recipe.worker_names()) - {missing} + # The fakes were actually applied (no real SmolAgents agent was built). + assert all(isinstance(worker, _RecordingAgent) for worker in system.workers.values()) + + def test_no_models_at_all_yields_empty_workers(self, system): + recipe = system.setup_use_case_workers("research") + + assert recipe.id == "research" + assert system.workers == {} + assert system.worker_tools == {} + + +class TestSharedRunState: + def test_overlapping_runs_share_single_task_context(self, system, monkeypatch): + observed: list[str] = [] + + class ObservingOrchestrator(_RecordingAgent): + def run(self, task: str) -> str: + time.sleep(0.1) + context = system.current_task_context + observed.append(context.objective if context else "") + return f"done:{task}" + + _prime_for_orchestration(system, monkeypatch, ObservingOrchestrator, _tiny_recipe()) + + async def run_both() -> list[str]: + return await asyncio.gather( + system.execute_multi_model_workflow("task-A", timeout=5), + system.execute_multi_model_workflow("task-B", timeout=5), + ) + + results = [json.loads(raw) for raw in asyncio.run(run_both())] + + assert [r["primary_result"] for r in results] == ["done:task-A", "done:task-B"] + # RTM-characterization: current behavior; expected to change in RTM-6 + # One mutable current_task_context per system: the second run overwrites the first, + # so the first run observes the second run's objective. Still present after PR #7. + assert observed == ["task-B", "task-B"] + assert system.current_task_context is not None + assert system.current_task_context.objective == "task-B" + + def test_sequential_runs_replace_task_context(self, system): + asyncio.run(system.execute_multi_model_workflow("first")) + first_context = system.current_task_context + + asyncio.run(system.execute_multi_model_workflow("second")) + + assert system.current_task_context is not first_context + assert system.current_task_context is not None + assert system.current_task_context.objective == "second" diff --git a/uv.lock b/uv.lock index 92611ba..e98645c 100644 --- a/uv.lock +++ b/uv.lock @@ -89,7 +89,7 @@ requires-dist = [ { name = "python-dotenv", specifier = ">=1.0.0" }, { name = "requests", specifier = ">=2.31.0" }, { name = "rich", specifier = ">=13.7.0" }, - { name = "smolagents", extras = ["mcp"], specifier = ">=0.1.0" }, + { name = "smolagents", extras = ["mcp"], specifier = ">=1.21.2" }, { name = "torch", specifier = ">=2.0.0" }, { name = "transformers", specifier = ">=4.40.0" }, { name = "typer", specifier = ">=0.12.0" },