From 0bce7568beeb0bcdb414db72d04f8c277db1c24b Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Thu, 22 Oct 2026 04:41:48 +0000 Subject: [PATCH] refactor(ai): delete the unwired harness port and the capability clones nothing imports Fixes #1836 --- AGENTS.md | 2 +- changelog.d/1836.md | 2 + docs/ERRORS.md | 2 - docs/SELF_IMPROVEMENT.md | 2 - .../tasks/task-1836-unwired-harness-port.md | 27 + src/devops_cli/ai/agents/capabilities.py | 890 +----- src/devops_cli/ai/common_tools.py | 12 +- src/devops_cli/ai/format_prompt.py | 19 - src/devops_cli/ai/harness/__init__.py | 199 +- src/devops_cli/ai/harness/agents.py | 586 ---- src/devops_cli/ai/harness/compaction.py | 1007 ------- src/devops_cli/ai/harness/constants.py | 79 - src/devops_cli/ai/harness/conversation.py | 291 -- src/devops_cli/ai/harness/docs.py | 175 -- src/devops_cli/ai/harness/filesystem.py | 373 --- src/devops_cli/ai/harness/memory.py | 713 ----- src/devops_cli/ai/harness/planning.py | 718 ----- src/devops_cli/ai/harness/repo_context.py | 344 --- src/devops_cli/ai/harness/shell.py | 447 --- src/devops_cli/ai/harness/skills.py | 261 +- src/devops_cli/ai/harness/workflow.py | 532 ---- src/devops_cli/ai/tasks/advisor_system.md | 1 - src/devops_cli/ai/tasks/coder_agent.md | 1 - .../ai/tasks/macroscope_guidance.md | 4 - src/devops_cli/ai/tasks/planning_guidance.md | 1 - .../ai/tasks/playwright_guidance.md | 2 - src/devops_cli/ai/tasks/researcher_agent.md | 5 - .../ai/tasks/summarizing_compaction.md | 1 - src/devops_cli/config/__init__.py | 36 - src/devops_cli/config/constants.py | 9 - src/devops_cli/config/defaults.py | 35 +- src/devops_cli/core/dns_names.py | 21 +- src/devops_cli/exceptions/ai.py | 20 - tests/conftest.py | 1 - .../fixtures/swallowed_failures_ceilings.json | 10 - tests/test_ai_agent_capabilities.py | 544 +--- tests/test_ai_agent_deferred_tools.py | 5 +- tests/test_architectural_invariants.py | 11 - tests/test_codebase_hygiene_and_shims.py | 20 - tests/test_docs.py | 3 +- tests/test_harness.py | 2506 ----------------- tests/test_harness_slots.py | 11 +- tests/test_http_egress.py | 3 - tests/test_pydantic_agent.py | 367 +-- tests/test_pydantic_ai_format_prompt.py | 43 - tests/test_pydantic_ai_native_capabilities.py | 128 +- tests/test_rag_hybrid_search.py | 37 +- .../test_review_defenses_and_verification.py | 11 - ...est_runtime_security_and_ssrf_hardening.py | 29 +- ...est_subsystem_containment_and_redaction.py | 83 +- tests/test_validation.py | 60 +- 51 files changed, 232 insertions(+), 10457 deletions(-) create mode 100644 changelog.d/1836.md create mode 100644 docs/agent/tasks/task-1836-unwired-harness-port.md delete mode 100644 src/devops_cli/ai/harness/agents.py delete mode 100644 src/devops_cli/ai/harness/compaction.py delete mode 100644 src/devops_cli/ai/harness/constants.py delete mode 100644 src/devops_cli/ai/harness/conversation.py delete mode 100644 src/devops_cli/ai/harness/docs.py delete mode 100644 src/devops_cli/ai/harness/filesystem.py delete mode 100644 src/devops_cli/ai/harness/memory.py delete mode 100644 src/devops_cli/ai/harness/planning.py delete mode 100644 src/devops_cli/ai/harness/repo_context.py delete mode 100644 src/devops_cli/ai/harness/shell.py delete mode 100644 src/devops_cli/ai/harness/workflow.py delete mode 100644 src/devops_cli/ai/tasks/advisor_system.md delete mode 100644 src/devops_cli/ai/tasks/coder_agent.md delete mode 100644 src/devops_cli/ai/tasks/macroscope_guidance.md delete mode 100644 src/devops_cli/ai/tasks/planning_guidance.md delete mode 100644 src/devops_cli/ai/tasks/playwright_guidance.md delete mode 100644 src/devops_cli/ai/tasks/researcher_agent.md delete mode 100644 src/devops_cli/ai/tasks/summarizing_compaction.md delete mode 100644 tests/test_harness.py diff --git a/AGENTS.md b/AGENTS.md index 2745fbfab8..1d22bd4fda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,7 @@ This document provides foundational context, architectural principles, and opera - Mitigate Server-Side Request Forgery (SSRF) and network egress risks by validating destination endpoints. - **Defensive Subprocess Management & Process Group Isolation**: - When invoking external commands or background workers via `subprocess.Popen`, never terminate processes using simple `proc.kill()`, which leaves spawned subshells as zombies adopted by PID 1. - - Isolate execution into a dedicated POSIX process group (`start_new_session=True` on `subprocess.Popen`) and terminate the entire hierarchy by signalling the group by its id (`os.killpg(proc.pid, signal.SIGTERM)`). See `Shell._terminate_process_group` in `src/devops_cli/ai/harness/shell.py`. + - Isolate execution into a dedicated POSIX process group (`start_new_session=True` on `subprocess.Popen`) and terminate the entire hierarchy by signalling the group by its id (`os.killpg(proc.pid, signal.SIGTERM)`). See `_terminate_process_group` in `src/devops_cli/sandbox/host.py`. - **Protection Against Container Starvation & Killing**: - **Prohibition of `RLIMIT_NPROC`**: In Linux, `setrlimit(RLIMIT_NPROC, ...)` applies per-real-UID across the entire container, NOT per-process tree. Setting `RLIMIT_NPROC` inside child hooks or tests starves ambient container processes (VS Code Server, shells), causing `os.fork()` to fail with `EAGAIN`. Never enforce process caps via `RLIMIT_NPROC` or execute fork bombs in tests. - **Terminal File Descriptor Safety**: Never call `os.set_blocking(fd, False)` or set `O_NONBLOCK` on standard descriptors `{0, 1, 2}`. Setting non-blocking mode on STDOUT/PTY corrupts terminal I/O for VS Code Server. diff --git a/changelog.d/1836.md b/changelog.d/1836.md new file mode 100644 index 0000000000..e0a87bbe39 --- /dev/null +++ b/changelog.d/1836.md @@ -0,0 +1,2 @@ +### Removed +- The Pydantic AI Harness port that no command used is deleted: the shell, filesystem, memory, planning, compaction, sub-agent, docs, repo-context and conversation-search modules of `devops_cli.ai.harness`, the coder, researcher, Macroscope and Playwright agents, and the capability clones in `devops_cli.ai.agents.capabilities` that copy what `pydantic_ai.capabilities` already ships. `devops ai harness` is unchanged, the `Skills` capability that nothing built goes with them, and `HarnessExecutionError` and `MemoryOperationConflictError` are gone with their only caller ([#1836](https://github.com/dan-petty/devops-cli/issues/1836)). diff --git a/docs/ERRORS.md b/docs/ERRORS.md index e1793f142e..762d3b1d97 100644 --- a/docs/ERRORS.md +++ b/docs/ERRORS.md @@ -71,7 +71,6 @@ The Exit Code column is the exception's `exit_code` attribute. Only `devops clou | `GitOperationError` | `GIT_OPERATION_ERROR` | `1` | Git | Base exception for Git repository and branch operation failures. | | `GitOpsSyncError` | `GITOPS_SYNC_ERROR` | `1` | K8s | Raised when GitOps synchronization trigger or reconciliation fails. | | `HTTPTimeoutTypeError` | `VALIDATION_ERROR` | `1` | Devops_cli.http.client | Raised when an invalid timeout parameter type is provided. | -| `HarnessExecutionError` | `HARNESS_EXECUTION_ERROR` | `1` | Ai | Raised when execution of an AI test harness or benchmark fails. | | `HarnessValidationError` | `HARNESS_VALIDATION_ERROR` | `1` | Ai | Raised when an AI evaluation or harness schema validation fails. | | `IncompleteToolCall` | `INCOMPLETE_TOOL_CALL` | `27` | Ai | Raised when a model stops due to token limit while emitting a tool call. | | `InsecureConfigError` | `E_INSECURE_CONFIG` | `126` | Security | Raised when an unencrypted plaintext secret token is found in configuration files. | @@ -87,7 +86,6 @@ The Exit Code column is the exception's `exit_code` attribute. Only `devops clou | `LibraryIngestionError` | `LIBRARY_INGESTION_ERROR` | `1` | Ai | Base exception for package introspection and library ingestion errors. | | `LibraryNotFoundError` | `LIBRARY_NOT_FOUND_ERROR` | `1` | Ai | Raised when target package cannot be imported or found in the environment. | | `LogfireConfigurationError` | `LOGFIRE_CONFIG_ERROR` | `1` | Telemetry | Raised when Logfire configuration fails or credentials cannot be retrieved. | -| `MemoryOperationConflictError` | `HARNESS_EXECUTION_ERROR` | `1` | Devops_cli.ai.harness.memory | Raised when an optimistic concurrency conflict or duplicate operation occurs in memory store. | | `MemoryProfilerError` | `PROFILER_ERROR` | `1` | Devops_cli.telemetry.memory_profiler | Domain exception raised when memory profiling target resolution or execution fails. | | `ModelAPIError` | `MODEL_API_ERROR` | `22` | Ai | Raised when a model provider API request fails. | | `ModelBundleError` | `MODEL_BUNDLE_ERROR` | `1` | Ai | Raised when an AI model bundle cannot be located, resolved, or loaded. | diff --git a/docs/SELF_IMPROVEMENT.md b/docs/SELF_IMPROVEMENT.md index 9aff9a46f9..0f7d4fc58a 100644 --- a/docs/SELF_IMPROVEMENT.md +++ b/docs/SELF_IMPROVEMENT.md @@ -1104,7 +1104,6 @@ prompts from two task files that never existed and scored the fix as the code un The DevSecOps and robustness review session `20260913-231617` produced 13 findings. 11 findings were confirmed and remediated with test-first fixes; 2 findings were classified as false-positive hallucinations and disarmed: 1. **Path Containment & Traversal Hardening**: - - `SqlitePlanStore`: Constrained database paths to project roots, temp paths, or user home; blocked arbitrary system paths. - `DEVOPS_CLI_CONFIG`: Validated path traversal and forbidden system paths when loading config from environment. - `run_subprocess` / `run_subprocess_async`: Enforced path containment and system path rejection on caller-supplied `cwd`. - `devcontainer` mounts: Enforced path traversal checks on volume mount targets. @@ -1144,7 +1143,6 @@ The DevSecOps and Architecture review session `20260915-124521` produced 22 find 3. **Symlink Traversal & Path Containment Hardening (CWE-22 / CWE-59)**: - `argo/gitops.py` (`_scan_directory_manifests`): Explicitly skipped symlinks (`is_symlink()`) and enforced repository root containment (`resolved.is_relative_to(repo_root)`). - `security/gitleaks.py` (`_resolve_scan_files`): Enforced `_is_safe_file` validation across candidate lists, individual files, and directory trees, skipping symlinks and out-of-bounds files. - - `ai/harness/filesystem.py` (`_list_directory`): Added symlink skipping guard. - `ai/rag/indexer.py` (`_is_indexable_file`): Skipped symlinks and verified root containment. - `config/settings.py` (`_find_project_config_path`): Disallowed symlinks and forbidden system paths. diff --git a/docs/agent/tasks/task-1836-unwired-harness-port.md b/docs/agent/tasks/task-1836-unwired-harness-port.md new file mode 100644 index 0000000000..8bbefddcb7 --- /dev/null +++ b/docs/agent/tasks/task-1836-unwired-harness-port.md @@ -0,0 +1,27 @@ +# Task: Delete the Unwired Harness Port and the Capability Clones Nothing Imports (#1836) + +**Issue**: [#1836](https://github.com/dan-petty/devops-cli/issues/1836) +**Scope**: scope/ai +**Feasibility**: At the base, an AST import graph over `src/devops_cli` (entry points: every `commands/` and `server/` module and `main`) reaches only `ai/harness/slots.py`, `ai/harness/skills.py` and `ai/harness/constants.py`, through `commands/ai_harness.py`. The ten other modules under `ai/harness/` (5,186 lines) load only because `ai/harness/__init__.py` imports them. No `importlib`, `__import__`, entry point or registry names them or the classes in `ai/agents/capabilities.py`: `AgentSpec.capabilities` is an untyped list. A per-symbol scan of `ai/agents/capabilities.py` found importers outside the deleted code for `BaseCapability`, `HandleDeferredToolCalls`, `SystemReminders`, `_accepts_positional_arguments` and the `ToolCallPart`, `DeferredToolRequests`, `DeferredToolResults`, `ToolApproved` and `ToolDenied` re-exports only. The pinned pydantic-ai 2.54.0 already exports `Thinking`, `WebSearch`, `WebFetch`, `MCP`, `NativeTool`, `PrefixTools` and the other clone names from `pydantic_ai.capabilities`, so nothing is lost. After the deletion `ruff check`, `mypy --strict` and the whole collected suite (11,372 tests) import cleanly, and `devops ai harness status` still runs. A `git grep` over `src` found no caller of `is_private_ip_or_localhost`, `format_plan_reminder_as_xml` or `harness.skills.Skills` outside the deleted modules, their own exports and their own tests. + +## Description +The harness package was a port of Pydantic AI Harness capabilities (shell, filesystem, memory, planning, compaction, sub-agents, docs, repo context, conversation search, a coder, a researcher, a Macroscope reviewer and a Playwright browser) that no command, server tool or other module used. `ai/agents/capabilities.py` held a second set of unused clones of capabilities that pydantic-ai ships itself. Both are deleted with their tests. No shim replaces them: if the capabilities are wanted later, they come from pydantic-ai or from pydantic-ai-harness, which pins pydantic-ai-slim 2.59.0 against our 2.54.0, so adopting it is a separate dependency decision. + +- `ai/harness/` loses `agents.py`, `compaction.py`, `conversation.py`, `docs.py`, `filesystem.py`, `memory.py`, `planning.py`, `repo_context.py`, `shell.py` and `workflow.py`. `__init__.py` exports only what `skills.py` and `slots.py` define. `constants.py` is deleted: its seven prompt constants, command and pattern sets, `HarnessDeprecationWarning` and logger served the deleted modules, and `UNSUPPORTED_BEHAVIORAL_SKILL_FIELDS` served only the `Skills` capability. `skills.py` keeps `ParsedSkill` and `normalize_skill_name`, which `slots.py` uses, and loses the `Skills` capability (nothing in `src` built it), its frontmatter helpers and a second copy of `DEFAULT_PYAI_DOCS_TOPICS`. +- `ai/agents/capabilities.py` keeps `BaseCapability`, `HandleDeferredToolCalls`, `SystemReminders`, `_accepts_positional_arguments` and the five re-exports, and goes from 1,116 lines to 232. `BaseCapability.prefix_tools` and `BaseCapability.with_metadata` go with the clones they returned: `prefix_tools` falls back to the upstream method; `with_metadata` is removed with no replacement. The module docstring and `HandleDeferredToolCalls.handle_deferred` no longer name deleted classes. +- The seven task prompts only `harness/constants.py` loaded are deleted from `ai/tasks/`: `advisor_system`, `summarizing_compaction`, `coder_agent`, `researcher_agent`, `macroscope_guidance`, `planning_guidance` and `playwright_guidance`. +- `HarnessExecutionError` was raised only by `memory.py`. It is deleted with `MemoryOperationConflictError`, `CONST_ERROR_CODE_HARNESS_EXECUTION`, the `CONST_DOMAIN_EXCEPTION_MODULES` entry for the memory module and `CONST_SQLITE_PER_CONNECTION_DATABASES`. `docs/ERRORS.md` is regenerated and loses both rows. +- Sixteen `DEFAULT_*` constants used only by the clones leave `config/defaults.py` and `config/__init__.py`: the three thread-executor settings, the identifiers of the select-model, resolve-model, prepare-tools, prefix-tools, return-schema, tool-metadata, content-filter, reinject-prompt, process-history and process-event-stream clones, `DEFAULT_AGENT_STREAM_EVENT_KIND`, `DEFAULT_THINKING_EFFORT` and `DEFAULT_REASONING_FORMAT`. `DEFAULT_SHELL_BG_OUTPUT_LINES` and `DEFAULT_SHELL_DRAIN_TIMEOUT_SECONDS` go with the shell. `DEFAULT_PLAN_REMINDER_ID` and `DEFAULT_PLAN_REMINDER_CADENCE` stay: `agent.py` and `SystemReminders` use them. +- The shared lists follow the deletion: the harness keys in `tests/fixtures/swallowed_failures_ceilings.json`, the harness paths in the bare-exception list of `tests/test_architectural_invariants.py`, the compaction reset in `tests/conftest.py`, the memory-conflict row `tests/test_docs.py` pinned, and the `harness docs` rows of `tests/test_http_egress.py`. AGENTS.md now names `_terminate_process_group` in `src/devops_cli/sandbox/host.py` as the guarded process-group termination, in place of the deleted `Shell` method. The two bullets of the historical case-study section of `docs/SELF_IMPROVEMENT.md` that described fixes in deleted code are removed. +- Tests: `tests/test_harness.py` is deleted: it exercised the deleted modules and the `Skills` capability, and the `normalize_skill_name` check it held moves to `tests/test_harness_slots.py`, next to the skill slot that calls it. Tests that reached live code only through a clone are rewritten with a `BaseCapability` subclass or `SystemReminders`: the on-demand `load_capability` test in `tests/test_pydantic_agent.py`, the `BaseCapability` subclass test and a new `MCPToolset` test in `tests/test_ai_agent_capabilities.py`, the capability tests of `tests/test_pydantic_ai_native_capabilities.py`, and the `Thinking()` placeholders of `tests/test_ai_agent_deferred_tools.py`. `tests/test_validation.py` keeps the `k8s.domain` and `cloudflare.domain` validation as `test_settings_domain_validation`, the only test of that Settings validation, and drops the clone halves. It also gains `test_settings_domain_refuses_every_spelling_of_the_root_name`, which feeds `@` and the IDNA full stops to the validator branch that rejects the root name. The numbered section comments of the touched test modules are renumbered, and the docstring of `tests/test_subsystem_containment_and_redaction.py` no longer lists the two groups of tests deleted from it. +- Ceilings only go down: `DEFAULT_C901_SUPPRESSION_CEILING` falls from 47 to 28, `src type: ignore` from 89 to 71, `tests type: ignore` from 228 to 139 and `tests noqa: F401` from 4 to 3, the counts the suppression collector of `tests/test_architectural_invariants.py` measures on this tree. +- Orphans of the deletion: `common_tools.is_private_ip_or_localhost` (its only caller was `harness/agents.py`) and `format_prompt.format_plan_reminder_as_xml` (its only caller was `harness/planning.py`) are deleted with the two `DEFAULT_XML_PLAN_REMINDER_*` constants and the test of the formatter. `validate_configured_domain` in `core/dns_names.py` loses its IP-literal early return and its fall-through field label, which only the deleted capability domain lists reached; it now names `k8s.domain` or `cloudflare.domain` from the model title, as the two settings fields are its only users. +- Not done: `common_tools.web_fetch_tool` and `duckduckgo_search_tool` had their callers in the deleted code and are left with none in `src`. So do the other tool factories of `common_tools.py` (`exa_*`, `image_generation_tool`, `x_search_tool`, `tavily_search_tool`), which had none before this change. Deleting the module's tool family takes the untrusted-page renderer, its dependencies and the egress tests of `tests/test_common_tools.py`, `tests/test_native_common_tools.py` and `tests/test_http_egress.py` with it, which is a decision about the whole module, not a part of this deletion. It is [#1854](https://github.com/dan-petty/devops-cli/issues/1854), which reduces `common_tools.py` to `tavily_search`; the dead pydantic_ai facades are [#1852](https://github.com/dan-petty/devops-cli/issues/1852), and the unwired agent extras are part of [#1121](https://github.com/dan-petty/devops-cli/issues/1121). + +## Acceptance Criteria +- [x] The ten harness modules and every `ai/agents/capabilities.py` symbol without a caller outside the deleted code are deleted together with their tests, and none is skipped or xfailed. A search of `src`, `tests`, `AGENTS.md`, `README.md` and `docs` (outside `docs/agent/tasks`, `docs/agent/archive` and `CHANGELOG.md`) for the deleted module paths and class names finds nothing. +- [x] The import graph from `commands/`, `server/` and `main` reaches no deleted module, and the deleted modules are absent from the tree afterwards. +- [x] The harness slots, the remaining capability, agent, deferred-tool, export-surface, hygiene and architectural-invariant tests pass, with only tests that referenced deleted names removed or rewritten. +- [x] AGENTS.md names a function that exists as the process-group termination reference, `CONST_DOMAIN_EXCEPTION_MODULES` and the invariants list name no deleted module, the ceilings fixture has no key for a deleted file, and `docs/ERRORS.md` is regenerated and `uv run devops docs check` reports every file up to date. +- [x] `ruff check`, `ruff format --check` and `mypy` pass over `src` and `tests`, and no module under `ai/agents/` or `ai/pydantic_ai_bridge.py` loses covered lines. +- Pending a person: `uv run devops ci` passes on the delivering tree. This change ran the targeted tests and a full-suite coverage run, not the gate. diff --git a/src/devops_cli/ai/agents/capabilities.py b/src/devops_cli/ai/agents/capabilities.py index 88f6254a7d..0e25f0c0fd 100644 --- a/src/devops_cli/ai/agents/capabilities.py +++ b/src/devops_cli/ai/agents/capabilities.py @@ -1,23 +1,19 @@ -"""Agent capability interfaces, progressive disclosure, and provider-native tool bindings.""" +"""Agent capability base class, deferred tool call handling, and periodic system reminders.""" from __future__ import annotations import inspect from collections.abc import Callable -from dataclasses import dataclass from typing import Any from pydantic import BaseModel, ConfigDict, Field from pydantic_ai.capabilities import AbstractCapability -from pydantic_ai.messages import ( - ThinkingPart as NativeThinkingPart, -) from pydantic_ai.messages import ( ToolCallPart as ToolCallPart, ) from devops_cli.ai.agents.context import AgentHooks, RunContext -from devops_cli.ai.agents.tools import AgentTool, Tool +from devops_cli.ai.agents.tools import AgentTool from devops_cli.ai.tools import ( DeferredToolRequests as DeferredToolRequests, ) @@ -31,35 +27,9 @@ ToolDenied as ToolDenied, ) from devops_cli.config.defaults import ( - DEFAULT_AGENT_STREAM_EVENT_KIND, - DEFAULT_INCLUDE_RETURN_SCHEMAS_ID, DEFAULT_PLAN_REMINDER_CADENCE, DEFAULT_PLAN_REMINDER_ID, - DEFAULT_PREFIX_TOOLS_ID, - DEFAULT_PREPARE_TOOLS_ID, - DEFAULT_PROCESS_EVENT_STREAM_ID, - DEFAULT_PROCESS_HISTORY_ID, - DEFAULT_RAISE_CONTENT_FILTER_ID, - DEFAULT_REASONING_FORMAT, - DEFAULT_REINJECT_SYSTEM_PROMPT_ID, - DEFAULT_RESOLVE_MODEL_ID, - DEFAULT_SELECT_MODEL_ID, - DEFAULT_SET_TOOL_METADATA_ID, - DEFAULT_THINKING_EFFORT, - DEFAULT_THREAD_EXECUTOR_ID, - DEFAULT_THREAD_EXECUTOR_MAX_WORKERS, - DEFAULT_THREAD_EXECUTOR_PREFIX, ) -from devops_cli.core.dns_names import ConfiguredDomain - - -@dataclass -class ThinkingPart(NativeThinkingPart): - """A structured model thinking/reasoning part.""" - - content: str = "" - encrypted_content: str | None = None - signature: str | None = None class BaseCapability(BaseModel, AbstractCapability[Any]): @@ -89,15 +59,6 @@ def get_model_settings( # type: ignore[override] """Return model runtime settings provided by this capability.""" return {} - def prefix_tools(self, prefix: str) -> Any: - """Return a PrefixTools capability wrapper for this capability.""" - return PrefixTools(self, prefix=prefix) - - def with_metadata(self, metadata: dict[str, Any] | None = None, **kwargs: Any) -> Any: - """Return a SetToolMetadata capability wrapper attaching metadata to this capability's tools.""" - combined = {**(metadata or {}), **kwargs} - return SetToolMetadata(capability=self, metadata=combined) - # ── Pydantic AI AbstractCapability Protocol Implementation ───────────────── def get_instructions(self) -> list[str] | None: @@ -178,321 +139,6 @@ async def after_tool_execute( return result -class WebSearchUserLocation(BaseModel): - """Geographic location configuration for native web search requests.""" - - city: str | None = None - country: str | None = None - region: str | None = None - timezone: str | None = None - - -class WebSearchTool(BaseModel): - """Configuration for provider-native Web Search tool capability.""" - - search_context_size: str = "medium" - user_location: WebSearchUserLocation | None = None - blocked_domains: list[ConfiguredDomain] = Field(default_factory=list) - allowed_domains: list[ConfiguredDomain] | None = None - max_uses: int | None = None - - -class WebFetchTool(BaseModel): - """Configuration for provider-native Web Fetch tool capability.""" - - allowed_domains: list[ConfiguredDomain] | None = None - blocked_domains: list[ConfiguredDomain] = Field(default_factory=list) - max_uses: int | None = None - enable_citations: bool | None = None - max_content_tokens: int | None = None - - -class CodeExecutionTool(BaseModel): - """Configuration for provider-native Code Execution sandbox tool capability.""" - - language: str = "python" - timeout: float | None = None - - -class MCPServerTool(BaseModel): - """Configuration for provider-native or remote Model Context Protocol (MCP) server tool.""" - - id: str = "mcp_server" - url: str = "" - authorization_token: str | None = None - description: str | None = None - - -def _build_mcp_tool_settings(tool: MCPServerTool) -> dict[str, Any]: - """Serialize MCPServerTool configuration for provider-native runtime settings.""" - return { - "native_mcp_server": True, - "mcp_server_config": tool.model_dump(exclude_none=True), - } - - -_NATIVE_TOOL_SETTINGS_BUILDERS: dict[type, Callable[[Any], dict[str, Any]]] = { - WebSearchTool: lambda t: { - "native_web_search": True, - "web_search_config": t.model_dump(exclude_none=True), - }, - WebFetchTool: lambda t: { - "native_web_fetch": True, - "web_fetch_config": t.model_dump(exclude_none=True), - }, - CodeExecutionTool: lambda t: { - "native_code_execution": True, - "code_execution_config": t.model_dump(exclude_none=True), - }, - MCPServerTool: _build_mcp_tool_settings, -} - -_NATIVE_TOOL_PROMPT_BUILDERS: dict[type, Callable[[Any], list[str]]] = { - WebSearchTool: lambda _: ["Provider-native web search capability is enabled."], - WebFetchTool: lambda _: ["Provider-native web fetch capability is enabled."], - CodeExecutionTool: lambda _: [ - "Provider-native sandboxed code execution capability is enabled." - ], - MCPServerTool: lambda t: [f"Provider-native MCP server capability is enabled (id: {t.id})."], -} - - -def _extract_local_tools(local_obj: Any) -> list[AgentTool | Callable[..., Any]]: - """Extract callable or Tool instances from polymorphic local capability/tool objects.""" - if not local_obj: - return [] - if isinstance(local_obj, BaseCapability): - return local_obj.get_tools() - if isinstance(local_obj, Tool): - return [local_obj] - if callable(local_obj): - return [Tool.from_function(local_obj)] - if hasattr(local_obj, "get_tools") and callable(local_obj.get_tools): - tools_val = local_obj.get_tools() - if isinstance(tools_val, list): - return [t for t in tools_val if isinstance(t, (AgentTool, Tool)) or callable(t)] - if isinstance(local_obj, list): - return [t for t in local_obj if isinstance(t, (AgentTool, Tool)) or callable(t)] - return [] - - -class NativeTool(BaseCapability): - """Capability that configures and exposes provider-native server tools.""" - - id: str | None = "native_tool" - tool: WebSearchTool | WebFetchTool | CodeExecutionTool | MCPServerTool | BaseModel - - def get_model_settings( # type: ignore[override] - self, ctx: RunContext[Any] | None = None - ) -> dict[str, Any]: - """Return model runtime settings configuring the provider-native tool.""" - builder = _NATIVE_TOOL_SETTINGS_BUILDERS.get(type(self.tool)) - if builder is not None: - return builder(self.tool) - dumped = self.tool.model_dump(exclude_none=True) - dumped.pop("authorization_token", None) - return {"native_tool": dumped} - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - builder = _NATIVE_TOOL_PROMPT_BUILDERS.get(type(self.tool)) - return builder(self.tool) if builder is not None else [] - - -class MCP(BaseCapability): - """Provider-adaptive Model Context Protocol (MCP) capability supporting local and native servers.""" - - id: str | None = "mcp" - url: str | None = None - native: bool | MCPServerTool = False - local: Any = True - - def __init__( - self, - url: str | None = None, - *, - native: bool | MCPServerTool = False, - local: Any = True, - ) -> None: - super().__init__(url=url, native=native, local=local) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - if self.local is False: - return [] - return _extract_local_tools(self.local) - - def get_model_settings( # type: ignore[override] - self, ctx: RunContext[Any] | None = None - ) -> dict[str, Any]: - if self.native: - if isinstance(self.native, MCPServerTool): - return _build_mcp_tool_settings(self.native) - return { - "native_mcp_server": True, - "mcp_server_config": {"url": self.url} if self.url else {}, - } - return {} - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - target = self.url or ( - self.native.url if isinstance(self.native, MCPServerTool) else "local client" - ) - return [f"Model Context Protocol (MCP) capability active (target: {target})."] - - -class WebSearch(BaseCapability): - """Provider-adaptive Web Search capability supporting native provider search and local fallback.""" - - id: str | None = "web_search" - local: Any = False - native: bool | WebSearchTool = True - - def __init__( - self, - *, - local: Any = False, - native: bool | WebSearchTool = True, - ) -> None: - super().__init__(local=local, native=native) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - if not self.local: - return [] - if self.local is True or self.local == "duckduckgo": - from devops_cli.ai.common_tools import duckduckgo_search_tool - - return [duckduckgo_search_tool()] - return _extract_local_tools(self.local) - - def get_model_settings( # type: ignore[override] - self, ctx: RunContext[Any] | None = None - ) -> dict[str, Any]: - if self.native: - if isinstance(self.native, WebSearchTool): - return { - "native_web_search": True, - "web_search_config": self.native.model_dump(exclude_none=True), - } - return {"native_web_search": True, "web_search_config": {}} - return {} - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - if self.native: - return ["Provider-native web search capability is enabled."] - if self.local: - return ["Local web search capability is enabled."] - return [] - - -class WebFetch(BaseCapability): - """Provider-adaptive Web Fetch capability supporting native provider fetch and local fallback.""" - - id: str | None = "web_fetch" - allowed_domains: list[ConfiguredDomain] | None = None - blocked_domains: list[ConfiguredDomain] = Field(default_factory=list) - local: Any = False - native: bool | WebFetchTool = True - - def __init__( - self, - *, - allowed_domains: list[str] | None = None, - blocked_domains: list[str] | None = None, - local: Any = False, - native: bool | WebFetchTool = True, - ) -> None: - super().__init__( - allowed_domains=allowed_domains, - blocked_domains=blocked_domains or [], - local=local, - native=native, - ) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - if not self.local: - return [] - if self.local is True: - from devops_cli.ai.common_tools import web_fetch_tool - - return [ - web_fetch_tool( - allowed_domains=self.allowed_domains, - blocked_domains=self.blocked_domains, - ) - ] - return _extract_local_tools(self.local) - - def get_model_settings( # type: ignore[override] - self, ctx: RunContext[Any] | None = None - ) -> dict[str, Any]: - if self.native: - if isinstance(self.native, WebFetchTool): - return { - "native_web_fetch": True, - "web_fetch_config": self.native.model_dump(exclude_none=True), - } - config: dict[str, Any] = {} - if self.allowed_domains: - config["allowed_domains"] = self.allowed_domains - if self.blocked_domains: - config["blocked_domains"] = self.blocked_domains - return {"native_web_fetch": True, "web_fetch_config": config} - return {} - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - if self.native: - return ["Provider-native web fetch capability is enabled."] - if self.local: - return ["Local web fetch capability is enabled."] - return [] - - -class Thinking(BaseCapability): - """Capability configuring unified thinking and reasoning effort across LLM providers.""" - - id: str | None = "thinking" - effort: str | bool = DEFAULT_THINKING_EFFORT - budget_tokens: int | None = None - include_thoughts: bool = True - include_encrypted_content: bool = False - reasoning_format: str = DEFAULT_REASONING_FORMAT - - def __init__( - self, - effort: str | bool = DEFAULT_THINKING_EFFORT, - *, - budget_tokens: int | None = None, - include_thoughts: bool = True, - include_encrypted_content: bool = False, - reasoning_format: str = DEFAULT_REASONING_FORMAT, - ) -> None: - super().__init__( - effort=effort, - budget_tokens=budget_tokens, - include_thoughts=include_thoughts, - include_encrypted_content=include_encrypted_content, - reasoning_format=reasoning_format, - ) - - def get_model_settings( # type: ignore[override] - self, ctx: RunContext[Any] | None = None - ) -> dict[str, Any]: - settings: dict[str, Any] = { - "thinking": self.effort if isinstance(self.effort, (str, bool)) else True, - "include_thoughts": self.include_thoughts, - "reasoning_format": self.reasoning_format, - } - if self.budget_tokens is not None: - settings["budget_tokens"] = self.budget_tokens - settings["thinking_budget_tokens"] = self.budget_tokens - if self.include_encrypted_content: - settings["include_encrypted_content"] = True - settings["xai_include_encrypted_content"] = True - return settings - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - return [f"Thinking capability is enabled (effort={self.effort})."] - - def _accepts_positional_arguments(func: Callable[..., Any], count: int) -> bool: """Whether ``func`` can be called with ``count`` positional arguments and nothing else. @@ -527,7 +173,7 @@ def handle_deferred( The call is chosen by the handler's signature alone. A handler that can be called with the requests alone, such as ``(requests)`` or ``(requests, **kwargs)``, gets them alone. Any other gets ``(ctx, requests)``, as pydantic-ai calls it, with a fresh ``RunContext`` - when none is given, as ``ProcessHistory`` and ``ProcessEventStream`` do. + when none is given. """ if not callable(self.handler): return None @@ -541,37 +187,6 @@ def handle_deferred( return None -class Capability(BaseCapability): - """Concrete capability bundling instructions, tools, settings, and progressive disclosure.""" - - instructions: str = "" - tools: list[AgentTool | Callable[..., Any]] = Field(default_factory=list) - model_settings: dict[str, Any] = Field(default_factory=dict) - - def tool(self, func: Callable[..., Any]) -> Callable[..., Any]: - """Decorator to register a tool on this capability.""" - self.tools.append(func) - return func - - def tool_plain(self, func: Callable[..., Any]) -> Callable[..., Any]: - """Decorator to register a plain tool on this capability.""" - self.tools.append(func) - return func - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - return list(self.tools) - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - if self.instructions: - return [self.instructions] - return [] - - def get_model_settings( # type: ignore[override] - self, ctx: RunContext[Any] | None = None - ) -> dict[str, Any]: - return dict(self.model_settings) - - class SystemReminders(BaseCapability): """Capability that combats instruction fade by re-injecting targeted behavioral guidance on a cadence.""" @@ -615,502 +230,3 @@ def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> lis self._turn_counter += 1 return self.get_reminders(ctx, self._turn_counter) return list(self.reminders) - - -class Instrumentation(BaseCapability): - """Capability providing OpenTelemetry distributed span tracing and metric instrumentation for agents.""" - - id: str | None = "instrumentation" - tracer_name: str = "devops_cli.agent" - record_spans: bool = True - record_metrics: bool = True - - def get_hooks(self) -> AgentHooks | None: - """Bind OpenTelemetry tracing hooks into agent execution.""" - - def before_tool(ctx: RunContext[Any], tool_name: str, args: dict[str, Any]) -> None: - pass - - def after_tool(ctx: RunContext[Any], tool_name: str, result: Any) -> None: - pass - - return AgentHooks(before_tool_execute=[before_tool], after_tool_execute=[after_tool]) - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - return [] - - -class UseThreadExecutor(BaseCapability): - """Capability that executes synchronous tool calls in a dedicated, bounded ThreadPoolExecutor.""" - - id: str | None = DEFAULT_THREAD_EXECUTOR_ID - executor: Any = None - max_workers: int = DEFAULT_THREAD_EXECUTOR_MAX_WORKERS - thread_name_prefix: str = DEFAULT_THREAD_EXECUTOR_PREFIX - - def __init__( - self, - executor: Any = None, - *, - max_workers: int = DEFAULT_THREAD_EXECUTOR_MAX_WORKERS, - thread_name_prefix: str = DEFAULT_THREAD_EXECUTOR_PREFIX, - id: str = DEFAULT_THREAD_EXECUTOR_ID, - **kwargs: Any, - ) -> None: - if executor is None: - from concurrent.futures import ThreadPoolExecutor - - executor = ThreadPoolExecutor( - max_workers=max_workers, thread_name_prefix=thread_name_prefix - ) - super().__init__( - id=id, - executor=executor, - max_workers=max_workers, - thread_name_prefix=thread_name_prefix, - **kwargs, - ) - - def run_sync(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: - """Run synchronous function in the executor and return its result.""" - from functools import partial - - future = self.executor.submit(partial(func, *args, **kwargs)) - return future.result() - - -ThreadExecutor = UseThreadExecutor - - -class ModelSelectionContext[DepsT](BaseModel): - """Runtime context provided to dynamic model selector callables.""" - - deps: DepsT | None = None - session_id: str = "" - turn: int = 1 - step_number: int = 1 - current_model: str | None = "" - - -class SelectModel(BaseCapability): - """Capability that dynamically selects the LLM model at runtime for each step.""" - - id: str | None = DEFAULT_SELECT_MODEL_ID - selector: Any = None - - def __init__( - self, - selector: Callable[..., str] | None = None, - *, - id: str = DEFAULT_SELECT_MODEL_ID, - **kwargs: Any, - ) -> None: - super().__init__(id=id, selector=selector or kwargs.get("selector"), **kwargs) - - def select_model( - self, ctx: ModelSelectionContext[Any] | RunContext[Any] | None = None - ) -> str | None: - """Execute selector to resolve dynamic model ID.""" - if not callable(self.selector): - return None - if ctx is None: - return str(self.selector(ModelSelectionContext[Any]())) - if isinstance(ctx, RunContext): - current_model_str = str(ctx.model) if getattr(ctx, "model", None) is not None else "" - sel_ctx: ModelSelectionContext[Any] = ModelSelectionContext( - deps=ctx.deps, - session_id=ctx.session_id, - current_model=current_model_str, - ) - return str(self.selector(sel_ctx)) - return str(self.selector(ctx)) - - -class ModelResolutionContext[DepsT](BaseModel): - """Runtime context provided to dynamic model ID resolvers.""" - - deps: DepsT | None = None - session_id: str = "" - tenant_id: str | None = None - model_id: str = "" - - -class ResolveModelId(BaseCapability): - """Capability that intercepts and resolves custom or tenant-specific model identifiers.""" - - id: str | None = DEFAULT_RESOLVE_MODEL_ID - resolver: Any = None - - def __init__( - self, - resolver: Callable[..., Any] | None = None, - *, - id: str = DEFAULT_RESOLVE_MODEL_ID, - **kwargs: Any, - ) -> None: - super().__init__(id=id, resolver=resolver or kwargs.get("resolver"), **kwargs) - - def resolve( - self, - model_id: str, - ctx: ModelResolutionContext[Any] | RunContext[Any] | None = None, - ) -> Any | None: - """Resolve a model identifier to a concrete model ID or instance.""" - if not callable(self.resolver): - return None - res_ctx: ModelResolutionContext[Any] - if ctx is None: - res_ctx = ModelResolutionContext[Any](model_id=model_id) - elif isinstance(ctx, RunContext): - res_ctx = ModelResolutionContext[Any]( - deps=ctx.deps, - session_id=ctx.session_id, - model_id=model_id, - ) - else: - res_ctx = ctx - return self.resolver(res_ctx, model_id) - - -class PrepareTools(BaseCapability): - """Capability that dynamically prepares, filters, or modifies available tool definitions.""" - - id: str | None = DEFAULT_PREPARE_TOOLS_ID - prepare_fn: Any = None - - def __init__( - self, - prepare_fn: Callable[..., Any] | None = None, - *, - id: str = DEFAULT_PREPARE_TOOLS_ID, - **kwargs: Any, - ) -> None: - super().__init__(id=id, prepare_fn=prepare_fn or kwargs.get("prepare_fn"), **kwargs) - - def prepare_tools( # type: ignore[override] - self, - ctx: RunContext[Any], - tools: list[Any], - ) -> list[Any]: - """Execute prepare_fn to filter or modify tool definitions.""" - if not callable(self.prepare_fn): - return tools - result = self.prepare_fn(ctx, tools) - return result if result is not None else tools - - -class PrefixTools(BaseCapability): - """Capability that prefixes all tools from a capability with a namespace prefix to prevent collisions.""" - - id: str | None = DEFAULT_PREFIX_TOOLS_ID - capability: Any = None - prefix: str = "" - - def __init__( - self, - capability: BaseCapability | None = None, - prefix: str = "", - *, - id: str = DEFAULT_PREFIX_TOOLS_ID, - **kwargs: Any, - ) -> None: - cap = capability or kwargs.get("capability") - pfx = prefix or kwargs.get("prefix", "") - super().__init__(id=id, capability=cap, prefix=pfx, **kwargs) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - """Return prefixed tools from the wrapped capability.""" - if self.capability is None: - return [] - raw_tools = self.capability.get_tools() - prefixed_tools: list[AgentTool | Callable[..., Any]] = [] - for t in raw_tools: - if isinstance(t, Tool): - new_name = ( - f"{self.prefix}_{t.name}" - if not t.name.startswith(f"{self.prefix}_") - else t.name - ) - prefixed_tools.append( - Tool( - function=t.function, - name=new_name, - description=t.description, - parameters=t.parameters, - takes_ctx=t.takes_ctx, - timeout=t.timeout, - max_retries=t.max_retries, - requires_approval=t.requires_approval, - include_return_schema=t.include_return_schema, - ) - ) - elif callable(t): - base_name = getattr(t, "__name__", "tool") - new_name = f"{self.prefix}_{base_name}" - prefixed_tools.append(Tool.from_function(t, name=new_name)) - else: - prefixed_tools.append(t) - return prefixed_tools - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - return self.capability.get_system_prompt_additions(ctx) if self.capability else [] - - def get_hooks(self) -> AgentHooks | None: - return self.capability.get_hooks() if self.capability else None - - def get_model_settings( # type: ignore[override] - self, ctx: RunContext[Any] | None = None - ) -> dict[str, Any]: - return self.capability.get_model_settings(ctx) if self.capability else {} - - -class IncludeToolReturnSchemas(BaseCapability): - """Capability that includes return value JSON schemas in tool definitions sent to the model.""" - - id: str | None = DEFAULT_INCLUDE_RETURN_SCHEMAS_ID - include_return_schema: bool = True - - def __init__( - self, - include_return_schema: bool = True, - *, - id: str = DEFAULT_INCLUDE_RETURN_SCHEMAS_ID, - **kwargs: Any, - ) -> None: - super().__init__(id=id, include_return_schema=include_return_schema, **kwargs) - - def prepare_tools( # type: ignore[override] - self, - ctx: RunContext[Any], - tools: list[Any], - ) -> list[Any]: - """Apply include_return_schema to all tool definitions.""" - for t in tools: - if hasattr(t, "include_return_schema"): - setattr(t, "include_return_schema", self.include_return_schema) - return tools - - -class SetToolMetadata(BaseCapability): - """Capability that merges custom key-value metadata pairs onto tool definitions.""" - - id: str | None = DEFAULT_SET_TOOL_METADATA_ID - capability: Any = None - metadata: dict[str, Any] = Field(default_factory=dict) - - def __init__( - self, - metadata: dict[str, Any] | None = None, - capability: BaseCapability | None = None, - *, - id: str = DEFAULT_SET_TOOL_METADATA_ID, - **kwargs: Any, - ) -> None: - cap = capability or kwargs.get("capability") - meta = metadata if metadata is not None else kwargs.get("metadata", {}) - super().__init__(id=id, capability=cap, metadata=meta, **kwargs) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - """Return tools from the wrapped capability with merged metadata.""" - if self.capability is None: - return [] - raw_tools = self.capability.get_tools() - tools_with_meta: list[AgentTool | Callable[..., Any]] = [] - for t in raw_tools: - if isinstance(t, Tool): - merged_meta = {**getattr(t, "metadata", {}), **self.metadata} - tools_with_meta.append( - Tool( - function=t.function, - name=t.name, - description=t.description, - parameters=t.parameters, - takes_ctx=t.takes_ctx, - timeout=t.timeout, - max_retries=t.max_retries, - requires_approval=t.requires_approval, - include_return_schema=t.include_return_schema, - metadata=merged_meta, - ) - ) - elif callable(t): - tools_with_meta.append(Tool.from_function(t, metadata=dict(self.metadata))) - else: - tools_with_meta.append(t) - return tools_with_meta - - def prepare_tools( # type: ignore[override] - self, - ctx: RunContext[Any], - tools: list[Any], - ) -> list[Any]: - """Merge metadata into any tools passed at runtime.""" - for t in tools: - if hasattr(t, "metadata") and isinstance(t.metadata, dict): - t.metadata.update(self.metadata) - return tools - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - return self.capability.get_system_prompt_additions(ctx) if self.capability else [] - - def get_hooks(self) -> AgentHooks | None: - return self.capability.get_hooks() if self.capability else None - - def get_model_settings( # type: ignore[override] - self, ctx: RunContext[Any] | None = None - ) -> dict[str, Any]: - return self.capability.get_model_settings(ctx) if self.capability else {} - - -class RaiseContentFilterError(BaseCapability): - """Capability that enforces raising a ContentFilterError whenever a model response is filtered.""" - - id: str | None = DEFAULT_RAISE_CONTENT_FILTER_ID - - def __init__( - self, - *, - id: str = DEFAULT_RAISE_CONTENT_FILTER_ID, - **kwargs: Any, - ) -> None: - super().__init__(id=id, **kwargs) - - def check_response(self, response: Any) -> None: - """Inspect model response and raise ContentFilterError if finish_reason is content_filter.""" - finish_reason = getattr(response, "finish_reason", None) - if finish_reason is None and isinstance(response, dict): - finish_reason = response.get("finish_reason") or response.get("stop_reason") - if str(finish_reason).lower() in ("content_filter", "safety", "recitation", "block"): - from devops_cli.exceptions.ai import ContentFilterError - - msg = "Model response was blocked or filtered by upstream content safety filter" - raise ContentFilterError(message=msg, body=response) - - -class ReinjectSystemPrompt(BaseCapability): - """Capability that ensures an agent's configured system prompt is present in message history.""" - - id: str | None = DEFAULT_REINJECT_SYSTEM_PROMPT_ID - replace_existing: bool = False - - def __init__( - self, - replace_existing: bool = False, - *, - id: str = DEFAULT_REINJECT_SYSTEM_PROMPT_ID, - **kwargs: Any, - ) -> None: - super().__init__(id=id, replace_existing=replace_existing, **kwargs) - - def reinject( - self, - messages: list[Any], - system_prompt: str, - ) -> list[Any]: - """Reinject system_prompt into the message history if missing or if replace_existing is True.""" - if not system_prompt or not system_prompt.strip(): - return messages - - has_system = False - filtered_messages: list[Any] = [] - - for m in messages: - is_sys = False - if isinstance(m, dict) and m.get("role") == "system": - is_sys = True - elif hasattr(m, "role") and getattr(m, "role") == "system": - is_sys = True - elif hasattr(m, "part_kind") and getattr(m, "part_kind") == "system-prompt": - is_sys = True - - if is_sys: - has_system = True - if not self.replace_existing: - filtered_messages.append(m) - else: - filtered_messages.append(m) - - if self.replace_existing or not has_system: - sys_msg: dict[str, str] = {"role": "system", "content": system_prompt.strip()} - return [sys_msg, *filtered_messages] - - return messages - - -class ProcessHistory(BaseCapability): - """Capability that intercepts and transforms message history before model execution.""" - - id: str | None = DEFAULT_PROCESS_HISTORY_ID - processor: Any = None - - def __init__( - self, - processor: Callable[..., Any] | None = None, - *, - id: str = DEFAULT_PROCESS_HISTORY_ID, - **kwargs: Any, - ) -> None: - super().__init__(id=id, processor=processor or kwargs.get("processor"), **kwargs) - - def process_history( - self, - messages: list[Any], - ctx: RunContext[Any] | None = None, - ) -> list[Any]: - """Apply the configured processor to transform or trim message history.""" - if not callable(self.processor): - return messages - - sig = inspect.signature(self.processor) - if len(sig.parameters) >= 2 and ctx is not None: - res = self.processor(ctx, messages) - elif len(sig.parameters) >= 2 and ctx is None: - res = self.processor(RunContext(), messages) - else: - res = self.processor(messages) - return res if res is not None else messages - - -class AgentStreamEvent(BaseModel): - """An event emitted during streaming model execution or tool invocation.""" - - event_kind: str = DEFAULT_AGENT_STREAM_EVENT_KIND - content: Any = None - metadata: dict[str, Any] = Field(default_factory=dict) - - -class ProcessEventStream(BaseCapability): - """Capability that intercepts, observes, or transforms the event stream during agent execution.""" - - id: str | None = DEFAULT_PROCESS_EVENT_STREAM_ID - handler: Any = None - - def __init__( - self, - handler: Callable[..., Any] | None = None, - *, - id: str = DEFAULT_PROCESS_EVENT_STREAM_ID, - **kwargs: Any, - ) -> None: - super().__init__(id=id, handler=handler or kwargs.get("handler"), **kwargs) - - async def handle_stream( - self, - events: Any, - ctx: RunContext[Any] | None = None, - ) -> Any: - """Forward events to handler or iterate through generator.""" - if not callable(self.handler): - return events - - sig = inspect.signature(self.handler) - if len(sig.parameters) >= 2 and ctx is not None: - res = self.handler(ctx, events) - elif len(sig.parameters) >= 2 and ctx is None: - res = self.handler(RunContext(), events) - else: - res = self.handler(events) - - if inspect.iscoroutine(res): - return await res - return res diff --git a/src/devops_cli/ai/common_tools.py b/src/devops_cli/ai/common_tools.py index 1e14c8c335..e07de93a03 100644 --- a/src/devops_cli/ai/common_tools.py +++ b/src/devops_cli/ai/common_tools.py @@ -274,19 +274,10 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # ============================================================================= -# SSRF Validation & Untrusted HTML Markdown Rendering +# Untrusted HTML Markdown Rendering # ============================================================================= -def is_private_ip_or_localhost(url_or_host: str) -> bool: - """Validate if a URL or hostname resolves to private/loopback/link-local space.""" - parsed = urllib.parse.urlparse(url_or_host) - host = parsed.hostname or url_or_host - from devops_cli.core.validation import is_loopback_or_private_host - - return is_loopback_or_private_host(host) - - class RenderedUntrustedPage(NamedTuple): """Structured result of untrusted web page rendering.""" @@ -732,7 +723,6 @@ def search_tavily(query: str) -> str: "exa_get_contents_tool", "exa_search_tool", "image_generation_tool", - "is_private_ip_or_localhost", "render_untrusted_page", "tavily_search", "tavily_search_tool", diff --git a/src/devops_cli/ai/format_prompt.py b/src/devops_cli/ai/format_prompt.py index 02924d92e9..6a448f034f 100644 --- a/src/devops_cli/ai/format_prompt.py +++ b/src/devops_cli/ai/format_prompt.py @@ -22,8 +22,6 @@ DEFAULT_XML_ITEM_TAG, DEFAULT_XML_METADATA_ROOT_TAG, DEFAULT_XML_NONE_STR, - DEFAULT_XML_PLAN_REMINDER_ITEM_TAG, - DEFAULT_XML_PLAN_REMINDER_ROOT_TAG, DEFAULT_XML_RAG_ITEM_TAG, DEFAULT_XML_RAG_ROOT_TAG, ) @@ -34,7 +32,6 @@ "format_examples_as_xml", "format_findings_as_xml", "format_metadata_as_xml", - "format_plan_reminder_as_xml", "format_prompt_data", "format_rag_context_as_xml", ) @@ -130,22 +127,6 @@ def format_findings_as_xml( ) -def format_plan_reminder_as_xml( - items: Iterable[Any], - root_tag: str = DEFAULT_XML_PLAN_REMINDER_ROOT_TAG, - item_tag: str = DEFAULT_XML_PLAN_REMINDER_ITEM_TAG, - indent: str | None = DEFAULT_XML_INDENT, -) -> str: - """Format plan task items into a structured XML reminder block.""" - task_list = list(items) - return format_as_xml( - obj=task_list, - root_tag=root_tag, - item_tag=item_tag, - indent=indent, - ) - - def format_metadata_as_xml( metadata: Mapping[str, Any], root_tag: str = DEFAULT_XML_METADATA_ROOT_TAG, diff --git a/src/devops_cli/ai/harness/__init__.py b/src/devops_cli/ai/harness/__init__.py index 4c70c120ec..e05c764fa3 100644 --- a/src/devops_cli/ai/harness/__init__.py +++ b/src/devops_cli/ai/harness/__init__.py @@ -1,103 +1,8 @@ -"""Pydantic AI Harness package providing modular capabilities, agents, and sandboxed environments.""" +"""Harness slots and skills.""" from __future__ import annotations -from devops_cli.ai.harness.agents import ( - Coder, - Macroscope, - MacroscopeIssue, - MacroscopeReview, - PlaywrightBrowser, - Researcher, - coder_agent, - researcher_agent, -) -from devops_cli.ai.harness.compaction import ( - Band, - CacheBustWarning, - CacheMark, - ClampOversizedMessages, - ClearToolResults, - CompactionReceipt, - ContextUsage, - DeduplicateFileReads, - FallbackCompaction, - LocalFileStore, - OverflowStore, - Passthrough, - ReportContextUsage, - SlidingWindowCompaction, - Spill, - Summarize, - SummarizingCompaction, - TieredCompaction, - ToolOutputLimits, - TranscriptHandleProvider, - Truncate, - TruncationStrategy, - WarnNearLimits, - WarnOnCacheBusts, - compact_now, - indented_json, - is_pinned, - json_lines, - pin, - reinject_pinned, -) -from devops_cli.ai.harness.constants import ( - DEFAULT_ADVISOR_INSTRUCTIONS, - DEFAULT_CODER_INSTRUCTIONS, - DEFAULT_DENIED_COMMANDS, - DEFAULT_MACROSCOPE_GUIDANCE, - DEFAULT_PLANNING_GUIDANCE, - DEFAULT_PLAYWRIGHT_GUIDANCE, - DEFAULT_PROTECTED_PATTERNS, - DEFAULT_RESEARCHER_INSTRUCTIONS, - DEFAULT_SUMMARIZING_INSTRUCTIONS, - INTERACTIVE_COMMANDS, - LLM_API_KEY_ENV_PATTERNS, - UNSUPPORTED_BEHAVIORAL_SKILL_FIELDS, - HarnessDeprecationWarning, -) -from devops_cli.ai.harness.conversation import ( - ConversationSearch, - ConversationSearchMatch, - HistorySource, - RunRecord, - SnapshotHistorySource, - bm25_rank, -) -from devops_cli.ai.harness.docs import ( - DEFAULT_PYAI_DOCS_TOPICS, - PyaiDocs, - PydanticAIDocs, -) -from devops_cli.ai.harness.filesystem import FileSystem -from devops_cli.ai.harness.memory import ( - FileStore, - InMemoryStore, - Memory, - MemoryFile, - MemoryMutationResult, - MemoryOperationConflictError, - MemorySearchResult, - MemoryStore, - SearchableMemoryStore, - SqliteMemoryStore, -) -from devops_cli.ai.harness.planning import ( - InMemoryPlanStore, - PlanEvent, - PlanEventEmitter, - PlanItem, - Planning, - PlanStatus, - PlanStore, - SqlitePlanStore, -) -from devops_cli.ai.harness.repo_context import AgentContextInventory, AssetRoot, RepoContext -from devops_cli.ai.harness.shell import Shell -from devops_cli.ai.harness.skills import ParsedSkill, Skills, normalize_skill_name +from devops_cli.ai.harness.skills import ParsedSkill, normalize_skill_name from devops_cli.ai.harness.slots import ( AgentHarness, BaseSlot, @@ -113,121 +18,21 @@ mark_tool_mutating, mark_tool_read_only, ) -from devops_cli.ai.harness.workflow import ( - MINIMUM_EFFORT_FLOOR, - Advisor, - AgentOverride, - ModelOption, - SubAgent, - SubAgents, - clamp_effort, -) __all__ = [ - "DEFAULT_ADVISOR_INSTRUCTIONS", - "DEFAULT_CODER_INSTRUCTIONS", - "DEFAULT_DENIED_COMMANDS", - "DEFAULT_MACROSCOPE_GUIDANCE", - "DEFAULT_PLANNING_GUIDANCE", - "DEFAULT_PLAYWRIGHT_GUIDANCE", - "DEFAULT_PROTECTED_PATTERNS", - "DEFAULT_PYAI_DOCS_TOPICS", - "DEFAULT_RESEARCHER_INSTRUCTIONS", - "DEFAULT_SUMMARIZING_INSTRUCTIONS", - "INTERACTIVE_COMMANDS", - "LLM_API_KEY_ENV_PATTERNS", - "MINIMUM_EFFORT_FLOOR", - "UNSUPPORTED_BEHAVIORAL_SKILL_FIELDS", - "Advisor", - "AgentContextInventory", "AgentHarness", - "AgentOverride", - "AssetRoot", - "Band", "BaseSlot", - "CacheBustWarning", - "CacheMark", - "ClampOversizedMessages", - "ClearToolResults", - "Coder", - "CompactionReceipt", - "ContextUsage", - "ConversationSearch", - "ConversationSearchMatch", - "DeduplicateFileReads", - "FallbackCompaction", - "FileStore", - "FileSystem", - "HarnessDeprecationWarning", - "HistorySource", - "InMemoryPlanStore", - "InMemoryStore", - "LocalFileStore", - "Macroscope", - "MacroscopeIssue", - "MacroscopeReview", - "Memory", - "MemoryFile", - "MemoryMutationResult", - "MemoryOperationConflictError", - "MemorySearchResult", - "MemoryStore", - "ModelOption", "ModelSlot", - "OverflowStore", "ParsedSkill", - "Passthrough", - "PlanEvent", - "PlanEventEmitter", - "PlanItem", - "PlanStatus", - "PlanStore", - "Planning", - "PlaywrightBrowser", - "PyaiDocs", - "PydanticAIDocs", - "RepoContext", - "ReportContextUsage", - "Researcher", - "RunRecord", - "SearchableMemoryStore", - "Shell", "SkillSlot", - "Skills", - "SlidingWindowCompaction", "SlotState", "SlotType", - "SnapshotHistorySource", - "Spill", - "SqliteMemoryStore", - "SqlitePlanStore", - "SubAgent", "SubAgentResult", "SubAgentSlot", - "SubAgents", - "Summarize", - "SummarizingCompaction", "SynthesisTier", - "TieredCompaction", "TieredExecutionResult", - "ToolOutputLimits", "ToolSlot", - "TranscriptHandleProvider", - "Truncate", - "TruncationStrategy", - "WarnNearLimits", - "WarnOnCacheBusts", - "bm25_rank", - "clamp_effort", - "coder_agent", - "compact_now", - "indented_json", - "is_pinned", - "json_lines", "mark_tool_mutating", "mark_tool_read_only", "normalize_skill_name", - "pin", - "reinject_pinned", - "researcher_agent", ] diff --git a/src/devops_cli/ai/harness/agents.py b/src/devops_cli/ai/harness/agents.py deleted file mode 100644 index 41b6fe996b..0000000000 --- a/src/devops_cli/ai/harness/agents.py +++ /dev/null @@ -1,586 +0,0 @@ -"""Preconfigured Coder, Researcher, Macroscope, and Browser agents.""" - -from __future__ import annotations - -import json -import logging -import re -import shutil -import subprocess -from collections.abc import Callable -from pathlib import Path -from typing import Any - -from pydantic import BaseModel, ConfigDict, Field -from pydantic_ai.tools import RunContext - -from devops_cli.ai.agents.agent import PydanticAgent -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.ai.common_tools import duckduckgo_search_tool, web_fetch_tool -from devops_cli.ai.harness.constants import ( - DEFAULT_CODER_INSTRUCTIONS, - DEFAULT_MACROSCOPE_GUIDANCE, - DEFAULT_PLAYWRIGHT_GUIDANCE, - DEFAULT_RESEARCHER_INSTRUCTIONS, -) -from devops_cli.ai.harness.filesystem import FileSystem -from devops_cli.ai.harness.planning import Planning -from devops_cli.ai.harness.repo_context import RepoContext -from devops_cli.ai.harness.shell import Shell -from devops_cli.core.dns_names import ConfiguredDomain, is_at_or_under - -logger = logging.getLogger(__name__) - - -class Coder(BaseCapability): - """Composite harness stack for autonomous coding agents.""" - - id: str | None = "coder_harness" - workspace_dir: Path = Field(default_factory=lambda: Path(".")) - allowed_commands: list[str] = Field( - default_factory=lambda: [ - "git", - "rg", - "grep", - "find", - "ls", - "cat", - "sed", - "head", - "tail", - "python", - "uv", - "pytest", - "ruff", - "make", - ] - ) - - def __init__( - self, workspace_dir: Path | str = ".", allowed_commands: list[str] | None = None - ) -> None: - p = Path(workspace_dir) - cmds = ( - allowed_commands - if allowed_commands is not None - else [ - "git", - "rg", - "grep", - "find", - "ls", - "cat", - "sed", - "head", - "tail", - "python", - "uv", - "pytest", - "ruff", - "make", - ] - ) - super().__init__(workspace_dir=p, allowed_commands=cmds) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - fs = FileSystem(root=self.workspace_dir) - sh = Shell(cwd=self.workspace_dir, allowed_commands=self.allowed_commands) - plan = Planning() - return fs.get_tools() + sh.get_tools() + plan.get_tools() - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - repo = RepoContext(workspace_dir=self.workspace_dir) - return repo.get_system_prompt_additions(ctx) + ["Coding Agent Harness Stack active."] - - -def coder_agent( - client: Any = None, - *, - name: str = "coder", - instructions: str = DEFAULT_CODER_INSTRUCTIONS, - workspace_dir: Path | str = ".", - allowed_commands: list[str] | None = None, -) -> PydanticAgent[Any]: - """Create a configured Coder agent instance with full harness capabilities.""" - return PydanticAgent( - client=client, - name=name, - system_prompt=instructions, - capabilities=[Coder(workspace_dir=workspace_dir, allowed_commands=allowed_commands)], - ) - - -class Researcher(BaseCapability): - """Composite harness stack for autonomous web and document research agents.""" - - id: str | None = "researcher_harness" - allowed_domains: list[ConfiguredDomain] | None = None - instructions: str | None = DEFAULT_RESEARCHER_INSTRUCTIONS - - def __init__( - self, - allowed_domains: list[str] | None = None, - instructions: str | None = DEFAULT_RESEARCHER_INSTRUCTIONS, - ) -> None: - super().__init__(allowed_domains=allowed_domains, instructions=instructions) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - fetch = web_fetch_tool(allowed_domains=self.allowed_domains) - search = duckduckgo_search_tool() - return [fetch, search] - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - additions = [ - "Researcher Agent Harness Stack active (DuckDuckGo search + SSRF-safe Web Fetch)." - ] - if self.instructions: - additions.append(self.instructions) - return additions - - -def researcher_agent( - client: Any = None, - *, - name: str = "researcher", - instructions: str | None = DEFAULT_RESEARCHER_INSTRUCTIONS, - allowed_domains: list[str] | None = None, -) -> PydanticAgent[Any]: - """Create a configured Researcher agent instance with web search and fetch capabilities.""" - return PydanticAgent( - client=client, - name=name, - system_prompt=instructions or "", - capabilities=[Researcher(allowed_domains=allowed_domains, instructions=instructions)], - ) - - -class MacroscopeIssue(BaseModel): - """A single finding streamed by macroscope codereview.""" - - model_config = ConfigDict(extra="ignore") - - issue_id: str = "" - sequence: int = 0 - path: str = "" - line: int = 1 - severity: str = "medium" - category: str = "quality" - body: str = "" - - -class MacroscopeReview(BaseModel): - """The result of one macroscope codereview execution.""" - - review_id: str | None = None - status: str = "completed" - findings: list[MacroscopeIssue] = Field(default_factory=list) - - -def _parse_macroscope_output( - output: str, default_status: str -) -> tuple[str | None, str, list[MacroscopeIssue]]: - """Parse JSON stream output from macroscope execution.""" - findings: list[MacroscopeIssue] = [] - review_id: str | None = None - status = default_status - - for raw_line in output.splitlines(): - line = raw_line.strip() - if not line: - continue - try: - data = json.loads(line) - ev_type = data.get("type") - if ev_type == "review_id": - review_id = data.get("id") - elif ev_type == "issue_event": - findings.append(MacroscopeIssue.model_validate(data.get("issue", {}))) - elif ev_type == "issue_status": - status = data.get("status", status) - except Exception: - continue - return review_id, status, findings - - -def _format_macroscope_review(review: MacroscopeReview) -> str: - """Format MacroscopeReview findings as canonical markdown.""" - if not review.findings: - return f"Macroscope review {review.review_id or ''} finished with status: {review.status}. 0 issues found." - formatted = [ - f"Macroscope Review ({review.review_id or 'unknown'}) - Status: {review.status} ({len(review.findings)} findings):" - ] - formatted.extend( - f"- [{f.severity.upper()}] {f.path}:{f.line} ({f.category}): {f.body}" - for f in review.findings - ) - return "\n".join(formatted) - - -_DIFF_BASE_PATTERN: re.Pattern[str] = re.compile(r"^[a-zA-Z0-9_\-./~^]+$") - - -def _is_safe_diff_base(diff_base: str) -> bool: - """Predicate checking whether a diff base reference is safe against path traversal.""" - if not diff_base: - return True - if ( - ".." in diff_base - or diff_base.startswith(("/", "\\")) - or Path(diff_base).is_absolute() - or not _DIFF_BASE_PATTERN.match(diff_base) - ): - return False - return True - - -def _validate_diff_base(diff_base: str | None) -> str | None: - """Validate diff base reference against path traversal and malicious characters.""" - if diff_base and not _is_safe_diff_base(diff_base): - return ( - f"Invalid base reference '{diff_base}': " - "path traversal or invalid characters blocked by security policy." - ) - return None - - -class Macroscope(BaseCapability): - """Capability running Macroscope CLI code reviews and feeding structured findings to the agent.""" - - id: str | None = "macroscope" - base: str | None = None - command: str = "macroscope" - cwd: Path = Field(default_factory=lambda: Path(".")) - timeout: float = 600.0 - guidance: str | None = DEFAULT_MACROSCOPE_GUIDANCE - - def __init__( - self, - base: str | None = None, - *, - command: str = "macroscope", - cwd: Path | str = ".", - timeout: float = 600.0, - guidance: str | None = DEFAULT_MACROSCOPE_GUIDANCE, - ) -> None: - p = Path(cwd) - super().__init__( - base=base, - command=command, - cwd=p, - timeout=timeout, - guidance=guidance, - ) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - def run_macroscope_review(base: str | None = None) -> str: - """Run macroscope codereview and return findings.""" - diff_base = base or self.base - if err := _validate_diff_base(diff_base): - return err - - bin_path = shutil.which(self.command) - if not bin_path: - return ( - f"Macroscope CLI '{self.command}' not found. " - "Install via: curl -sSL https://raw.githubusercontent.com/prassoai/macroscope-local/main/install.sh | bash" - ) - - cmd = [self.command, "codereview", "--raw"] - if diff_base: - cmd.extend(["--base", diff_base]) - - try: - proc = subprocess.run( - cmd, - cwd=str(self.cwd.resolve()), - capture_output=True, - text=True, - timeout=self.timeout, - check=False, - ) - output = proc.stdout or "" - def_status = "completed" if proc.returncode == 0 else "failed" - review_id, status, findings = _parse_macroscope_output(output, def_status) - review = MacroscopeReview(review_id=review_id, status=status, findings=findings) - return _format_macroscope_review(review) - except subprocess.TimeoutExpired: - return f"Macroscope review timed out after {self.timeout}s" - except Exception as exc: - return f"Macroscope review error: {exc}" - - return [ - Tool.from_function( - run_macroscope_review, - name="run_macroscope_review", - description="Run macroscope codereview on the repository and return structured findings.", - ) - ] - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - additions = ["Macroscope Code Review Capability enabled."] - if self.guidance: - additions.append(self.guidance) - return additions - - -def _is_allowed_browser_host(host: str, allowed_domains: list[str]) -> bool: - """Return True when host matches any allowed domain under DNS label rules.""" - import dns.exception - - if not host: - return False - try: - return any(is_at_or_under(host, d) for d in allowed_domains) - except dns.exception.DNSException: - return False - - -def _validate_browser_navigation( - url: str, - *, - block_private_addresses: bool, - allowed_domains: list[str] | None, -) -> str | None: - """Return an error message if browser navigation to url is blocked by egress policy.""" - from urllib.parse import urlsplit - - from devops_cli.ai.common_tools import is_private_ip_or_localhost - - parsed = urlsplit(url) - if parsed.scheme.lower() not in ("http", "https"): - return f"Navigation blocked: Unsupported URL scheme '{parsed.scheme}'. Only http and https are allowed." - if block_private_addresses and is_private_ip_or_localhost(url): - return f"Egress blocked: Access to private/loopback URL '{url}' is forbidden." - if allowed_domains: - parsed_host = parsed.hostname or "" - if not _is_allowed_browser_host(parsed_host, allowed_domains): - allowed_set = {d.lower().strip() for d in allowed_domains} - return f"Egress blocked: Host '{parsed_host}' from URL '{url}' is not in allowed domains: {sorted(allowed_set)}." - return None - - -class PlaywrightBrowser(BaseCapability): - """Capability managing a headless Chromium browser instance via Playwright.""" - - id: str | None = "playwright_browser" - headless: bool = True - allowed_domains: list[ConfiguredDomain] | None = None - block_private_addresses: bool = True - screenshot_on_navigate: bool = False - max_content_tokens: int = 4000 - action_timeout_ms: int = 5000 - navigation_timeout_ms: int = 60000 - chromium_sandbox: bool = True - auto_install_chromium: bool = False - storage_state: Any = None - cdp_url: str | None = None - guidance: str | None = DEFAULT_PLAYWRIGHT_GUIDANCE - - def __init__( - self, - *, - headless: bool = True, - allowed_domains: list[str] | None = None, - block_private_addresses: bool = True, - screenshot_on_navigate: bool = False, - max_content_tokens: int = 4000, - action_timeout_ms: int = 5000, - navigation_timeout_ms: int = 60000, - chromium_sandbox: bool = True, - auto_install_chromium: bool = False, - storage_state: Any = None, - cdp_url: str | None = None, - guidance: str | None = DEFAULT_PLAYWRIGHT_GUIDANCE, - ) -> None: - super().__init__( - headless=headless, - allowed_domains=allowed_domains, - block_private_addresses=block_private_addresses, - screenshot_on_navigate=screenshot_on_navigate, - max_content_tokens=max_content_tokens, - action_timeout_ms=action_timeout_ms, - navigation_timeout_ms=navigation_timeout_ms, - chromium_sandbox=chromium_sandbox, - auto_install_chromium=auto_install_chromium, - storage_state=storage_state, - cdp_url=cdp_url, - guidance=guidance, - ) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 - def navigate(url: str, timeout_ms: int | None = None) -> str: - """Navigate to a URL and return title, URL, and visible page text.""" - blocked = _validate_browser_navigation( - url, - block_private_addresses=self.block_private_addresses, - allowed_domains=self.allowed_domains, - ) - if blocked: - return blocked - return f"Navigated to {url}. Title: Page Title. Content loaded." - - def snapshot(timeout_ms: int | None = None) -> str: - """Return the accessibility tree snapshot with aria-ref handles.""" - return "RootWebArea [aria-ref=e1] title='Page Title'\n heading 'Welcome' [aria-ref=e2]\n button 'Submit' [aria-ref=e3]" - - def click(selector: str, timeout_ms: int | None = None) -> str: - """Click an element matching CSS selector, aria-ref, or coordinates.""" - return f"Clicked element '{selector}'." - - def type_text( - selector: str, text: str, sequential: bool = False, timeout_ms: int | None = None - ) -> str: - """Type text into an input element.""" - return f"Typed '{text}' into '{selector}'." - - def press_key(key: str, selector: str | None = None, timeout_ms: int | None = None) -> str: - """Press a keyboard key.""" - return f"Pressed key '{key}' on {selector or 'active element'}." - - def select_option(selector: str, values: list[str], timeout_ms: int | None = None) -> str: - """Select option(s) in a dropdown select element.""" - return f"Selected options {values} in '{selector}'." - - def hover(selector: str, timeout_ms: int | None = None) -> str: - """Hover over an element to reveal tooltips or hover menus.""" - return f"Hovered over '{selector}'." - - def wait_for( - selector: str | None = None, - text: str | None = None, - gone: bool = False, - timeout_ms: int | None = None, - ) -> str: - """Wait for an element or text to appear or disappear.""" - target = selector or text or "element" - state = "disappeared" if gone else "appeared" - return f"Waited until {target} {state}." - - def screenshot(full_page: bool = False, timeout_ms: int | None = None) -> str: - """Take a screenshot of the current page viewport or full page.""" - return "Screenshot captured (viewport)." - - def get_text(selector: str | None = None, timeout_ms: int | None = None) -> str: - """Get visible text from the page or a specific selector.""" - return "Page text content extracted." - - def scroll( - direction: str, - x: int | None = None, - y: int | None = None, - timeout_ms: int | None = None, - ) -> str: - """Scroll the page in a direction (up, down, top, bottom).""" - return f"Scrolled page {direction}." - - def go_back(timeout_ms: int | None = None) -> str: - """Navigate back in history.""" - return "Navigated back." - - def go_forward(timeout_ms: int | None = None) -> str: - """Navigate forward in history.""" - return "Navigated forward." - - def execute_js(script: str, timeout_ms: int | None = None) -> str: - """Execute a JavaScript snippet in the page context.""" - return f"Script executed: {script[:50]}..." - - def console_messages(errors_only: bool = False) -> str: - """Retrieve captured browser console log messages.""" - return "Console logs: 0 errors." - - def tabs(action: str = "list", index: int | None = None) -> str: - """Manage browser tabs (list, select, close, new).""" - return f"Tabs action '{action}' performed (tab index: {index or 0})." - - def handle_next_dialog(accept: bool, prompt_text: str | None = None) -> str: - """Configure handler for the next browser alert/confirm/prompt dialog.""" - return f"Next dialog configured: accept={accept}, text={prompt_text}." - - def network_requests(url_contains: str | None = None, errors_only: bool = False) -> str: - """Retrieve network requests recorded during page lifecycle.""" - return "Network requests: 200 OK (0 failed)." - - return [ - Tool.from_function( - navigate, name="navigate", description="Navigate to a URL and return visible text." - ), - Tool.from_function( - snapshot, - name="snapshot", - description="Return accessibility tree snapshot with aria-ref handles.", - ), - Tool.from_function( - click, - name="click", - description="Click an element matching selector or aria-ref.", - ), - Tool.from_function( - type_text, - name="type_text", - description="Type text into an input element.", - ), - Tool.from_function(press_key, name="press_key", description="Press a keyboard key."), - Tool.from_function( - select_option, - name="select_option", - description="Select dropdown options.", - ), - Tool.from_function(hover, name="hover", description="Hover over an element."), - Tool.from_function( - wait_for, - name="wait_for", - description="Wait for an element or text to appear/disappear.", - ), - Tool.from_function( - screenshot, - name="screenshot", - description="Take a screenshot of the page.", - ), - Tool.from_function( - get_text, - name="get_text", - description="Get text from page or element.", - ), - Tool.from_function(scroll, name="scroll", description="Scroll page in a direction."), - Tool.from_function(go_back, name="go_back", description="Navigate back in history."), - Tool.from_function( - go_forward, name="go_forward", description="Navigate forward in history." - ), - Tool.from_function( - execute_js, - name="execute_js", - description="Execute JavaScript snippet.", - ), - Tool.from_function( - console_messages, - name="console_messages", - description="Get console log messages.", - ), - Tool.from_function(tabs, name="tabs", description="Manage browser tabs."), - Tool.from_function( - handle_next_dialog, - name="handle_next_dialog", - description="Handle next JavaScript dialog.", - ), - Tool.from_function( - network_requests, - name="network_requests", - description="Get recorded network requests.", - ), - ] - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - additions = ["Playwright Browser Capability enabled."] - if self.guidance: - additions.append(self.guidance) - return additions - - -Coder.model_rebuild() -Researcher.model_rebuild() -MacroscopeIssue.model_rebuild() -MacroscopeReview.model_rebuild() -Macroscope.model_rebuild() -PlaywrightBrowser.model_rebuild() diff --git a/src/devops_cli/ai/harness/compaction.py b/src/devops_cli/ai/harness/compaction.py deleted file mode 100644 index fb6af021f3..0000000000 --- a/src/devops_cli/ai/harness/compaction.py +++ /dev/null @@ -1,1007 +0,0 @@ -"""Compaction strategies and context usage management.""" - -from __future__ import annotations - -import json -import logging -import os -import re -import tempfile -import time -import uuid -import warnings -from collections import OrderedDict -from collections.abc import Callable, Mapping, Sequence -from datetime import timedelta -from enum import StrEnum -from pathlib import Path -from typing import Any, Protocol, runtime_checkable - -from pydantic import BaseModel, ConfigDict, Field -from pydantic_ai.tools import RunContext - -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.ai.harness.constants import DEFAULT_SUMMARIZING_INSTRUCTIONS -from devops_cli.exceptions.ai import HarnessValidationError -from devops_cli.models.ai import ChatMessage - -logger = logging.getLogger(__name__) - - -class TruncationStrategy(StrEnum): - """Strategies for clamping oversized tool return text.""" - - head = "head" - tail = "tail" - head_tail = "head_tail" - - -class Passthrough(BaseModel): - """No-op reduction action leaving matching returns untouched.""" - - model_config = ConfigDict(extra="ignore") - - -_TRUNCATION_FORMATTERS: dict[str, Callable[[str, int], str]] = { - "head": lambda t, m: t[:m] + f"\n\n[... {len(t) - m} characters truncated ...]", - "tail": lambda t, m: f"[... {len(t) - m} characters truncated ...]\n\n" + t[-m:], -} - - -def _truncate_head_tail(text: str, max_chars: int) -> str: - half = max_chars // 2 - return ( - text[:half] - + f"\n\n[... {len(text) - max_chars} characters truncated ...]\n\n" - + text[-half:] - ) - - -class Truncate(BaseModel): - """Clamps return text to a character budget.""" - - model_config = ConfigDict(extra="ignore") - - max_chars: int = 5000 - strategy: TruncationStrategy | str = TruncationStrategy.head_tail - then: Any | None = None - - def reduce(self, text: str) -> str: - """Clamp text according to strategy.""" - if len(text) <= self.max_chars: - return text - strat = ( - self.strategy.value - if isinstance(self.strategy, TruncationStrategy) - else str(self.strategy) - ) - formatter = _TRUNCATION_FORMATTERS.get(strat, _truncate_head_tail) - return formatter(text, self.max_chars) - - -@runtime_checkable -class OverflowStore(Protocol): - """Protocol for persisting spilled tool outputs.""" - - def write(self, key: str, data: bytes) -> str: ... - def read(self, handle: str) -> bytes: ... - - -_MAX_OVERFLOW_FALLBACK_ENTRIES = 128 -_OVERFLOW_MEMORY_FALLBACK: OrderedDict[str, bytes] = OrderedDict() - - -def reset_overflow_memory_fallback() -> None: - """Clear the in-memory overflow fallback store.""" - _OVERFLOW_MEMORY_FALLBACK.clear() - - -class LocalFileStore(BaseModel): - """Filesystem-backed store for spilled tool return payloads.""" - - model_config = ConfigDict(extra="ignore") - - base_dir: Path = Field( - default_factory=lambda: Path( - os.environ.get( - "DEVOPS_CLI_OVERFLOW_DIR", - str(Path(tempfile.gettempdir()) / "devops_cli_overflow"), - ) - ) - ) - cleanup_after: timedelta | None = None - - def __init__( - self, - base_dir: Path | str | None = None, - cleanup_after: timedelta | None = None, - ) -> None: - p = ( - Path(base_dir) - if base_dir is not None - else Path( - os.environ.get( - "DEVOPS_CLI_OVERFLOW_DIR", - str(Path(tempfile.gettempdir()) / "devops_cli_overflow"), - ) - ) - ) - super().__init__(base_dir=p, cleanup_after=cleanup_after) - try: - self.base_dir.mkdir(parents=True, exist_ok=True) - os.chmod(self.base_dir, 0o700) - except Exception: - pass - - def write(self, key: str, data: bytes) -> str: - """Persist data under key and return handle.""" - sanitized_key = re.sub(r"[^a-zA-Z0-9_\-\.]", "_", key) - handle = f"spill_{sanitized_key}_{uuid.uuid4().hex[:8]}" - try: - target = self.base_dir / handle - target.write_bytes(data) - return handle - except Exception: - if len(_OVERFLOW_MEMORY_FALLBACK) >= _MAX_OVERFLOW_FALLBACK_ENTRIES: - _OVERFLOW_MEMORY_FALLBACK.popitem(last=False) - _OVERFLOW_MEMORY_FALLBACK[handle] = data - return handle - - def read(self, handle: str) -> bytes: - """Read data for handle.""" - if handle in _OVERFLOW_MEMORY_FALLBACK: - return _OVERFLOW_MEMORY_FALLBACK[handle] - sanitized = re.sub(r"[^a-zA-Z0-9_\-\.]", "_", handle) - target = self.base_dir / sanitized - if target.exists(): - return target.read_bytes() - raise FileNotFoundError(f"Spill handle not found: {handle}") - - def read_slice( - self, - handle: str, - offset: int = 0, - limit: int = 100, - from_end: bool = False, - pattern: str | None = None, - ) -> str: - """Read a line-bounded slice from the spilled payload.""" - data = self.read(handle) - text = data.decode("utf-8", errors="replace") - lines = text.splitlines() - - if pattern: - lines = [line for line in lines if pattern in line] - - if from_end: - selected = lines[max(0, len(lines) - limit) :] - else: - selected = lines[max(0, offset) : max(0, offset) + limit] - - return "\n".join(selected) - - -class Spill(BaseModel): - """Losslessly persists tool return to overflow store and returns handle + preview.""" - - model_config = ConfigDict(extra="ignore") - - max_chars: int = 10000 - store: Any | None = None - then: Any | None = None - - def reduce(self, text: str, tool_name: str = "tool", tool_call_id: str = "") -> str: - """Spill payload to store and return handle preview.""" - resolved_store = self.store or LocalFileStore() - key = f"{tool_name}_{tool_call_id}" if tool_call_id else tool_name - try: - handle = resolved_store.write(key, text.encode("utf-8")) - preview = text[:500].replace("\n", " ") - lines_count = len(text.splitlines()) - return ( - f"[Tool output spilled: {len(text)} chars ({lines_count} lines)]\n" - f"Handle: {handle}\n" - f"Preview: {preview}...\n" - f"Use `read_tool_result(handle='{handle}', offset=0, limit=100)` to page through output." - ) - except Exception: - if self.then and hasattr(self.then, "reduce"): - return str(self.then.reduce(text)) - return text[: self.max_chars] - - -class Summarize(BaseModel): - """Size-gated LLM summary of tool output.""" - - model_config = ConfigDict(extra="ignore") - - summary_model: Any | None = None - then: Any | None = None - - def reduce(self, text: str, tool_name: str = "tool") -> str: - """Summarize text output.""" - lines = text.splitlines() - preview_lines = lines[:10] - return ( - f"[Summary of {tool_name} output ({len(text)} chars, {len(lines)} lines)]:\n" - + "\n".join(preview_lines) - + ("\n..." if len(lines) > 10 else "") - ) - - -class Band(BaseModel): - """A size threshold and associated reduction action.""" - - model_config = ConfigDict(extra="ignore") - - over: int - action: Any - - -def indented_json(val: Any) -> str: - """Format structured value as indented JSON (one field per line).""" - - return json.dumps(val, indent=2, ensure_ascii=False) - - -def json_lines(val: Any) -> str: - """Format structured list or record as JSON Lines (one record per line).""" - - if isinstance(val, (list, tuple)): - return "\n".join(json.dumps(item, ensure_ascii=False) for item in val) - return json.dumps(val, ensure_ascii=False) - - -class ToolOutputLimits(BaseCapability): - """Capability managing tool output limits with Truncate, Spill, and Summarize bands.""" - - id: str | None = "tool_output_limits" - max_chars: int = 15000 - bands: list[Band] = Field( - default_factory=lambda: [Band(over=10000, action=Spill(then=Truncate(max_chars=5000)))] - ) - per_tool: dict[str, list[Band]] = Field(default_factory=dict) - tool_filter: list[str] | set[str] | None = None - over_tokens: bool = False - tokenizer: Any | None = None - store: Any | None = None - strip_ansi: bool = False - summary_prompt: str = "Summarize {tool_name} output: {output}" - serializer: Any | None = None - - def __init__( - self, - bands: Sequence[Band] | None = None, - *, - per_tool: Mapping[str, Sequence[Band]] | None = None, - tool_filter: Sequence[str] | set[str] | None = None, - max_chars: int = 15000, - over_tokens: bool = False, - tokenizer: Any | None = None, - store: Any | None = None, - strip_ansi: bool = False, - summary_prompt: str = "Summarize {tool_name} output: {output}", - serializer: Any | None = None, - id: str = "tool_output_limits", - ) -> None: - resolved_bands = ( - list(bands) - if bands is not None - else [Band(over=10000, action=Spill(store=store, then=Truncate(max_chars=5000)))] - ) - resolved_per_tool = ( - {k: list(v) for k, v in per_tool.items()} if per_tool is not None else {} - ) - super().__init__( - id=str(id or "tool_output_limits"), - max_chars=max_chars, - bands=resolved_bands, - per_tool=resolved_per_tool, - tool_filter=list(tool_filter) if tool_filter is not None else None, - over_tokens=over_tokens, - tokenizer=tokenizer, - store=store, - strip_ansi=strip_ansi, - summary_prompt=summary_prompt, - serializer=serializer, - ) - - def reduce_output( # noqa: C901 - self, tool_name: str, output: Any, tool_call_id: str = "" - ) -> tuple[Any, bool]: - """Measure tool return size and apply winning reduction band.""" - if tool_name == "read_tool_result": - return output, False - - if self.tool_filter is not None and tool_name not in self.tool_filter: - return output, False - - # Serialize if structured - text = output - if not isinstance(output, (str, bytes)): - if self.serializer and callable(self.serializer): - try: - text = self.serializer(output) - except Exception: - text = str(output) - else: - import json - - try: - text = json.dumps(output, ensure_ascii=False) - except Exception: - text = str(output) - - if isinstance(text, bytes): - return text, False - - if self.strip_ansi and isinstance(text, str): - text = re.sub(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", text) - - measured_size = ( - self.tokenizer(text) - if (self.over_tokens and self.tokenizer and callable(self.tokenizer)) - else (len(text) // 4 if self.over_tokens else len(text)) - ) - - active_bands = self.per_tool.get(tool_name, self.bands) - sorted_bands = sorted(active_bands, key=lambda b: b.over, reverse=True) - - for band in sorted_bands: - if measured_size >= band.over: - return self._reduce_band_action(band.action, text, tool_name, tool_call_id) - - if len(text) > self.max_chars: - return Truncate(max_chars=self.max_chars).reduce(text), True - - return text, False - - def _reduce_band_action( - self, action: Any, text: str, tool_name: str, tool_call_id: str | None - ) -> tuple[Any, bool]: - """Apply a reduction action (Truncate, Spill, Summarize, Passthrough, or callable).""" - if isinstance(action, Passthrough): - return text, False - if isinstance(action, Truncate): - return action.reduce(text), True - if isinstance(action, Spill): - return action.reduce(text, tool_name=tool_name, tool_call_id=tool_call_id or ""), True - if isinstance(action, Summarize): - return action.reduce(text, tool_name=tool_name), True - if callable(action): - return action(text), True - return text, False - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - """Expose the read_tool_result tool for paging back into spilled outputs.""" - store = self.store or LocalFileStore() - - def read_tool_result( - handle: str, - offset: int = 0, - limit: int = 100, - from_end: bool = False, - pattern: str | None = None, - ) -> str: - """Page through a spilled tool result by handle, line offset, and limit.""" - try: - clamped_limit = min(max(1, limit), 500) - clamped_offset = max(0, offset) - return store.read_slice( - handle=handle, - offset=clamped_offset, - limit=clamped_limit, - from_end=from_end, - pattern=pattern, - ) - except Exception as e: - return f"Error reading spill handle '{handle}': {e}" - - return [ - Tool.from_function( - read_tool_result, - name="read_tool_result", - description="Read a slice of a spilled tool return payload by handle, offset, and line limit.", - ) - ] - - -class ContextUsage(BaseModel): - """Token and message count metrics for conversation context.""" - - model_config = ConfigDict(extra="ignore") - - total_tokens: int = 0 - context_limit: int = 128000 - context_fraction: float = 0.0 - message_count: int = 0 - - -def pin(item: Any) -> Any: - """Pin a message or content part so that compaction never discards or modifies it.""" - if hasattr(item, "_pinned"): - item._pinned = True - elif isinstance(item, dict): - item.setdefault("metadata", {})["pinned"] = True - else: - try: - setattr(item, "_pinned", True) - except Exception: - pass - return item - - -def is_pinned(item: Any) -> bool: - """Check whether a message or content part is pinned.""" - if getattr(item, "_pinned", False): - return True - if isinstance(item, dict): - return bool(item.get("metadata", {}).get("pinned")) - if hasattr(item, "metadata") and isinstance(item.metadata, dict): - return bool(item.metadata.get("pinned")) - return False - - -def reinject_pinned(messages: list[Any], pinned_items: Sequence[Any]) -> list[Any]: - """Ensure all pinned messages are present in the compacted message history.""" - existing_ids = {getattr(m, "id", getattr(m, "tool_call_id", str(m))) for m in messages} - result = list(messages) - for p in pinned_items: - p_id = getattr(p, "id", getattr(p, "tool_call_id", str(p))) - if p_id not in existing_ids: - result.insert(1 if len(result) > 1 else 0, p) - existing_ids.add(p_id) - return result - - -class ClampOversizedMessages(BaseCapability): - """Capability that head/tail-truncates single oversized message parts.""" - - id: str | None = "clamp_oversized_messages" - max_chars: int = 20000 - - def compact_messages(self, messages: list[Any]) -> list[Any]: - """Truncate individual messages whose length exceeds max_chars.""" - compacted: list[Any] = [] - for msg in messages: - if is_pinned(msg): - compacted.append(msg) - continue - - content = getattr(msg, "content", msg if isinstance(msg, str) else "") - if isinstance(content, str) and len(content) > self.max_chars: - head = content[: self.max_chars // 2] - tail = content[-(self.max_chars // 2) :] - omitted = len(content) - self.max_chars - new_text = ( - f"{head}\n\n[... Truncated content: {omitted} characters omitted ...]\n\n{tail}" - ) - if hasattr(msg, "model_copy"): - compacted.append(msg.model_copy(update={"content": new_text})) - elif isinstance(msg, dict): - c = dict(msg) - c["content"] = new_text - compacted.append(c) - else: - compacted.append(new_text) - else: - compacted.append(msg) - return compacted - - -class ClearToolResults(BaseCapability): - """Capability managing context compaction by clearing older tool result messages in place.""" - - id: str | None = "clear_tool_results" - max_fraction: float = 0.7 - keep_pairs: int = 2 - - def compact_messages(self, messages: list[Any]) -> list[Any]: - """Clear older tool outputs while keeping the most recent keep_pairs intact.""" - tool_indices: list[int] = [] - for i, msg in enumerate(messages): - role = getattr(msg, "role", msg.get("role") if isinstance(msg, dict) else "") - content = getattr(msg, "content", msg.get("content") if isinstance(msg, dict) else "") - name = getattr(msg, "name", msg.get("name") if isinstance(msg, dict) else "") - if ( - role in {"tool", "function"} - or getattr(msg, "tool_call_id", None) - or (isinstance(msg, dict) and "tool_call_id" in msg) - or "[tool result:" in str(content).lower() - or bool(name) - ): - if not is_pinned(msg): - tool_indices.append(i) - - if len(tool_indices) <= self.keep_pairs: - return list(messages) - - indices_to_clear = set(tool_indices[: -self.keep_pairs]) - compacted: list[Any] = [] - for i, msg in enumerate(messages): - if i in indices_to_clear: - name = getattr( - msg, "name", msg.get("name", "tool") if isinstance(msg, dict) else "tool" - ) - cleared_text = f"[Cleared tool result: {name}]" - if hasattr(msg, "model_copy"): - compacted.append(msg.model_copy(update={"content": cleared_text})) - elif isinstance(msg, dict): - c = dict(msg) - c["content"] = cleared_text - compacted.append(c) - else: - compacted.append(cleared_text) - else: - compacted.append(msg) - return compacted - - -class DeduplicateFileReads(BaseCapability): - """Capability that blanks superseded file read results when a newer read of the same file exists.""" - - id: str | None = "deduplicate_file_reads" - file_read_tools: set[str] = Field( - default_factory=lambda: {"read_file", "view_file", "cat", "get_file", "read_path"} - ) - - def compact_messages(self, messages: list[Any]) -> list[Any]: - """Drop duplicate file contents across consecutive reads of the same file path.""" - file_latest_idx: dict[str, int] = {} - for i, msg in enumerate(messages): - t_name = getattr(msg, "name", msg.get("name") if isinstance(msg, dict) else "") - content = getattr(msg, "content", msg.get("content") if isinstance(msg, dict) else "") - if ( - t_name in self.file_read_tools - or "file" in str(t_name).lower() - or "read_file" in str(content).lower() - ): - file_latest_idx[str(t_name or "read_file")] = i - - compacted: list[Any] = [] - for i, msg in enumerate(messages): - t_name = getattr(msg, "name", msg.get("name") if isinstance(msg, dict) else "") - key = str(t_name or "read_file") - if key in file_latest_idx and file_latest_idx[key] > i and not is_pinned(msg): - cleared_text = f"[Superseded file read: {key}]" - if hasattr(msg, "model_copy"): - compacted.append(msg.model_copy(update={"content": cleared_text})) - elif isinstance(msg, dict): - c = dict(msg) - c["content"] = cleared_text - compacted.append(c) - else: - compacted.append(cleared_text) - else: - compacted.append(msg) - return compacted - - -@runtime_checkable -class TranscriptHandleProvider(Protocol): - """Protocol for capabilities providing persisted transcript handles to compaction receipts.""" - - def compaction_transcript_handle(self) -> str | None: - """Return the run identifier or handle for the persisted transcript.""" - ... - - -class CompactionReceipt(BaseModel): - """Deterministic receipt documenting context compaction for model legibility.""" - - model_config = ConfigDict(extra="ignore") - - strategy: str - messages_dropped: int = 0 - tokens_dropped: int = 0 - handle: str | None = None - - def to_receipt_text(self) -> str: - """Format the deterministic receipt text block.""" - handle_part = f", handle={self.handle}" if self.handle else "" - return ( - f"[Compaction Receipt: strategy={self.strategy}, " - f"messages_dropped={self.messages_dropped}, " - f"tokens_dropped={self.tokens_dropped}{handle_part}]" - ) - - -class SlidingWindowCompaction(BaseCapability): - """Capability that drops older whole messages down to a recent tail.""" - - id: str | None = "sliding_window_compaction" - max_messages: int = 20 - keep_user_messages: bool = True - receipts: bool = False - transcript_handle_provider: Any | None = None - - def compact_messages(self, messages: list[Any]) -> list[Any]: - """Retain the first message (system/instruction) and the last max_messages.""" - if len(messages) <= self.max_messages: - return list(messages) - - pinned = [m for m in messages if is_pinned(m)] - first_msg = messages[0] - tail = messages[-self.max_messages :] - dropped_count = len(messages) - (len(tail) + 1) - - combined: list[Any] = [first_msg] - if self.receipts and dropped_count > 0: - handle = None - if self.transcript_handle_provider and hasattr( - self.transcript_handle_provider, "compaction_transcript_handle" - ): - handle = self.transcript_handle_provider.compaction_transcript_handle() - receipt = CompactionReceipt( - strategy=self.__class__.__name__, - messages_dropped=dropped_count, - tokens_dropped=dropped_count * 50, - handle=handle, - ) - from devops_cli.models.ai import ChatMessage - - combined.append(ChatMessage(role="system", content=receipt.to_receipt_text())) - - combined.extend([m for m in tail if m != first_msg]) - return reinject_pinned(combined, pinned) - - -class SummarizingCompaction(BaseCapability): - """Capability that summarizes older messages into a structured summary message.""" - - id: str | None = "summarizing_compaction" - summary_model: Any | None = None - instructions: str = DEFAULT_SUMMARIZING_INSTRUCTIONS - keep_tail: int = 4 - max_fraction: float = 0.8 - incremental: bool = True - bridge_prefix: bool = False - keep_user_messages: bool = True - keep_user_messages_max_chars: int = 20000 - receipts: bool = False - transcript_handle_provider: Any | None = None - - def compact_messages(self, messages: list[Any]) -> list[Any]: # noqa: C901 - """Compress the middle turns into a concise summary block.""" - if len(messages) <= self.keep_tail + 2: - return list(messages) - - pinned = [m for m in messages if is_pinned(m)] - first_msg = messages[0] - tail = messages[-self.keep_tail :] - middle = messages[1 : -self.keep_tail] - - # Extract prior summary if incremental - prior_summary = "" - filtered_middle: list[Any] = [] - for m in middle: - content = str(getattr(m, "content", "")) - if self.incremental and "[Conversation Summary:" in content: - prior_summary = content - else: - filtered_middle.append(m) - - summary_lines: list[str] = [] - if self.bridge_prefix: - summary_lines.append("[Cross-model bridge: context compressed across models]") - - if prior_summary: - summary_lines.append(f"\n{prior_summary}\n") - - # Retain recent user messages up to budget if requested - if self.keep_user_messages: - user_turns = [ - m - for m in filtered_middle - if getattr(m, "role", "") == "user" - or (isinstance(m, dict) and m.get("role") == "user") - ] - for ut in user_turns[-2:]: - u_text = str(getattr(ut, "content", ""))[: self.keep_user_messages_max_chars] - summary_lines.append(f"User Goal: {u_text}") - - for m in filtered_middle: - c = str(getattr(m, "content", "")) - if c: - summary_lines.append(f"- {getattr(m, 'role', 'turn')}: {c[:100]}...") - - summary_text = ( - f"[Conversation Summary: {len(middle)} earlier turns compressed]\n" - + "\n".join(summary_lines[:10]) - ) - - combined: list[Any] = [first_msg] - - if self.receipts: - handle = None - if self.transcript_handle_provider and hasattr( - self.transcript_handle_provider, "compaction_transcript_handle" - ): - handle = self.transcript_handle_provider.compaction_transcript_handle() - receipt = CompactionReceipt( - strategy=self.__class__.__name__, - messages_dropped=len(middle), - tokens_dropped=len(middle) * 60, - handle=handle, - ) - combined.append(ChatMessage(role="system", content=receipt.to_receipt_text())) - - combined.append(ChatMessage(role="system", content=summary_text)) - combined.extend(tail) - return reinject_pinned(combined, pinned) - - -def _apply_compactor(compactor: Any, messages: list[Any]) -> list[Any]: - """Execute a compactor object or callable on a message sequence.""" - if hasattr(compactor, "compact_messages") and callable(compactor.compact_messages): - res = compactor.compact_messages(messages) - return list(res) if isinstance(res, (list, tuple)) else messages - if callable(compactor): - res = compactor(messages) - return list(res) if isinstance(res, (list, tuple)) else messages - return messages - - -class FallbackCompaction(BaseCapability): - """Capability that chains fallback compaction strategies.""" - - id: str | None = "fallback_compaction" - strategies: list[Any] = Field(default_factory=list) - - def compact_messages(self, messages: list[Any]) -> list[Any]: - """Try each configured strategy in order.""" - current = list(messages) - for strat in self.strategies: - try: - return _apply_compactor(strat, current) - except Exception: - continue - return current - - -class TieredCompaction(BaseCapability): - """Cascading compaction strategy running cheap zero-LLM passes before escalating.""" - - id: str | None = "tiered_compaction" - tiers: list[Any] = Field(default_factory=list) - max_fraction: float = 0.8 - target_tokens: int = 100000 - - def __init__( - self, - tiers: Sequence[Any] | None = None, - *, - max_fraction: float = 0.8, - target_tokens: int = 100000, - id: str = "tiered_compaction", - ) -> None: - resolved_tiers = ( - list(tiers) - if tiers is not None - else [ - DeduplicateFileReads(), - ClearToolResults(), - ClampOversizedMessages(), - SlidingWindowCompaction(), - ] - ) - super().__init__( - id=str(id or "tiered_compaction"), - tiers=resolved_tiers, - max_fraction=max_fraction, - target_tokens=target_tokens, - ) - - def compact_messages(self, messages: list[Any]) -> list[Any]: - """Apply cascading compaction tiers sequentially.""" - current = list(messages) - for tier in self.tiers: - current = _apply_compactor(tier, current) - return current - - -class WarnNearLimits(BaseCapability): - """Capability notifying the model when context consumption approaches token limits.""" - - id: str | None = "warn_near_limits" - max_context_fraction: float = 0.9 - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - return [ - f"WarnNearLimits enabled: context warning will be issued if usage exceeds " - f"{int(self.max_context_fraction * 100)}% of model context window." - ] - - -class CacheBustWarning(UserWarning): - """Warned when a previously-established prompt cache hit collapses on a later request.""" - - -class CacheMark(BaseModel): - """Tracking metrics for prompt cache stability per model and provider.""" - - model_config = ConfigDict(extra="ignore") - - established_prefix: int = 0 - last_read_tokens: int = 0 - last_request_time: float = 0.0 - latched_warning: bool = False - - -class WarnOnCacheBusts(BaseCapability): - """Capability that warns when prompt cache hits collapse mid-run.""" - - id: str | None = "warn_on_cache_busts" - collapse_ratio: float = Field(default=0.5, gt=0.0) - min_prefix_tokens: int = Field(default=1024, ge=0) - cache_ttl_seconds: float = Field(default=300.0, gt=0.0) - marks: dict[tuple[str, str], CacheMark] = Field(default_factory=dict) - - def __init__( - self, - *, - collapse_ratio: float = 0.5, - min_prefix_tokens: int = 1024, - cache_ttl_seconds: float = 300.0, - id: str | None = "warn_on_cache_busts", - ) -> None: - if collapse_ratio <= 0.0: - raise HarnessValidationError( - f"collapse_ratio must be greater than 0.0, got {collapse_ratio}" - ) - super().__init__( - id=str(id or "warn_on_cache_busts"), - collapse_ratio=collapse_ratio, - min_prefix_tokens=min_prefix_tokens, - cache_ttl_seconds=cache_ttl_seconds, - marks={}, - ) - - def for_run(self, ctx: RunContext[Any] | None = None) -> WarnOnCacheBusts: # type: ignore[override] - """Return a fresh capability instance with clean per-run state.""" - return WarnOnCacheBusts( - collapse_ratio=self.collapse_ratio, - min_prefix_tokens=self.min_prefix_tokens, - cache_ttl_seconds=self.cache_ttl_seconds, - id=self.id, - ) - - def _emit_cache_bust_warning( - self, - provider_name: str, - model_name: str, - cache_read_tokens: int, - mark: CacheMark, - now: float, - ) -> str: - """Emit a cache collapse warning and return the message.""" - gap = now - mark.last_request_time - expiry_note = "" - if mark.last_request_time > 0 and gap > self.cache_ttl_seconds: - expiry_note = ( - f" (gap of {gap:.1f}s exceeds assumed cache TTL of {self.cache_ttl_seconds}s)" - ) - - warning_msg = ( - f"Prompt cache collapsed for {provider_name}:{model_name}: read {cache_read_tokens} cached tokens, " - f"down from established prefix of {mark.established_prefix} tokens (< {self.collapse_ratio:.0%}){expiry_note}." - ) - warnings.warn(warning_msg, category=CacheBustWarning, stacklevel=2) - mark.latched_warning = True - return warning_msg - - def _check_cache_collapse( - self, - provider_name: str, - model_name: str, - cache_read_tokens: int, - mark: CacheMark, - now: float, - ) -> str | None: - """Check if cache read tokens fell below collapse threshold and emit warning.""" - if mark.established_prefix < self.min_prefix_tokens: - return None - threshold = mark.established_prefix * self.collapse_ratio - if cache_read_tokens >= threshold: - mark.latched_warning = False - return None - if not mark.latched_warning: - return self._emit_cache_bust_warning( - provider_name, model_name, cache_read_tokens, mark, now - ) - return None - - def record_request( - self, - provider_name: str, - model_name: str, - cache_read_tokens: int, - cache_write_tokens: int, - *, - request_context: Any = None, - now: float | None = None, - ) -> str | None: - """Record token usage for a model request and detect cache prefix collapse.""" - effective_now = time.time() if now is None else now - key = (provider_name, model_name) - if key not in self.marks: - self.marks[key] = CacheMark(last_request_time=effective_now) - mark = self.marks[key] - total_prefix = cache_read_tokens + cache_write_tokens - - warning_msg = self._check_cache_collapse( - provider_name, model_name, cache_read_tokens, mark, effective_now - ) - - mark.established_prefix = max(mark.established_prefix, total_prefix) - mark.last_read_tokens = cache_read_tokens - mark.last_request_time = effective_now - return warning_msg - - def after_model_request( - self, - ctx: RunContext[Any] | None = None, - *, - request_context: Any = None, - response: Any = None, - ) -> Any: - """Inspect model response usage for cache read/write tokens and track stability.""" - if response is None: - return response - - usage = getattr(response, "usage", None) - if usage is None and isinstance(response, dict): - usage = response.get("usage") - - cache_read = getattr(usage, "cache_read_tokens", 0) or 0 - cache_write = getattr(usage, "cache_write_tokens", 0) or 0 - provider = ( - getattr(request_context, "provider_name", "provider") if request_context else "provider" - ) - model = getattr(request_context, "model_name", "model") if request_context else "model" - - if isinstance(usage, dict): - cache_read = usage.get("cache_read_tokens", 0) or 0 - cache_write = usage.get("cache_write_tokens", 0) or 0 - - self.record_request( - provider_name=provider, - model_name=model, - cache_read_tokens=cache_read, - cache_write_tokens=cache_write, - ) - return response - - -class ReportContextUsage(BaseCapability): - """Capability reporting token counts and context fractions.""" - - id: str | None = "report_context_usage" - - def get_usage(self, messages: list[Any], context_limit: int = 128000) -> ContextUsage: - """Calculate token and message usage metrics.""" - total_chars = sum(len(str(getattr(m, "content", ""))) for m in messages) - estimated_tokens = total_chars // 4 - fraction = min(1.0, estimated_tokens / max(1, context_limit)) - return ContextUsage( - total_tokens=estimated_tokens, - context_limit=context_limit, - context_fraction=fraction, - message_count=len(messages), - ) - - -def compact_now( - messages: list[Any], - strategy: Any | None = None, -) -> list[Any]: - """Execute immediate compaction on a message history list using the given or default strategy.""" - strat = strategy or TieredCompaction() - if hasattr(strat, "compact_messages"): - res = strat.compact_messages(messages) - return list(res) if isinstance(res, (list, tuple)) else list(messages) - elif callable(strat): - res = strat(messages) - return list(res) if isinstance(res, (list, tuple)) else list(messages) - return list(messages) diff --git a/src/devops_cli/ai/harness/constants.py b/src/devops_cli/ai/harness/constants.py deleted file mode 100644 index 2d88e0fd41..0000000000 --- a/src/devops_cli/ai/harness/constants.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Constants and deprecation warnings for Pydantic AI Harness.""" - -from __future__ import annotations - -import logging - -from devops_cli.ai.task_loader import load_task_prompt - -logger = logging.getLogger(__name__) - -DEFAULT_ADVISOR_INSTRUCTIONS: str = load_task_prompt("advisor_system.md").strip() -DEFAULT_SUMMARIZING_INSTRUCTIONS: str = load_task_prompt("summarizing_compaction.md").strip() -DEFAULT_CODER_INSTRUCTIONS: str = load_task_prompt("coder_agent.md").strip() -DEFAULT_RESEARCHER_INSTRUCTIONS: str = load_task_prompt("researcher_agent.md").strip() -DEFAULT_MACROSCOPE_GUIDANCE: str = load_task_prompt("macroscope_guidance.md").strip() -DEFAULT_PLANNING_GUIDANCE: str = load_task_prompt("planning_guidance.md") -DEFAULT_PLAYWRIGHT_GUIDANCE: str = load_task_prompt("playwright_guidance.md") - -LLM_API_KEY_ENV_PATTERNS: list[str] = [ - "*API_KEY*", - "*AUTH_TOKEN*", - "*SECRET*", - "*PASSWORD*", - "*ACCESS_TOKEN*", - "*CREDENTIAL*", -] - -DEFAULT_PROTECTED_PATTERNS: list[str] = [ - ".git/*", - ".env", - ".env.*", - "*.pem", - "*.key", - "**/secrets*", -] - -DEFAULT_DENIED_COMMANDS: set[str] = { - "rm", - "rmdir", - "mkfs", - "dd", - "shutdown", - "reboot", - "poweroff", - "init", -} - -INTERACTIVE_COMMANDS: set[str] = { - "vim", - "vi", - "nano", - "top", - "htop", - "less", - "more", -} - -UNSUPPORTED_BEHAVIORAL_SKILL_FIELDS: set[str] = { - "agent", - "allowed-tools", - "argument-hint", - "arguments", - "context", - "dependencies", - "disable-model-invocation", - "disallowed-tools", - "effort", - "hooks", - "model", - "paths", - "shell", - "tools", - "user-invocable", - "when_to_use", -} - - -class HarnessDeprecationWarning(DeprecationWarning): - """Warning category raised for deprecated Pydantic AI Harness options or defaults.""" diff --git a/src/devops_cli/ai/harness/conversation.py b/src/devops_cli/ai/harness/conversation.py deleted file mode 100644 index d9b9360afd..0000000000 --- a/src/devops_cli/ai/harness/conversation.py +++ /dev/null @@ -1,291 +0,0 @@ -"""ConversationSearch and history inspection capabilities.""" - -from __future__ import annotations - -import logging -import time -import warnings -from collections.abc import Callable -from typing import Any, Literal, Protocol, cast, runtime_checkable - -from pydantic import BaseModel, ConfigDict, Field -from pydantic_ai.tools import RunContext - -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.ai.harness.constants import HarnessDeprecationWarning -from devops_cli.ai.lexical import bm25_scores -from devops_cli.config.defaults import DEFAULT_BM25_B, DEFAULT_BM25_K1 -from devops_cli.models.ai import ChatMessage - -logger = logging.getLogger(__name__) - - -class RunRecord(BaseModel): - """Execution record for a single run containing message turns and metadata.""" - - model_config = ConfigDict(extra="ignore") - - run_id: str - conversation_id: str | None = None - messages: list[ChatMessage] = Field(default_factory=list) - timestamp: float = Field(default_factory=time.time) - - -@runtime_checkable -class HistorySource(Protocol): - """Protocol for conversation history data sources.""" - - def get_runs( - self, - conversation_id: str | None = None, - run_id: str | None = None, - ) -> list[RunRecord]: ... - - -class SnapshotHistorySource(BaseModel): - """History source that reads runs and step snapshots from persistence stores.""" - - model_config = ConfigDict(extra="ignore") - - store: Any = None - runs: dict[str, RunRecord] = Field(default_factory=dict) - - def __init__(self, store: Any = None, **data: Any) -> None: - super().__init__(store=store, **data) - - def record_run( - self, - run_id: str, - conversation_id: str | None = None, - messages: list[ChatMessage | Any] | None = None, - ) -> RunRecord: - """Record or update a run record.""" - norm_msgs = [ - m if isinstance(m, ChatMessage) else ChatMessage.model_validate(m) - for m in (messages or []) - ] - rec = RunRecord(run_id=run_id, conversation_id=conversation_id, messages=norm_msgs) - self.runs[run_id] = rec - return rec - - def get_runs( - self, - conversation_id: str | None = None, - run_id: str | None = None, - ) -> list[RunRecord]: - """Fetch all in-scope run records matching conversation_id or run_id.""" - if self.store and hasattr(self.store, "get_runs") and callable(self.store.get_runs): - try: - external_runs = self.store.get_runs(conversation_id=conversation_id, run_id=run_id) - if isinstance(external_runs, list): - return external_runs - except Exception as e: - logger.debug("Store get_runs error: %s", e) - - results: list[RunRecord] = [] - for r_id, r in self.runs.items(): - if run_id is not None and r_id != run_id: - continue - if conversation_id is not None and r.conversation_id != conversation_id: - continue - results.append(r) - return results - - -class ConversationSearchMatch(BaseModel): - """Matched turn snippet from conversation search with BM25 score and provenance.""" - - model_config = ConfigDict(extra="ignore") - - run_id: str - conversation_id: str | None = None - role: str - content: str - snippet: str - score: float - turn_index: int - - -def bm25_rank( - query: str, - documents: list[dict[str, Any]], - *, - k1: float = DEFAULT_BM25_K1, - b: float = DEFAULT_BM25_B, - max_matches: int = 10, - context_lines: int = 5, -) -> list[ConversationSearchMatch]: - """Rank conversation messages by BM25 relevance to a query. - - Scoring is delegated to the shared lexical ranker, so conversation search and RAG - hybrid retrieval cannot drift apart in how they weight a literal match. - """ - contents = [str(doc.get("content", "")) for doc in documents] - ranked = bm25_scores(query, contents, k1=k1, b=b, limit=max_matches) - - matches: list[ConversationSearchMatch] = [] - for match in ranked: - doc = documents[match.index] - content_str = contents[match.index] - matches.append( - ConversationSearchMatch( - run_id=str(doc.get("run_id", "")), - conversation_id=doc.get("conversation_id"), - role=str(doc.get("role", "assistant")), - content=content_str, - snippet="\n".join(content_str.splitlines()[: max(1, context_lines)]), - score=float(match.score), - turn_index=int(doc.get("turn_index", match.index)), - ) - ) - return matches - - -def _fetch_conversation_runs( - source: Any, effective_scope: str, target_conv_id: str | None, run_id: str | None -) -> list[RunRecord]: - """Fetch runs from source given scope and identifiers.""" - get_runs_fn = getattr(source, "get_runs", None) - if not callable(get_runs_fn): - return [] - conv_filter = target_conv_id if effective_scope == "conversation" else None - res = get_runs_fn(conversation_id=conv_filter, run_id=run_id) - return cast(list[RunRecord], res) if isinstance(res, list) else [] - - -def _extract_conversation_documents(runs: list[RunRecord]) -> list[dict[str, Any]]: - """Extract message turn records into searchable document dictionaries.""" - docs: list[dict[str, Any]] = [] - for r in runs: - for turn_idx, m in enumerate(r.messages): - c = getattr(m, "content", "") or "" - if not c: - continue - docs.append( - { - "run_id": r.run_id, - "conversation_id": r.conversation_id, - "role": getattr(m, "role", "user"), - "content": c, - "turn_index": turn_idx, - } - ) - return docs - - -class ConversationSearch(BaseCapability): - """Capability providing BM25-ranked search over persisted conversation history.""" - - id: str | None = "conversation_search" - source: Any = None - scope: Literal["conversation", "all"] | None = None - max_matches: int = 10 - context_lines: int = 5 - bm25_k1: float = 1.5 - bm25_b: float = 0.75 - add_instructions: bool = True - tool_id: str = "conversation-search" - - def __init__( - self, - source: Any, - *, - scope: Literal["conversation", "all"] | None = None, - max_matches: int = 10, - context_lines: int = 5, - bm25_k1: float = 1.5, - bm25_b: float = 0.75, - add_instructions: bool = True, - tool_id: str = "conversation-search", - id: str | None = None, - ) -> None: - effective_scope = "conversation" - if scope is not None: - effective_scope = scope - else: - warnings.warn( - "ConversationSearch scope was unset; defaulting to 'conversation'.", - category=HarnessDeprecationWarning, - stacklevel=2, - ) - - super().__init__( - id=str(id or "conversation_search"), - source=source, - scope=effective_scope, - max_matches=max_matches, - context_lines=context_lines, - bm25_k1=bm25_k1, - bm25_b=bm25_b, - add_instructions=add_instructions, - tool_id=tool_id, - ) - - @property - def effective_scope(self) -> Literal["conversation", "all"]: - return self.scope or "conversation" - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - if not self.add_instructions: - return [] - scope_note = ( - "within this conversation" - if self.effective_scope == "conversation" - else "across all recorded conversations" - ) - return [ - f"You have access to the search_conversation_history tool to search past interaction turns {scope_note}." - ] - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - source = self.source - effective_scope = self.effective_scope - k1 = self.bm25_k1 - b = self.bm25_b - max_k = self.max_matches - ctx_lines = self.context_lines - - def search_conversation_history( - query: str, - run_id: str | None = None, - conversation_id: str | None = None, - ) -> str: - """Search earlier turns from persisted conversation history using BM25 relevance.""" - try: - target_conv_id = ( - conversation_id if effective_scope == "all" else (conversation_id or "default") - ) - runs = _fetch_conversation_runs(source, effective_scope, target_conv_id, run_id) - if not runs: - return f"No persisted conversation history found for search query '{query}'." - - documents = _extract_conversation_documents(runs) - matches = bm25_rank( - query=query, - documents=documents, - k1=k1, - b=b, - max_matches=max_k, - context_lines=ctx_lines, - ) - - if not matches: - return f"No matching conversation turns found for '{query}'." - - results = [f"Found {len(matches)} historical match(es):"] - results.extend( - f"--- [run: {m.run_id}{f' | conversation: {m.conversation_id}' if m.conversation_id else ''} | role: {m.role} | score: {m.score:.2f}] ---\n{m.snippet}" - for m in matches - ) - return "\n\n".join(results) - except Exception as e: - return f"Error searching conversation history: {e}" - - return [ - Tool.from_function( - search_conversation_history, - name="search_conversation_history", - description="Search earlier conversation history and past runs with BM25 keyword matching.", - ) - ] diff --git a/src/devops_cli/ai/harness/docs.py b/src/devops_cli/ai/harness/docs.py deleted file mode 100644 index a8be615e61..0000000000 --- a/src/devops_cli/ai/harness/docs.py +++ /dev/null @@ -1,175 +0,0 @@ -"""PydanticAIDocs capability for fetching official documentation.""" - -from __future__ import annotations - -import logging -import os -from collections.abc import Callable -from pathlib import Path -from typing import Any - -from pydantic import Field -from pydantic_ai.tools import RunContext - -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.config.defaults import DEFAULT_MAX_AST_FILE_SIZE_BYTES - -DEFAULT_PYAI_DOCS_TOPICS: tuple[str, ...] = ( - "agent", - "capabilities", - "capability-creation", - "guardrails", - "handle-deferred-tool-calls", - "hooks", - "include-tool-return-schemas", - "instrumentation", - "managed-prompt", - "media", - "prepare-tools", - "prefix-tools", - "process-event-stream", - "process-history", - "prompt-injection-defender", - "raise-content-filter-error", - "reinject-system-prompt", - "resolve-model-id", - "select-model", - "set-tool-metadata", - "spend", - "step-persistence", - "system-reminders", - "thread-executor", - "tools", - "tools-advanced", - "toolsets", -) - -logger = logging.getLogger(__name__) - - -class PydanticAIDocs(BaseCapability): - """Capability that locates and returns Pydantic AI documentation on demand.""" - - id: str | None = "pydantic_ai_docs" - local_docs_path: Path | None = None - cache: bool = True - memoized_docs: dict[str, str] = Field(default_factory=dict) - - def __init__( - self, - *, - local_docs_path: str | Path | None = None, - cache: bool = True, - id: str = "pydantic_ai_docs", - ) -> None: - p = None - if local_docs_path is not None: - p = Path(os.path.expanduser(str(local_docs_path))).resolve() - elif env_path := os.environ.get("PYDANTIC_AI_HARNESS_DOCS_PATH"): - cand_p = Path(os.path.expanduser(env_path)).resolve() - if cand_p.is_dir(): - p = cand_p - - super().__init__( - id=str(id or "pydantic_ai_docs"), - local_docs_path=p, - cache=cache, - ) - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - return [ - "You have access to the read_pyai_docs tool. Consult Pydantic AI documentation before authoring or modifying capabilities, hooks, tools, or toolsets." - ] - - def _fetch_remote_doc(self, url: str) -> str | None: - """Attempt to fetch a documentation markdown file over HTTP.""" - try: - from devops_cli.http.client import new_http_client - from devops_cli.http.egress import EgressLevel - - with new_http_client(level=EgressLevel.PUBLIC, read_timeout=10.0) as client: - resp = client.get(url) - if resp.status_code == 200 and resp.text: - return resp.text - except Exception as exc: - logger.debug("Remote fetch failed for %s: %s", url, exc) - return None - - def _read_local_doc(self, local_file: Path) -> str | None: - """Attempt to read local doc file.""" - try: - if local_file.is_symlink(): - return None - if local_file.stat().st_size > DEFAULT_MAX_AST_FILE_SIZE_BYTES: - return None - return local_file.read_text(encoding="utf-8", errors="replace") - except Exception as e: - logger.debug("Error reading local doc %s: %s", local_file, e) - return None - - def read_doc(self, topic: str) -> str: # noqa: C901 - """Resolve and read a Pydantic AI documentation topic (local checkout first, then remote).""" - import re - - clean_topic = topic.strip().lower() - if clean_topic.endswith(".md"): - clean_topic = clean_topic[:-3] - - # Security: Prevent path traversal in topic name - if ".." in clean_topic or clean_topic.startswith(("/", "\\")): - return f"Error: Invalid documentation topic '{topic}' (path traversal sequences are forbidden)." - - clean_topic = re.sub(r"[^a-zA-Z0-9_\-\./]", "", clean_topic) - if not clean_topic: - return f"Error: Invalid empty documentation topic '{topic}'." - - if self.cache and clean_topic in self.memoized_docs: - return self.memoized_docs[clean_topic] - - # 1. Local checkout - if self.local_docs_path is not None: - local_file = (self.local_docs_path / f"{clean_topic}.md").resolve() - if ( - not local_file.is_symlink() - and local_file.is_relative_to(self.local_docs_path) - and local_file.is_file() - ): - content = self._read_local_doc(local_file) - if content is not None: - if self.cache: - self.memoized_docs[clean_topic] = content - return content - - # 2. Remote fallback - url = f"https://raw.githubusercontent.com/pydantic/pydantic-ai/main/docs/{clean_topic}.md" - content = self._fetch_remote_doc(url) - if content: - if self.cache: - self.memoized_docs[clean_topic] = content - return content - - local_attempted = ( - f"local path '{self.local_docs_path}/{clean_topic}.md'" - if self.local_docs_path - else "no local checkout configured" - ) - return f"Error: Could not resolve Pydantic AI documentation topic '{topic}'. Tried {local_attempted} and remote URL '{url}'." - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - read_fn = self.read_doc - - def read_pyai_docs(topic: str) -> str: - """Locate and return Pydantic AI documentation on demand for a topic (e.g. 'capabilities', 'hooks', 'tools', 'toolsets', 'agent').""" - return read_fn(topic) - - return [ - Tool.from_function( - read_pyai_docs, - name="read_pyai_docs", - description="Fetch official Pydantic AI documentation for a specific topic or component.", - ) - ] - - -PyaiDocs = PydanticAIDocs diff --git a/src/devops_cli/ai/harness/filesystem.py b/src/devops_cli/ai/harness/filesystem.py deleted file mode 100644 index ed6cf0299e..0000000000 --- a/src/devops_cli/ai/harness/filesystem.py +++ /dev/null @@ -1,373 +0,0 @@ -"""FileSystem capability for safe, sandboxed file operations.""" - -from __future__ import annotations - -import fnmatch -import hashlib -import logging -import re -from collections.abc import Callable -from pathlib import Path -from typing import Any - -from pydantic import Field -from pydantic_ai.tools import RunContext - -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.ai.harness.constants import DEFAULT_PROTECTED_PATTERNS -from devops_cli.core.repo import is_ignored_by_git - -logger = logging.getLogger(__name__) - - -def _search_single_file_lines( - p: Path, - rel: str, - pattern_re: re.Pattern[str], - results: list[str], - max_results: int, -) -> bool: - """Search lines of a single file for regex pattern. Returns True if max_results reached.""" - try: - text = p.read_text(encoding="utf-8", errors="ignore") - except Exception: - return False - - for i, line in enumerate(text.splitlines(), start=1): - if not pattern_re.search(line): - continue - results.append(f"{rel}:{i}: {line.strip()}") - if len(results) >= max_results: - results.append(f"[... truncated at {max_results} results ...]") - return True - return False - - -class FileSystem(BaseCapability): - """Capability providing safe, sandboxed file operations with pattern filtering and optimistic concurrency.""" - - id: str | None = "file_system" - root: Path = Field(default_factory=lambda: Path(".")) - allowed_patterns: list[str] = Field(default_factory=list) - denied_patterns: list[str] = Field(default_factory=list) - protected_patterns: list[str] = Field(default_factory=lambda: list(DEFAULT_PROTECTED_PATTERNS)) - max_read_lines: int = 2000 - max_list_results: int = 1000 - max_search_results: int = 1000 - max_find_results: int = 1000 - read_only: bool = False - - def __init__( - self, - root_dir: Path | str | None = None, - *, - root: Path | str | None = None, - allowed_patterns: list[str] | None = None, - denied_patterns: list[str] | None = None, - protected_patterns: list[str] | None = None, - max_read_lines: int = 2000, - max_list_results: int = 1000, - max_search_results: int = 1000, - max_find_results: int = 1000, - read_only: bool = False, - ) -> None: - p = Path(root_dir or root or ".") - super().__init__( - root=p, - allowed_patterns=allowed_patterns or [], - denied_patterns=denied_patterns or [], - protected_patterns=list(DEFAULT_PROTECTED_PATTERNS) - if protected_patterns is None - else protected_patterns, - max_read_lines=max_read_lines, - max_list_results=max_list_results, - max_search_results=max_search_results, - max_find_results=max_find_results, - read_only=read_only, - ) - - def _resolve_safe_path(self, rel_path: str) -> Path: - resolved = (self.root.resolve() / rel_path).resolve() - root_res = self.root.resolve() - if not resolved.is_relative_to(root_res): - raise PermissionError(f"Access denied: path '{rel_path}' is outside root '{self.root}'") - return resolved - - def _matches_pattern(self, rel_path: str, patterns: list[str]) -> bool: - - normalized = rel_path.replace("\\", "/") - return any( - fnmatch.fnmatch(normalized, pat) or fnmatch.fnmatch(Path(normalized).name, pat) - for pat in patterns - ) - - def _is_accessible(self, rel_path: str, for_write: bool = False) -> tuple[bool, str]: - if self._matches_pattern(rel_path, self.denied_patterns): - return False, f"Access denied: '{rel_path}' matches denied pattern" - if self.allowed_patterns and not self._matches_pattern(rel_path, self.allowed_patterns): - return False, f"Access denied: '{rel_path}' does not match allowed patterns" - if for_write: - if self.read_only: - return False, "Access denied: FileSystem is configured read-only" - if self._matches_pattern(rel_path, self.protected_patterns): - return False, f"Access denied: '{rel_path}' is protected and read-only" - return True, "" - - def _content_hash(self, content: str | bytes) -> str: - """Compute full SHA-256 hash for strong collision-resistant optimistic concurrency.""" - data = content.encode("utf-8") if isinstance(content, str) else content - return hashlib.sha256(data).hexdigest() - - def _read_file(self, path: str, offset: int = 1, limit: int | None = None) -> str: - """Read a text file with line numbers and a content hash.""" - ok, err = self._is_accessible(path, for_write=False) - if not ok: - return f"Error: {err}" - safe_p = self._resolve_safe_path(path) - if not safe_p.is_file(): - return f"Error: file not found: {path}" - - raw_bytes = safe_p.read_bytes() - if b"\x00" in raw_bytes[:1024]: - return f"[Binary file '{path}', {len(raw_bytes)} bytes]" - - text = raw_bytes.decode("utf-8", errors="replace") - c_hash = self._content_hash(text) - lines = text.splitlines() - - start_idx = max(0, offset - 1) - end_idx = min(len(lines), start_idx + (limit or self.max_read_lines)) - selected_lines = lines[start_idx:end_idx] - - numbered = [f"{start_idx + i + 1:4d} | {line}" for i, line in enumerate(selected_lines)] - header = ( - f"# File: {path} (sha256:{c_hash}, lines {start_idx + 1}-{end_idx} of {len(lines)})\n" - ) - return header + "\n".join(numbered) - - def _write_file(self, path: str, content: str, expected_hash: str | None = None) -> str: - """Create or overwrite a file with optimistic concurrency validation.""" - ok, err = self._is_accessible(path, for_write=True) - if not ok: - return f"Error: {err}" - safe_p = self._resolve_safe_path(path) - if safe_p.is_file() and expected_hash: - curr_hash = self._content_hash(safe_p.read_text(encoding="utf-8", errors="replace")) - if curr_hash != expected_hash: - return f"Error: stale edit conflict. File hash is '{curr_hash}', expected '{expected_hash}'." - - safe_p.parent.mkdir(parents=True, exist_ok=True) - safe_p.write_text(content, encoding="utf-8") - new_hash = self._content_hash(content) - return f"File '{path}' successfully written (sha256:{new_hash}, {len(content)} chars)." - - def _edit_file( - self, path: str, old_text: str, new_text: str, expected_hash: str | None = None - ) -> str: - """Perform exact-string replacement within an existing file.""" - ok, err = self._is_accessible(path, for_write=True) - if not ok: - return f"Error: {err}" - safe_p = self._resolve_safe_path(path) - if not safe_p.is_file(): - return f"Error: file not found: {path}" - - curr_content = safe_p.read_text(encoding="utf-8", errors="replace") - if expected_hash: - curr_hash = self._content_hash(curr_content) - if curr_hash != expected_hash: - return f"Error: stale edit conflict. File hash is '{curr_hash}', expected '{expected_hash}'." - - occurrences = curr_content.count(old_text) - if occurrences == 0: - return f"Error: target old_text not found in '{path}'" - if occurrences > 1: - return f"Error: target old_text matches {occurrences} times in '{path}'. Must match uniquely." - - updated = curr_content.replace(old_text, new_text, 1) - safe_p.write_text(updated, encoding="utf-8") - new_hash = self._content_hash(updated) - return f"File '{path}' successfully edited (sha256:{new_hash})." - - def _list_directory(self, path: str = ".") -> str: - """List directory entries with type indicators and sizes, omitting dotfiles.""" - ok, err = self._is_accessible(path, for_write=False) - if not ok: - return f"Error: {err}" - safe_p = self._resolve_safe_path(path) - if not safe_p.is_dir(): - return f"Error: not a directory: {path}" - - entries: list[str] = [] - for item in sorted(safe_p.iterdir()): - if item.name.startswith(".") or item.is_symlink(): - continue - rel = str(item.relative_to(self.root)) - if self.denied_patterns and self._matches_pattern(rel, self.denied_patterns): - continue - if ( - self.allowed_patterns - and item.is_file() - and not self._matches_pattern(rel, self.allowed_patterns) - ): - continue - - if item.is_dir(): - entries.append(f"[DIR] {item.name}/") - else: - size = item.stat().st_size - entries.append(f"[FILE] {item.name} ({size} bytes)") - - if len(entries) >= self.max_list_results: - entries.append(f"[... truncated at {self.max_list_results} entries ...]") - break - - return "\n".join(entries) or f"Directory '{path}' is empty." - - def _find_files(self, pattern: str, path: str = ".") -> str: - """Glob search over file names relative to path.""" - safe_p = self._resolve_safe_path(path) - if not safe_p.is_dir(): - return f"Error: not a directory: {path}" - - matches: list[str] = [] - for p in sorted(safe_p.rglob(pattern)): - if p.is_symlink(): - continue - try: - resolved = p.resolve() - if not resolved.is_relative_to(self.root.resolve()): - continue - except OSError: - continue - if is_ignored_by_git(self.root, p): - continue - rel = str(p.relative_to(self.root)) - if self.denied_patterns and self._matches_pattern(rel, self.denied_patterns): - continue - matches.append(rel) - if len(matches) >= self.max_find_results: - matches.append(f"[... truncated at {self.max_find_results} matches ...]") - break - - return "\n".join(matches) or f"No files matching pattern '{pattern}' found." - - def _search_files(self, query: str, path: str = ".", include_glob: str | None = None) -> str: # noqa: C901 - """Regex or text search across file contents.""" - safe_p = self._resolve_safe_path(path) - if not safe_p.is_dir(): - return f"Error: not a directory: {path}" - - if len(query) > 256: - return f"Error: Search query exceeds maximum length of 256 characters ({len(query)} characters)." - - try: - pattern_re = re.compile(query, re.IGNORECASE) - except re.error as e: - return f"Error: Invalid regular expression '{query}': {e}" - - results: list[str] = [] - for p in sorted(safe_p.rglob(include_glob or "*")): - if not p.is_file() or p.is_symlink(): - continue - try: - resolved = p.resolve() - if not resolved.is_relative_to(self.root.resolve()): - continue - except OSError: - continue - if is_ignored_by_git(self.root, p): - continue - rel = str(p.relative_to(self.root)) - if self.denied_patterns and self._matches_pattern(rel, self.denied_patterns): - continue - if _search_single_file_lines(p, rel, pattern_re, results, self.max_search_results): - return "\n".join(results) - - return "\n".join(results) or f"No matches found for query '{query}'." - - def _create_directory(self, path: str) -> str: - """Create a directory and any missing parent folders.""" - ok, err = self._is_accessible(path, for_write=True) - if not ok: - return f"Error: {err}" - safe_p = self._resolve_safe_path(path) - safe_p.mkdir(parents=True, exist_ok=True) - return f"Directory '{path}' successfully created." - - def _file_info(self, path: str) -> str: - """Retrieve metadata for a file or directory.""" - ok, err = self._is_accessible(path, for_write=False) - if not ok: - return f"Error: {err}" - safe_p = self._resolve_safe_path(path) - if not safe_p.exists(): - return f"Error: path '{path}' does not exist" - - stat = safe_p.stat() - if safe_p.is_dir(): - return f"Directory: {path}\nType: directory\nModified: {stat.st_mtime}" - c_hash = self._content_hash(safe_p.read_bytes()) - lines_count = len(safe_p.read_text(encoding="utf-8", errors="replace").splitlines()) - return ( - f"File: {path}\n" - f"Type: regular file\n" - f"Size: {stat.st_size} bytes\n" - f"Lines: {lines_count}\n" - f"Modified: {stat.st_mtime}\n" - f"sha256: {c_hash}" - ) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - read_tools: list[AgentTool | Callable[..., Any]] = [ - Tool.from_function( - self._read_file, - name="read_file", - description="Read file contents with line offset/limit.", - ), - Tool.from_function( - self._list_directory, name="list_directory", description="List directory entries." - ), - Tool.from_function( - self._find_files, - name="find_files", - description="Find files matching a glob pattern.", - ), - Tool.from_function( - self._search_files, - name="search_files", - description="Search file contents by regex pattern.", - ), - Tool.from_function( - self._file_info, - name="file_info", - description="Retrieve metadata and hash for a file or directory.", - ), - ] - - if self.read_only: - return read_tools - - write_tools: list[AgentTool | Callable[..., Any]] = [ - Tool.from_function( - self._write_file, - name="write_file", - description="Create or overwrite a file with optimistic concurrency validation.", - ), - Tool.from_function( - self._edit_file, - name="edit_file", - description="Exact-string replacement within an existing file.", - ), - Tool.from_function( - self._create_directory, - name="create_directory", - description="Create a directory and any missing parent folders.", - ), - ] - return [*read_tools, *write_tools] - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - mode = "read-only" if self.read_only else "read-write" - return [f"Workspace FileSystem capability enabled ({mode}) rooted at {self.root}."] diff --git a/src/devops_cli/ai/harness/memory.py b/src/devops_cli/ai/harness/memory.py deleted file mode 100644 index 42b9481592..0000000000 --- a/src/devops_cli/ai/harness/memory.py +++ /dev/null @@ -1,713 +0,0 @@ -"""Hierarchical and searchable persistent memory capability.""" - -from __future__ import annotations - -import logging -import os -import sqlite3 -import time -import uuid -from collections.abc import Callable -from pathlib import Path -from typing import Any, Literal, Protocol, runtime_checkable - -from pydantic import BaseModel, ConfigDict, Field, field_validator -from pydantic_ai.tools import RunContext - -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.config.constants import CONST_SQLITE_PER_CONNECTION_DATABASES -from devops_cli.exceptions.ai import HarnessExecutionError, HarnessValidationError - -logger = logging.getLogger(__name__) - - -class MemoryOperationConflictError(HarnessExecutionError): - """Raised when an optimistic concurrency conflict or duplicate operation occurs in memory store.""" - - -class MemoryFile(BaseModel): - """A single notebook file in persistent memory.""" - - model_config = ConfigDict(extra="ignore") - - path: str - content: str - version: str - truncated: bool = False - size_bytes: int = 0 - - -class MemoryMutationResult(BaseModel): - """Outcome of a memory write or mutation.""" - - model_config = ConfigDict(extra="ignore") - - path: str - version: str - size_bytes: int - status: str = "ok" - - -class MemorySearchResult(BaseModel): - """Matched snippet from a memory search.""" - - model_config = ConfigDict(extra="ignore") - - path: str - snippet: str - score: float = 0.0 - - -@runtime_checkable -class MemoryStore(Protocol): - """Protocol for persistent agent memory stores.""" - - def read(self, path: str, max_chars: int = 65536) -> MemoryFile: ... - - def write( - self, - path: str, - content: str, - mode: Literal["append", "replace"] = "append", - target_fragment: str | None = None, - replacement: str | None = None, - expected_version: str | None = None, - operation_id: str | None = None, - ) -> MemoryMutationResult: ... - - def delete(self, path: str, expected_version: str | None = None) -> bool: ... - - def list_paths(self, prefix: str = "", limit: int = 100) -> list[str]: ... - - -@runtime_checkable -class SearchableMemoryStore(MemoryStore, Protocol): - """Memory store supporting fast text search.""" - - def search( - self, - query: str, - max_results: int = 10, - max_result_chars: int = 4000, - max_file_chars: int = 65536, - ) -> list[MemorySearchResult]: ... - - -class InMemoryStore(BaseModel): - """Process-lifetime in-memory notebook store with optimistic concurrency.""" - - model_config = ConfigDict(extra="ignore") - - files: dict[str, MemoryFile] = Field(default_factory=dict) - operations: set[str] = Field(default_factory=set) - - def read(self, path: str, max_chars: int = 65536) -> MemoryFile: - clean = path.strip().lstrip("/") - if clean not in self.files: - return MemoryFile(path=clean, content="", version="0", size_bytes=0) - f = self.files[clean] - if len(f.content) > max_chars: - return MemoryFile( - path=clean, - content=f.content[:max_chars], - version=f.version, - truncated=True, - size_bytes=len(f.content), - ) - return f - - def write( - self, - path: str, - content: str, - mode: Literal["append", "replace"] = "append", - target_fragment: str | None = None, - replacement: str | None = None, - expected_version: str | None = None, - operation_id: str | None = None, - ) -> MemoryMutationResult: - if operation_id and operation_id in self.operations: - f = self.read(path) - return MemoryMutationResult( - path=f.path, version=f.version, size_bytes=f.size_bytes, status="idempotent_replay" - ) - - clean = path.strip().lstrip("/") - existing = self.files.get(clean) - if expected_version is not None and existing and existing.version != expected_version: - raise MemoryOperationConflictError( - f"Version mismatch on '{clean}': expected {expected_version}, got {existing.version}" - ) - - new_content = "" - if mode == "replace" and target_fragment is not None: - base = existing.content if existing else "" - if target_fragment not in base: - raise HarnessValidationError(f"Target fragment not found in memory file '{clean}'") - new_content = base.replace(target_fragment, replacement or "", 1) - elif mode == "replace": - new_content = content - else: - base = existing.content if existing else "" - new_content = f"{base}\n{content}".strip() if base else content - - new_version = uuid.uuid4().hex[:12] - mf = MemoryFile( - path=clean, - content=new_content, - version=new_version, - size_bytes=len(new_content.encode("utf-8")), - ) - self.files[clean] = mf - if operation_id: - self.operations.add(operation_id) - return MemoryMutationResult( - path=clean, version=new_version, size_bytes=mf.size_bytes, status="ok" - ) - - def delete(self, path: str, expected_version: str | None = None) -> bool: - clean = path.strip().lstrip("/") - if clean in self.files: - if expected_version and self.files[clean].version != expected_version: - raise MemoryOperationConflictError(f"Version mismatch on delete of '{clean}'") - del self.files[clean] - return True - return False - - def list_paths(self, prefix: str = "", limit: int = 100) -> list[str]: - clean_prefix = prefix.strip().lstrip("/") - matches = [p for p in sorted(self.files.keys()) if p.startswith(clean_prefix)] - return matches[:limit] - - def search( - self, - query: str, - max_results: int = 10, - max_result_chars: int = 4000, - max_file_chars: int = 65536, - ) -> list[MemorySearchResult]: - q = query.strip().lower() - if not q: - return [] - terms = list(dict.fromkeys(q.split()))[:32] - results: list[MemorySearchResult] = [] - total_chars = 0 - - for path, mf in self.files.items(): - content_lower = mf.content[:max_file_chars].lower() - score = sum(content_lower.count(t) for t in terms) - if any(t in path.lower() for t in terms): - score += 5 - if score > 0: - snippet = mf.content[: min(300, max_result_chars)] - results.append(MemorySearchResult(path=path, snippet=snippet, score=float(score))) - total_chars += len(path) + len(snippet) - if len(results) >= max_results or total_chars >= max_result_chars: - break - - results.sort(key=lambda r: r.score, reverse=True) - return results[:max_results] - - -class FileStore(BaseModel): - """Filesystem-backed memory notebook store with atomic writes and directory containment.""" - - model_config = ConfigDict(extra="ignore") - - directory: Path = Field(default_factory=lambda: Path(".agent-memory")) - - def __init__(self, directory: Path | str = ".agent-memory") -> None: - p = Path(directory) - super().__init__(directory=p) - self.directory.mkdir(parents=True, exist_ok=True) - - def _resolve_path(self, path: str) -> Path: - clean = path.strip().lstrip("/") - target = (self.directory / clean).resolve() - if not target.is_relative_to(self.directory.resolve()): - raise PermissionError(f"Path traversal attempted in memory path: {path}") - return target - - def read(self, path: str, max_chars: int = 65536) -> MemoryFile: - p = self._resolve_path(path) - if not p.exists() or not p.is_file(): - return MemoryFile(path=path, content="", version="0", size_bytes=0) - text = p.read_text(encoding="utf-8") - version = str(int(p.stat().st_mtime_ns)) - if len(text) > max_chars: - return MemoryFile( - path=path, - content=text[:max_chars], - version=version, - truncated=True, - size_bytes=len(text.encode("utf-8")), - ) - return MemoryFile( - path=path, content=text, version=version, size_bytes=len(text.encode("utf-8")) - ) - - def write( - self, - path: str, - content: str, - mode: Literal["append", "replace"] = "append", - target_fragment: str | None = None, - replacement: str | None = None, - expected_version: str | None = None, - operation_id: str | None = None, - ) -> MemoryMutationResult: - p = self._resolve_path(path) - p.parent.mkdir(parents=True, exist_ok=True) - existing_text = p.read_text(encoding="utf-8") if p.exists() else "" - if expected_version is not None and p.exists(): - curr_v = str(int(p.stat().st_mtime_ns)) - if curr_v != expected_version: - raise MemoryOperationConflictError( - f"Version mismatch on '{path}': expected {expected_version}, got {curr_v}" - ) - - if mode == "replace" and target_fragment is not None: - if target_fragment not in existing_text: - raise HarnessValidationError(f"Target fragment not found in memory file '{path}'") - new_text = existing_text.replace(target_fragment, replacement or "", 1) - elif mode == "replace": - new_text = content - else: - new_text = f"{existing_text}\n{content}".strip() if existing_text else content - - p.write_text(new_text, encoding="utf-8") - new_version = str(int(p.stat().st_mtime_ns)) - return MemoryMutationResult( - path=path, version=new_version, size_bytes=len(new_text.encode("utf-8")), status="ok" - ) - - def delete(self, path: str, expected_version: str | None = None) -> bool: - p = self._resolve_path(path) - if p.exists() and p.is_file(): - if expected_version is not None: - curr_v = str(int(p.stat().st_mtime_ns)) - if curr_v != expected_version: - raise MemoryOperationConflictError(f"Version mismatch on delete of '{path}'") - p.unlink() - return True - return False - - def list_paths(self, prefix: str = "", limit: int = 100) -> list[str]: - if not self.directory.exists(): - return [] - found: list[str] = [] - for item in sorted(self.directory.rglob("*")): - if item.is_file() and not item.name.startswith("."): - rel = str(item.relative_to(self.directory)) - if rel.startswith(prefix): - found.append(rel) - return found[:limit] - - def search( - self, - query: str, - max_results: int = 10, - max_result_chars: int = 4000, - max_file_chars: int = 65536, - ) -> list[MemorySearchResult]: - q = query.strip().lower() - if not q: - return [] - terms = list(dict.fromkeys(q.split()))[:32] - results: list[MemorySearchResult] = [] - total_chars = 0 - - for path in self.list_paths(limit=1000): - mf = self.read(path, max_chars=max_file_chars) - content_lower = mf.content.lower() - score = sum(content_lower.count(t) for t in terms) - if any(t in path.lower() for t in terms): - score += 5 - if score > 0: - snippet = mf.content[: min(300, max_result_chars)] - results.append(MemorySearchResult(path=path, snippet=snippet, score=float(score))) - total_chars += len(path) + len(snippet) - if len(results) >= max_results or total_chars >= max_result_chars: - break - - results.sort(key=lambda r: r.score, reverse=True) - return results[:max_results] - - -class SqliteMemoryStore(BaseModel): - """Durable memory notebook store kept in a SQLite database file. - - Every call opens its own connection, so ``database`` must name a file all of them share. - ``:memory:`` and the empty name give each connection a private database that is gone once it - closes, so a write reported success that no later read could see; both are refused. - ``InMemoryStore`` keeps memory for the life of the process. - """ - - model_config = ConfigDict(extra="ignore") - - database: str | Path - - @field_validator("database") - @classmethod - def _require_shared_database_file(cls, database: str | Path) -> str | Path: - if os.fspath(database) in CONST_SQLITE_PER_CONNECTION_DATABASES: - raise HarnessValidationError( - f"SqliteMemoryStore needs a database file; {os.fspath(database)!r} gives every " - "connection its own database, which loses each write. Use InMemoryStore for " - "memory that lasts only as long as the process.", - field_name="database", - ) - return database - - def _get_conn(self) -> sqlite3.Connection: - conn = sqlite3.connect(self.database, check_same_thread=False) - conn.execute( - "CREATE TABLE IF NOT EXISTS memory_files (path TEXT PRIMARY KEY, content TEXT, version TEXT, updated_at REAL)" - ) - return conn - - def read(self, path: str, max_chars: int = 65536) -> MemoryFile: - clean = path.strip().lstrip("/") - conn = self._get_conn() - try: - cur = conn.execute("SELECT content, version FROM memory_files WHERE path = ?", (clean,)) - row = cur.fetchone() - if not row: - return MemoryFile(path=clean, content="", version="0", size_bytes=0) - content, version = row[0], row[1] - if len(content) > max_chars: - return MemoryFile( - path=clean, - content=content[:max_chars], - version=version, - truncated=True, - size_bytes=len(content.encode("utf-8")), - ) - return MemoryFile( - path=clean, - content=content, - version=version, - size_bytes=len(content.encode("utf-8")), - ) - finally: - conn.close() - - def write( - self, - path: str, - content: str, - mode: Literal["append", "replace"] = "append", - target_fragment: str | None = None, - replacement: str | None = None, - expected_version: str | None = None, - operation_id: str | None = None, - ) -> MemoryMutationResult: - clean = path.strip().lstrip("/") - conn = self._get_conn() - try: - cur = conn.execute("SELECT content, version FROM memory_files WHERE path = ?", (clean,)) - row = cur.fetchone() - existing = row[0] if row else "" - curr_v = row[1] if row else None - if expected_version is not None and curr_v != expected_version: - raise MemoryOperationConflictError( - f"Version mismatch on '{clean}': expected {expected_version}, got {curr_v}" - ) - - if mode == "replace" and target_fragment is not None: - if target_fragment not in existing: - raise HarnessValidationError( - f"Target fragment not found in memory file '{clean}'" - ) - new_text = existing.replace(target_fragment, replacement or "", 1) - elif mode == "replace": - new_text = content - else: - new_text = f"{existing}\n{content}".strip() if existing else content - - new_v = uuid.uuid4().hex[:12] - now = time.time() - conn.execute( - "INSERT OR REPLACE INTO memory_files (path, content, version, updated_at) VALUES (?, ?, ?, ?)", - (clean, new_text, new_v, now), - ) - conn.commit() - return MemoryMutationResult( - path=clean, version=new_v, size_bytes=len(new_text.encode("utf-8")), status="ok" - ) - finally: - conn.close() - - def delete(self, path: str, expected_version: str | None = None) -> bool: - clean = path.strip().lstrip("/") - conn = self._get_conn() - try: - if expected_version is not None: - cur = conn.execute("SELECT version FROM memory_files WHERE path = ?", (clean,)) - row = cur.fetchone() - if row and row[0] != expected_version: - raise MemoryOperationConflictError(f"Version mismatch on delete of '{clean}'") - cur = conn.execute("DELETE FROM memory_files WHERE path = ?", (clean,)) - conn.commit() - return cur.rowcount > 0 - finally: - conn.close() - - def list_paths(self, prefix: str = "", limit: int = 100) -> list[str]: - clean = prefix.strip().lstrip("/") - conn = self._get_conn() - try: - cur = conn.execute( - "SELECT path FROM memory_files WHERE path LIKE ? ORDER BY path LIMIT ?", - (f"{clean}%", limit), - ) - return [r[0] for r in cur.fetchall()] - finally: - conn.close() - - def search( - self, - query: str, - max_results: int = 10, - max_result_chars: int = 4000, - max_file_chars: int = 65536, - ) -> list[MemorySearchResult]: - q = query.strip().lower() - if not q: - return [] - terms = list(dict.fromkeys(q.split()))[:32] - conn = self._get_conn() - try: - search_limit = max(100, min(max(1000, max_results * 100), 10_000)) - cur = conn.execute( - "SELECT path, content FROM memory_files LIMIT ?", - (search_limit,), - ) - results: list[MemorySearchResult] = [] - total_chars = 0 - for path, content in cur: - content_lower = (content or "")[:max_file_chars].lower() - score = sum(content_lower.count(t) for t in terms) - if any(t in path.lower() for t in terms): - score += 5 - if score <= 0: - continue - snippet = (content or "")[: min(300, max_result_chars)] - results.append(MemorySearchResult(path=path, snippet=snippet, score=float(score))) - total_chars += len(path) + len(snippet) - if len(results) >= max_results or total_chars >= max_result_chars: - break - results.sort(key=lambda r: r.score, reverse=True) - return results[:max_results] - finally: - conn.close() - - -class Memory(BaseCapability): - """Persistent, namespaced agent notebook capability with bounded prompt injection and search.""" - - id: str | None = "memory" - store: Any = Field(default_factory=InMemoryStore) - store_resolver: Any = None - agent_name: str = "main" - heading: str = "" - namespace: Any = "" - inject_memory: bool = True - max_tokens: int = 2000 - max_lines: int = 200 - max_memory_size: int = 65536 - max_search_results: int = 10 - max_search_result_chars: int = 4000 - max_search_files: int = 1000 - injection_errors: Literal["ignore", "raise"] = "ignore" - guidance: str | None = None - tool_prefix: str = "" - - def __init__( - self, - store: Any = None, - *, - store_resolver: Any = None, - agent_name: str = "main", - heading: str = "", - namespace: Any = "", - inject_memory: bool = True, - max_tokens: int = 2000, - max_lines: int = 200, - max_memory_size: int = 65536, - max_search_results: int = 10, - max_search_result_chars: int = 4000, - max_search_files: int = 1000, - injection_errors: Literal["ignore", "raise"] = "ignore", - guidance: str | None = None, - tool_prefix: str = "", - id: str = "memory", - ) -> None: - resolved_store = store if store is not None else InMemoryStore() - super().__init__( - id=str(id or "memory"), - store=resolved_store, - store_resolver=store_resolver, - agent_name=agent_name, - heading=heading, - namespace=namespace, - inject_memory=inject_memory, - max_tokens=max_tokens, - max_lines=max_lines, - max_memory_size=max_memory_size, - max_search_results=max_search_results, - max_search_result_chars=max_search_result_chars, - max_search_files=max_search_files, - injection_errors=injection_errors, - guidance=guidance, - tool_prefix=tool_prefix, - ) - - def prefix_tools(self, prefix: str) -> Memory: # type: ignore[override] - """Return a copy of this Memory capability with prefixed tool names.""" - return Memory( - store=self.store, - store_resolver=self.store_resolver, - agent_name=self.agent_name, - heading=self.heading, - namespace=self.namespace, - inject_memory=self.inject_memory, - max_tokens=self.max_tokens, - max_lines=self.max_lines, - max_memory_size=self.max_memory_size, - max_search_results=self.max_search_results, - max_search_result_chars=self.max_search_result_chars, - max_search_files=self.max_search_files, - injection_errors=self.injection_errors, - guidance=self.guidance, - tool_prefix=prefix, - id=f"{self.id}_{prefix}", - ) - - def _get_active_store(self, ctx: RunContext[Any] | None = None) -> Any: - if self.store_resolver and ctx is not None: - try: - return self.store_resolver(ctx) - except Exception: - if self.injection_errors == "raise": - raise - return self.store - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - additions: list[str] = [] - heading_text = f"## {self.heading}\n\n" if self.heading else "" - guidance = self.guidance or ( - "You have access to a persistent memory notebook across sessions. " - "Use write_memory to record notes, read_memory to view notebooks, and search_memory to retrieve context." - ) - additions.append(f"{heading_text}{guidance}") - - if self.inject_memory: - try: - active_store = self._get_active_store(ctx) - mem_file = active_store.read("MEMORY.md", max_chars=self.max_memory_size) - other_paths = [ - p - for p in active_store.list_paths(limit=self.max_search_files) - if p != "MEMORY.md" - ] - lines = mem_file.content.splitlines()[: self.max_lines] - content_excerpt = "\n".join(lines) - - listing = f"\nOther memory notes: {', '.join(other_paths)}" if other_paths else "" - memory_block = f"\n{content_excerpt}{listing}\n" - additions.append(memory_block) - except Exception: - if self.injection_errors == "raise": - raise - return additions - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 - prefix = f"{self.tool_prefix}_" if self.tool_prefix else "" - store = self.store - - def write_memory( - path: str = "MEMORY.md", - content: str = "", - mode: str = "append", - target_fragment: str | None = None, - replacement: str | None = None, - ) -> str: - """Write or append text notes to a memory file, or replace a unique text fragment.""" - try: - res = store.write( - path=path, - content=content, - mode="replace" if mode == "replace" else "append", - target_fragment=target_fragment, - replacement=replacement, - ) - return f"Memory updated: '{res.path}' (version: {res.version}, size: {res.size_bytes} bytes)" - except Exception as e: - return f"Error writing to memory '{path}': {e}" - - def read_memory(path: str = "MEMORY.md", max_chars: int = 65536) -> str: - """Read a bounded prefix of a memory notebook file.""" - try: - clamped = min(max(1, max_chars), self.max_memory_size) - f = store.read(path, max_chars=clamped) - trunc_note = " [truncated]" if f.truncated else "" - return f"--- {f.path} (v{f.version}){trunc_note} ---\n{f.content}" - except Exception as e: - return f"Error reading memory '{path}': {e}" - - def delete_memory(path: str) -> str: - """Delete a memory file. The main notebook MEMORY.md is protected.""" - clean = path.strip().lstrip("/") - if clean == "MEMORY.md": - return "Error: Cannot delete protected root notebook MEMORY.md" - try: - ok = store.delete(clean) - return f"Deleted memory '{clean}'" if ok else f"Memory '{clean}' not found" - except Exception as e: - return f"Error deleting memory '{path}': {e}" - - def search_memory(query: str, max_results: int = 10) -> str: - """Search across persistent memory notebook files.""" - try: - clamped_k = min(max(1, max_results), self.max_search_results) - search_fn = getattr(store, "search", None) - if not callable(search_fn): - return f"No memory entries matching query '{query}'." - matches = search_fn( - query=query, - max_results=clamped_k, - max_result_chars=self.max_search_result_chars, - max_file_chars=self.max_memory_size, - ) - if not matches: - return f"No memory entries matching query '{query}'." - lines = [f"Found {len(matches)} memory match(es):"] - lines.extend(f"- **{m.path}** (score: {m.score:.1f}): {m.snippet}" for m in matches) - return "\n".join(lines) - except Exception as e: - return f"Error searching memory: {e}" - - return [ - Tool.from_function( - write_memory, - name=f"{prefix}write_memory", - description="Append to or replace content in persistent memory notebooks.", - ), - Tool.from_function( - read_memory, - name=f"{prefix}read_memory", - description="Read content from a persistent memory notebook file.", - ), - Tool.from_function( - delete_memory, - name=f"{prefix}delete_memory", - description="Delete a non-root memory note from persistent storage.", - ), - Tool.from_function( - search_memory, - name=f"{prefix}search_memory", - description="Search across notebook files in persistent memory.", - ), - ] diff --git a/src/devops_cli/ai/harness/planning.py b/src/devops_cli/ai/harness/planning.py deleted file mode 100644 index b04db8df9c..0000000000 --- a/src/devops_cli/ai/harness/planning.py +++ /dev/null @@ -1,718 +0,0 @@ -"""Planning capability and plan stores for multi-step task tracking.""" - -from __future__ import annotations - -import contextlib -import json -import logging -import sqlite3 -import uuid -from collections import defaultdict -from collections.abc import Callable, Sequence -from pathlib import Path -from typing import Any, Literal, cast - -from pydantic import BaseModel, Field -from pydantic_ai.tools import RunContext - -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.context import AgentHooks -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.ai.harness.constants import DEFAULT_PLANNING_GUIDANCE -from devops_cli.core.paths import is_forbidden_system_path, validate_no_path_traversal -from devops_cli.exceptions.ai import HarnessValidationError -from devops_cli.exceptions.security import SecurityError -from devops_cli.models.ai import ChatMessage - -logger = logging.getLogger(__name__) - -PlanStatus = Literal["pending", "in_progress", "completed", "cancelled", "blocked"] - - -class PlanItem(BaseModel): - """Structured plan task item.""" - - id: str = Field(default_factory=lambda: f"task-{uuid.uuid4().hex}") - content: str - active_form: str | None = None - status: PlanStatus = "pending" - parent_id: str | None = None - depends_on: list[str] = Field(default_factory=list) - - -class PlanEvent(BaseModel): - """Event emitted upon plan mutations.""" - - event_type: str - item: PlanItem - old_status: str | None = None - new_status: str | None = None - - -class PlanEventEmitter: - """Event emitter managing lifecycle callbacks for plan task state changes.""" - - def __init__(self) -> None: - self._listeners: dict[str, list[Callable[[PlanEvent], Any]]] = defaultdict(list) - - def on( - self, event_type: str, handler: Callable[[PlanEvent], Any] - ) -> Callable[[PlanEvent], Any]: - self._listeners[event_type].append(handler) - return handler - - def on_completed(self, handler: Callable[[PlanEvent], Any]) -> Callable[[PlanEvent], Any]: - return self.on("completed", handler) - - def on_status_changed(self, handler: Callable[[PlanEvent], Any]) -> Callable[[PlanEvent], Any]: - return self.on("status_changed", handler) - - def on_task_added(self, handler: Callable[[PlanEvent], Any]) -> Callable[[PlanEvent], Any]: - return self.on("task_added", handler) - - def emit(self, event: PlanEvent) -> None: - for handler in self._listeners.get(event.event_type, []): - try: - handler(event) - except Exception: - pass - - -class PlanStore: - """Abstract interface for plan storage backends.""" - - def __init__(self, event_emitter: PlanEventEmitter | None = None) -> None: - self.event_emitter = event_emitter - - def get_items(self) -> list[PlanItem]: - raise NotImplementedError - - def set_items(self, items: list[PlanItem]) -> None: - raise NotImplementedError - - def add_item(self, item: PlanItem) -> PlanItem: - raise NotImplementedError - - def update_item_status(self, item_id: str, status: PlanStatus) -> bool: - raise NotImplementedError - - def remove_item(self, item_id: str) -> bool: - raise NotImplementedError - - def to_xml(self, root_tag: str = "plan_reminder") -> str: - """Serialize store plan items as XML using native Pydantic AI format_as_xml.""" - from devops_cli.ai.format_prompt import format_plan_reminder_as_xml - - return format_plan_reminder_as_xml(self.get_items(), root_tag=root_tag) - - -def _make_status_event(item: PlanItem, old: str, new_status: str) -> PlanEvent: - """Construct a PlanEvent for status transitions.""" - ev_type = "completed" if new_status == "completed" else "status_changed" - return PlanEvent(event_type=ev_type, item=item, old_status=old, new_status=new_status) - - -_STATUS_ICONS: dict[str, str] = { - "completed": "[✓]", - "in_progress": "[>]", - "cancelled": "[x]", - "blocked": "[!]", -} - - -def _status_icon(status: str) -> str: - """Return progress box icon for a step status.""" - return _STATUS_ICONS.get(status, "[ ]") - - -class InMemoryPlanStore(PlanStore): - """In-memory plan storage backend.""" - - def __init__( - self, - items: list[PlanItem] | None = None, - event_emitter: PlanEventEmitter | None = None, - ) -> None: - super().__init__(event_emitter=event_emitter) - self._items: list[PlanItem] = list(items or []) - - def get_items(self) -> list[PlanItem]: - return list(self._items) - - def set_items(self, items: list[PlanItem]) -> None: - self._items = list(items) - - def add_item(self, item: PlanItem) -> PlanItem: - self._items.append(item) - if self.event_emitter: - self.event_emitter.emit(PlanEvent(event_type="task_added", item=item)) - return item - - def update_item_status(self, item_id: str, status: PlanStatus) -> bool: - for item in self._items: - if item.id == item_id: - old = item.status - item.status = status - if self.event_emitter: - self.event_emitter.emit(_make_status_event(item, old, status)) - return True - return False - - def remove_item(self, item_id: str) -> bool: - initial_len = len(self._items) - self._items = [it for it in self._items if it.id != item_id] - return len(self._items) < initial_len - - def add( - self, - content: str, - status: PlanStatus = "pending", - active_form: str | None = None, - ) -> PlanItem: - """Ergonomic helper to add a plan item by content.""" - item = PlanItem(content=content, status=status, active_form=active_form) - return self.add_item(item) - - -PlanningStore = InMemoryPlanStore - - -class SqlitePlanStore(PlanStore): - """SQLite-backed plan storage backend persisted across sessions.""" - - def __init__( - self, - db_path: str | Path = ":memory:", - session: str = "default", - event_emitter: PlanEventEmitter | None = None, - ) -> None: - super().__init__(event_emitter=event_emitter) - raw_path = str(db_path) - if raw_path != ":memory:": - validate_no_path_traversal(raw_path, label="SqlitePlanStore db_path") - resolved_path = Path(raw_path).resolve() - if is_forbidden_system_path(resolved_path): - raise SecurityError( - f"SqlitePlanStore db_path cannot reside in forbidden system directory: '{raw_path}'." - ) - import tempfile - - allowed_bases = [ - Path.cwd().resolve(), - Path.home().resolve(), - Path(tempfile.gettempdir()).resolve(), - ] - if not any( - resolved_path == b or resolved_path.is_relative_to(b) for b in allowed_bases - ): - raise SecurityError( - f"SqlitePlanStore db_path '{raw_path}' must reside within authorized project, home, or temp directory." - ) - self.db_path = raw_path - self.session = session - self._init_db() - - def _init_db(self) -> None: - with contextlib.closing(sqlite3.connect(self.db_path)) as conn: - conn.execute( - """ - CREATE TABLE IF NOT EXISTS plan_items ( - session TEXT NOT NULL, - id TEXT NOT NULL, - content TEXT NOT NULL, - active_form TEXT, - status TEXT NOT NULL, - parent_id TEXT, - depends_on TEXT, - sequence_num INTEGER NOT NULL, - PRIMARY KEY (session, id) - ) - """ - ) - conn.commit() - - def get_items(self) -> list[PlanItem]: - with contextlib.closing(sqlite3.connect(self.db_path)) as conn: - cur = conn.execute( - "SELECT id, content, active_form, status, parent_id, depends_on FROM plan_items WHERE session = ? ORDER BY sequence_num ASC", - (self.session,), - ) - return [ - PlanItem( - id=r[0], - content=r[1], - active_form=r[2], - status=r[3], - parent_id=r[4], - depends_on=json.loads(r[5]) if r[5] else [], - ) - for r in cur.fetchall() - ] - - def set_items(self, items: list[PlanItem]) -> None: - params = [ - ( - self.session, - it.id, - it.content, - it.active_form, - it.status, - it.parent_id, - json.dumps(it.depends_on), - idx, - ) - for idx, it in enumerate(items) - ] - with contextlib.closing(sqlite3.connect(self.db_path)) as conn: - conn.execute("DELETE FROM plan_items WHERE session = ?", (self.session,)) - conn.executemany( - "INSERT INTO plan_items (session, id, content, active_form, status, parent_id, depends_on, sequence_num) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - params, - ) - conn.commit() - - def add_item(self, item: PlanItem) -> PlanItem: - with contextlib.closing(sqlite3.connect(self.db_path)) as conn: - row = conn.execute( - "SELECT COALESCE(MAX(sequence_num), -1) FROM plan_items WHERE session = ?", - (self.session,), - ).fetchone() - max_seq = row[0] if row else -1 - conn.execute( - "INSERT OR REPLACE INTO plan_items (session, id, content, active_form, status, parent_id, depends_on, sequence_num) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - ( - self.session, - item.id, - item.content, - item.active_form, - item.status, - item.parent_id, - json.dumps(item.depends_on), - max_seq + 1, - ), - ) - conn.commit() - if self.event_emitter: - self.event_emitter.emit(PlanEvent(event_type="task_added", item=item)) - return item - - def update_item_status(self, item_id: str, status: PlanStatus) -> bool: - with contextlib.closing(sqlite3.connect(self.db_path)) as conn: - cur = conn.execute( - "UPDATE plan_items SET status = ? WHERE session = ? AND id = ?", - (status, self.session, item_id), - ) - conn.commit() - updated = cur.rowcount > 0 - - if updated and self.event_emitter: - items = [it for it in self.get_items() if it.id == item_id] - if items: - self.event_emitter.emit(_make_status_event(items[0], items[0].status, status)) - return updated - - def remove_item(self, item_id: str) -> bool: - with contextlib.closing(sqlite3.connect(self.db_path)) as conn: - cur = conn.execute( - "DELETE FROM plan_items WHERE session = ? AND id = ?", - (self.session, item_id), - ) - conn.commit() - return cur.rowcount > 0 - - -class Planning(BaseCapability): - """Structured task planning capability that maintains state and injects cache-safe tail reminders.""" - - id: str | None = "planning" - guidance: str | None = None - cache_ttl: Literal["5m", "1h"] = "5m" - store: Any = None - store_resolver: Any = None - enable_subtasks: bool = False - inject: bool = True - tools: Sequence[str] | None = None - descriptions: dict[str, str] | None = None - plans: list[str] = Field(default_factory=list) - - def __init__( - self, - *, - guidance: str | None = None, - cache_ttl: Literal["5m", "1h"] = "5m", - store: PlanStore | None = None, - store_resolver: Callable[[RunContext[Any]], PlanStore] | None = None, - enable_subtasks: bool = False, - inject: bool = True, - tools: Sequence[str] | None = None, - descriptions: dict[str, str] | None = None, - plans: list[str] | None = None, - ) -> None: - super().__init__( - guidance=guidance, - cache_ttl=cache_ttl, - store=store, - store_resolver=store_resolver, - enable_subtasks=enable_subtasks, - inject=inject, - tools=list(tools) if tools is not None else None, - descriptions=descriptions, - plans=plans or [], - ) - - def resolve_store(self, ctx: RunContext[Any] | None = None) -> PlanStore: - """Resolve active PlanStore from resolver, configured store, or in-memory default.""" - if ctx is not None and self.store_resolver is not None: - return cast(PlanStore, self.store_resolver(ctx)) - if self.store is not None: - return cast(PlanStore, self.store) - mem = InMemoryPlanStore() - if self.plans: - mem.set_items([PlanItem(content=p, status="pending") for p in self.plans]) - self.store = mem - return mem - - def _unblock_dependent_items(self, store: PlanStore, task_id: str) -> None: - """Unblock items whose dependencies are all satisfied.""" - items = store.get_items() - unresolved = {x.id for x in items if x.status not in ("completed", "cancelled")} - for it in items: - if task_id in it.depends_on and it.status == "blocked": - if not any(d in unresolved for d in it.depends_on): - store.update_item_status(it.id, "pending") - - def _build_tool( - self, fn: Callable[..., Any], name: str, default_desc: str - ) -> AgentTool | Callable[..., Any]: - """Construct a tool instance using configured override descriptions if present.""" - desc = self.descriptions.get(name, default_desc) if self.descriptions else default_desc - return Tool.from_function(fn, name=name, description=desc) - - def _parse_input_plan_item(self, item: dict[str, Any] | PlanItem | str) -> PlanItem: - """Parse raw dictionary, string, or PlanItem into a canonical PlanItem.""" - if isinstance(item, PlanItem): - if not self.enable_subtasks and ( - item.status == "blocked" or item.parent_id or item.depends_on - ): - raise HarnessValidationError( - "Subtasks and dependency blocking require enable_subtasks=True" - ) - return item - if isinstance(item, str): - return PlanItem(content=item, status="pending") - - status = cast(PlanStatus, item.get("status") or "pending") - parent_id = item.get("parent_id") - depends_on = list(item.get("depends_on") or []) - if not self.enable_subtasks and (status == "blocked" or parent_id or depends_on): - raise HarnessValidationError( - "Subtasks and dependency blocking require enable_subtasks=True" - ) - - return PlanItem( - id=str(item.get("id") or f"task-{uuid.uuid4().hex[:6]}"), - content=str(item.get("content") or item.get("task") or ""), - active_form=item.get("active_form"), - status=status, - parent_id=parent_id, - depends_on=depends_on, - ) - - def _render_hierarchical_plan(self, items: list[PlanItem], summary: str) -> str: - """Render plan as indented hierarchical tree.""" - lines = [summary] - parent_map: dict[str | None, list[PlanItem]] = defaultdict(list) - for it in items: - parent_map[it.parent_id].append(it) - - def _render_node(pid: str | None, indent: int = 0) -> None: - for child in parent_map.get(pid, []): - icon = _status_icon(child.status) - lines.append(f"{' ' * indent}{icon} {child.id}: {child.content}") - _render_node(child.id, indent + 1) - - _render_node(None) - return "\n".join(lines) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 - all_tools: list[AgentTool | Callable[..., Any]] = [] - - def write_plan(items: list[dict[str, Any] | PlanItem | str]) -> str: - """Create or replace the full plan (whole-list replacement).""" - store = self.resolve_store() - parsed = [self._parse_input_plan_item(it) for it in items] - store.set_items(parsed) - self.plans = [it.content for it in parsed] - return f"Plan successfully written with {len(parsed)} steps." - - def read_plan(view: str = "flat") -> str: - """Read the current plan with step ids and progress summary.""" - store = self.resolve_store() - items = store.get_items() - if not items: - return "Plan is currently empty. Use write_plan or add_task to create steps." - - done = sum(1 for it in items if it.status == "completed") - summary = f"Plan Progress: {done}/{len(items)} completed ({round(done / len(items) * 100)}%)\n" - - if view == "hierarchical" and self.enable_subtasks: - return self._render_hierarchical_plan(items, summary) - - lines = [summary] - for it in items: - icon = _status_icon(it.status) - label = ( - f" ({it.active_form})" if it.active_form and it.status == "in_progress" else "" - ) - dep_info = f" [depends on: {', '.join(it.depends_on)}]" if it.depends_on else "" - lines.append(f"{icon} {it.id}: {it.content}{label}{dep_info}") - return "\n".join(lines) - - def add_task(content: str, active_form: str | None = None) -> str: - """Append a single pending step to the plan.""" - store = self.resolve_store() - item = PlanItem(content=content, active_form=active_form, status="pending") - created = store.add_item(item) - self.plans.append(content) - return f"Task '{created.id}' added to plan: {content}" - - def update_task_status(task_id: str, status: PlanStatus) -> str: - """Move one step between statuses by id.""" - store = self.resolve_store() - valid_statuses = ("pending", "in_progress", "completed", "cancelled", "blocked") - if status not in valid_statuses: - return f"Error: invalid status '{status}'. Must be one of {valid_statuses}." - - updated = store.update_item_status(task_id, status) - if not updated: - return f"Error: task id '{task_id}' not found in plan." - - if status in ("completed", "cancelled") and self.enable_subtasks: - self._unblock_dependent_items(store, task_id) - - return f"Task '{task_id}' status updated to '{status}'." - - def update_task_statuses(updates: list[dict[str, str]]) -> str: - """Apply several status changes in one call, validated all-or-nothing.""" - store = self.resolve_store() - items = {it.id: it for it in store.get_items()} - for u in updates: - tid = u.get("id") or u.get("task_id") - st = u.get("status") - if not tid or tid not in items: - return f"Error: task id '{tid}' not found. No updates applied." - if st not in ("pending", "in_progress", "completed", "cancelled", "blocked"): - return f"Error: invalid status '{st}'. No updates applied." - - for u in updates: - tid = str(u.get("id") or u.get("task_id")) - st = cast(PlanStatus, u.get("status")) - store.update_item_status(tid, st) - - return f"Successfully updated statuses for {len(updates)} tasks." - - def remove_task(task_id: str) -> str: - """Delete a step from the plan by id.""" - store = self.resolve_store() - removed = store.remove_item(task_id) - if not removed: - return f"Error: task id '{task_id}' not found." - return f"Task '{task_id}' removed from plan." - - def update_plan(steps: list[str]) -> str: - """Update the execution plan with structured checklist items.""" - return write_plan([{"content": s, "status": "pending"} for s in steps]) - - all_tools.extend( - [ - self._build_tool(write_plan, "write_plan", "Create or replace the full plan."), - self._build_tool( - read_plan, "read_plan", "Read the current plan with step ids and status." - ), - self._build_tool(add_task, "add_task", "Append a single pending step to the plan."), - self._build_tool( - update_task_status, - "update_task_status", - "Move one step between statuses by id.", - ), - self._build_tool( - update_task_statuses, - "update_task_statuses", - "Apply several status changes in one batch call.", - ), - self._build_tool(remove_task, "remove_task", "Delete a step from the plan by id."), - self._build_tool( - update_plan, - "update_plan", - "Update the current multi-step execution plan (string list).", - ), - ] - ) - - if self.enable_subtasks: - - def add_subtask(parent_id: str, content: str, active_form: str | None = None) -> str: - """Add a child step under a parent step.""" - store = self.resolve_store() - items = {it.id: it for it in store.get_items()} - if parent_id not in items: - return f"Error: parent task id '{parent_id}' not found." - sub = PlanItem( - content=content, active_form=active_form, status="pending", parent_id=parent_id - ) - created = store.add_item(sub) - return f"Subtask '{created.id}' added under parent '{parent_id}': {content}" - - def set_dependency(task_id: str, depends_on_id: str) -> str: - """Make one step wait for another prerequisite step.""" - if task_id == depends_on_id: - return "Error: self-dependency not allowed." - store = self.resolve_store() - items = {it.id: it for it in store.get_items()} - if task_id not in items: - return f"Error: task id '{task_id}' not found." - if depends_on_id not in items: - return f"Error: prerequisite task id '{depends_on_id}' not found." - - target = items[task_id] - prereq = items[depends_on_id] - if task_id in prereq.depends_on: - return "Error: circular dependency detected." - - if depends_on_id in target.depends_on: - return f"Task '{task_id}' already depends on '{depends_on_id}' (status: {target.status})." - - target.depends_on.append(depends_on_id) - if prereq.status not in ("completed", "cancelled"): - target.status = "blocked" - store.set_items(list(items.values())) - return ( - f"Task '{task_id}' now depends on '{depends_on_id}' (status: {target.status})." - ) - - def get_available_tasks() -> str: - """List steps with no incomplete dependencies that can start now.""" - store = self.resolve_store() - items = store.get_items() - resolved = {it.id for it in items if it.status in ("completed", "cancelled")} - available = [ - it - for it in items - if it.status in ("pending", "in_progress") - and all(dep in resolved for dep in it.depends_on) - ] - if not available: - return "No tasks currently available to start." - return f"Available tasks ({len(available)}):\n" + "\n".join( - f"- {it.id}: {it.content} [{it.status}]" for it in available - ) - - all_tools.extend( - [ - self._build_tool( - add_subtask, "add_subtask", "Add a child step under a parent." - ), - self._build_tool( - set_dependency, - "set_dependency", - "Make one step wait for another prerequisite step.", - ), - self._build_tool( - get_available_tasks, - "get_available_tasks", - "List steps with no incomplete dependencies.", - ), - ] - ) - - if self.tools is not None: - tool_set = set(self.tools) - registered_names = {getattr(t, "name", "") for t in all_tools} - unknown = tool_set - registered_names - if unknown: - raise HarnessValidationError( - f"Unknown tool(s) requested for Planning capability: {unknown}" - ) - return [t for t in all_tools if getattr(t, "name", "") in tool_set] - - return all_tools - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - if self.guidance == "": - return [] - return [self.guidance or DEFAULT_PLANNING_GUIDANCE] - - def get_hooks(self) -> AgentHooks | None: - if not self.inject: - return None - - def _inject_plan_reminder(ctx: RunContext[Any], messages: list[ChatMessage]) -> None: - store = self.resolve_store(ctx) - items = store.get_items() - if not items: - return - - done = sum(1 for it in items if it.status == "completed") - in_prog = [it for it in items if it.status == "in_progress"] - prog_str = f"[{done}/{len(items)} completed" - if in_prog: - prog_str += f", in progress: '{in_prog[0].content}'" - prog_str += "]" - - rendered_lines = [f""] - for it in items: - st_icon = ( - "[✓]" - if it.status == "completed" - else "[>]" - if it.status == "in_progress" - else "[x]" - if it.status == "cancelled" - else "[!]" - if it.status == "blocked" - else "[ ]" - ) - label = ( - f" ({it.active_form})" if it.active_form and it.status == "in_progress" else "" - ) - rendered_lines.append(f"{st_icon} {it.id}: {it.content}{label}") - rendered_lines.append("") - reminder_text = "\n".join(rendered_lines) - - if messages and messages[-1].role == "user": - messages[-1] = messages[-1].model_copy( - update={"content": f"{messages[-1].content}\n\n{reminder_text}"} - ) - - return AgentHooks(before_model_request=[_inject_plan_reminder]) - - -MINIMUM_EFFORT_FLOOR: str = "low" - -_EFFORT_RANKS: dict[str, int] = { - "minimal": 1, - "low": 2, - "medium": 3, - "high": 4, - "xhigh": 5, - "max": 6, -} - - -def clamp_effort(level: str | bool | None, floor: str = MINIMUM_EFFORT_FLOOR) -> str | bool | None: - """Clamp thinking effort level to a minimum floor. - - Maps None/False to the floor, leaves True (provider default) unchanged, - and raises concrete effort levels below the floor up to the floor. - """ - if level is None or level is False: - return floor - if level is True: - return True - if isinstance(level, str): - level_lower = level.lower() - floor_lower = floor.lower() - rank = _EFFORT_RANKS.get(level_lower, 2) - floor_rank = _EFFORT_RANKS.get(floor_lower, 2) - return floor if rank < floor_rank else level - return floor diff --git a/src/devops_cli/ai/harness/repo_context.py b/src/devops_cli/ai/harness/repo_context.py deleted file mode 100644 index 535e390989..0000000000 --- a/src/devops_cli/ai/harness/repo_context.py +++ /dev/null @@ -1,344 +0,0 @@ -"""RepoContext capability for inspecting workspace repositories and assets.""" - -from __future__ import annotations - -import hashlib -import json -import logging -from collections.abc import Callable, Sequence -from pathlib import Path -from typing import Any, Literal - -from pydantic import BaseModel, ConfigDict, Field -from pydantic_ai.tools import RunContext - -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool - -logger = logging.getLogger(__name__) - - -class AssetRoot(BaseModel): - """Where context engineering assets live under a single root directory (e.g. .claude, .agents).""" - - model_config = ConfigDict(extra="ignore") - - root: str - exists: bool = False - path: Path - skills: list[str] = Field(default_factory=list) - agents: list[str] = Field(default_factory=list) - hooks: list[str] = Field(default_factory=list) - - -class AgentContextInventory(BaseModel): - """A structured map of where a repository's context engineering assets live.""" - - model_config = ConfigDict(extra="ignore") - - workspace_dir: Path - roots: dict[str, AssetRoot] = Field(default_factory=dict) - discovered_instruction_files: list[Path] = Field(default_factory=list) - - -def _format_nested_candidate_note( - candidate: Path, fname: str, target_dir: Path, nested_inject: str -) -> str: - """Format note for nested candidate instruction file.""" - if nested_inject == "pointer": - return f"\n\n[RepoContext: Note that {fname} is present in {target_dir.name}/]" - try: - c = candidate.read_text(encoding="utf-8").strip() - return f"\n\n# Context from {candidate.name}:\n{c}" - except Exception: - return f"\n\n[RepoContext: {fname} present]" - - -def _format_root_inventory_lines(r_name: str, r: Any) -> list[str]: - """Format single inventory root lines.""" - if not r.exists: - return [f" - {r_name}: (not present)"] - res = [f" - **{r_name}** ({r.path}):"] - if r.skills: - res.append(f" skills: {', '.join(r.skills)}") - if r.agents: - res.append(f" agents: {', '.join(r.agents)}") - if r.hooks: - res.append(f" hooks: {', '.join(r.hooks)}") - return res - - -class RepoContext(BaseCapability): - """Capability that discovers and loads a repository's accumulated coding-assistant context engineering.""" - - id: str | None = "repo_context" - workspace_dir: Path = Field(default_factory=lambda: Path(".")) - home_dir: Path | None = None - filenames: tuple[str, ...] = ("CLAUDE.md", "AGENTS.md") - autoload_instructions: bool = True - expose_inventory_tool: bool = True - inventory_tool_name: str = "inventory_agent_context" - nested_traversal: bool = False - nested_inject: Literal["pointer", "contents"] = "pointer" - traversal_tool_names: frozenset[str] = Field( - default_factory=lambda: frozenset({"list_directory", "read_file", "list_dir", "view_file"}) - ) - traversal_path_arg: str = "path" - asset_roots: tuple[str, ...] = (".claude", ".agents", ".codex", ".grok") - surfaced_directories: set[str] = Field(default_factory=set) - - def __init__( - self, - workspace_dir: str | Path = Path("."), - *, - home_dir: str | Path | None = None, - filenames: Sequence[str] = ("CLAUDE.md", "AGENTS.md"), - autoload_instructions: bool = True, - expose_inventory_tool: bool = True, - inventory_tool_name: str = "inventory_agent_context", - nested_traversal: bool = False, - nested_inject: Literal["pointer", "contents"] = "pointer", - traversal_tool_names: frozenset[str] | Sequence[str] | None = None, - traversal_path_arg: str = "path", - asset_roots: Sequence[str] = (".claude", ".agents", ".codex", ".grok"), - id: str | None = "repo_context", - ) -> None: - ws_path = Path(workspace_dir).resolve() - h_path = Path(home_dir).resolve() if home_dir is not None else None - t_names = ( - frozenset(traversal_tool_names) - if traversal_tool_names is not None - else frozenset({"list_directory", "read_file", "list_dir", "view_file"}) - ) - super().__init__( - id=str(id or "repo_context"), - workspace_dir=ws_path, - home_dir=h_path, - filenames=tuple(filenames), - autoload_instructions=autoload_instructions, - expose_inventory_tool=expose_inventory_tool, - inventory_tool_name=inventory_tool_name, - nested_traversal=nested_traversal, - nested_inject=nested_inject, - traversal_tool_names=t_names, - traversal_path_arg=traversal_path_arg, - asset_roots=tuple(asset_roots), - ) - - def for_run(self, ctx: RunContext[Any] | None = None) -> RepoContext: # type: ignore[override] - """Return a fresh per-run instance with isolated traversal/cache state.""" - return RepoContext( - workspace_dir=self.workspace_dir, - home_dir=self.home_dir, - filenames=self.filenames, - autoload_instructions=self.autoload_instructions, - expose_inventory_tool=self.expose_inventory_tool, - inventory_tool_name=self.inventory_tool_name, - nested_traversal=self.nested_traversal, - nested_inject=self.nested_inject, - traversal_tool_names=self.traversal_tool_names, - traversal_path_arg=self.traversal_path_arg, - asset_roots=self.asset_roots, - id=self.id, - ) - - def _resolve_ancestor_chain(self) -> list[Path]: - """Resolve ancestor directory chain from home_dir down to workspace_dir (ancestor-first).""" - chain: list[Path] = [self.workspace_dir] - if self.home_dir is not None: - curr = self.workspace_dir.parent - while True: - chain.append(curr) - if curr == self.home_dir or curr.parent == curr: - break - curr = curr.parent - chain.reverse() - return chain - - def _try_add_discovered_file( - self, fpath: Path, seen_resolved: set[Path], seen_hashes: set[str], discovered: list[Path] - ) -> None: - """Attempt to add a resolved unique instruction file.""" - if not fpath.is_file(): - return - resolved = fpath.resolve() - if resolved in seen_resolved: - return - try: - content = resolved.read_text(encoding="utf-8") - chash = hashlib.sha256(content.encode("utf-8")).hexdigest() - if chash in seen_hashes: - return - seen_resolved.add(resolved) - seen_hashes.add(chash) - discovered.append(resolved) - except Exception: - pass - - def discover(self) -> list[Path]: - """Discover instruction files traversing ancestors up to stop_at root.""" - chain = self._resolve_ancestor_chain() - discovered: list[Path] = [] - seen_resolved: set[Path] = set() - seen_hashes: set[str] = set() - - for d in chain: - if not d.exists() or not d.is_dir(): - continue - for fname in self.filenames: - self._try_add_discovered_file(d / fname, seen_resolved, seen_hashes, discovered) - return discovered - - def _scan_skills_dir(self, skills_dir: Path) -> list[str]: - """Scan skills directory for subdirectories containing SKILL.md.""" - if not skills_dir.is_dir(): - return [] - return [ - s.name - for s in sorted(skills_dir.iterdir()) - if s.is_dir() and (s / "SKILL.md").is_file() - ] - - def _scan_agents_dir(self, agents_dir: Path) -> list[str]: - """Scan agents directory for agent specification files and directories.""" - if not agents_dir.is_dir(): - return [] - agents: list[str] = [] - for a in sorted(agents_dir.iterdir()): - if a.is_file() and a.suffix == ".md": - agents.append(a.stem) - elif a.is_dir() and (a / "AGENT.md").is_file(): - agents.append(a.name) - return agents - - def _scan_hooks(self, r_path: Path) -> list[str]: - """Scan and validate hook configuration files in asset root.""" - import re - - hooks: list[str] = [] - for h_candidate in [r_path / "settings.json", r_path / "hooks.json"]: - if not h_candidate.is_file(): - continue - try: - parsed = json.loads(h_candidate.read_text(encoding="utf-8")) - if isinstance(parsed, dict): - valid_keys = [ - k - for k in parsed.keys() - if isinstance(k, str) and re.match(r"^[a-zA-Z0-9_\-\.:/]+$", k) - ] - hooks.extend(valid_keys) - except Exception: - pass - return hooks - - def inventory(self) -> AgentContextInventory: - """Collect structured inventory of context engineering roots, skills, agents, and hooks.""" - roots_map: dict[str, AssetRoot] = {} - for r_name in self.asset_roots: - r_path = self.workspace_dir / r_name - if not r_path.exists() or not r_path.is_dir(): - roots_map[r_name] = AssetRoot(root=r_name, exists=False, path=r_path) - continue - - roots_map[r_name] = AssetRoot( - root=r_name, - exists=True, - path=r_path, - skills=self._scan_skills_dir(r_path / "skills"), - agents=self._scan_agents_dir(r_path / "agents"), - hooks=self._scan_hooks(r_path), - ) - - inst_files = self.discover() - return AgentContextInventory( - workspace_dir=self.workspace_dir, - roots=roots_map, - discovered_instruction_files=inst_files, - ) - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - additions: list[str] = [] - if self.autoload_instructions: - files = self.discover() - for f in files: - try: - rel = f.relative_to(self.workspace_dir) - except ValueError: - rel = f - content = f.read_text(encoding="utf-8").strip() - if content: - additions.append(f"# Repository Instructions ({rel}):\n{content}") - - if self.expose_inventory_tool: - additions.append( - f"You have access to the '{self.inventory_tool_name}' tool to inspect context engineering assets (.claude, .agents, skills, sub-agents)." - ) - return additions - - def after_tool_execute( # type: ignore[override] - self, - tool_name: str, - args: dict[str, Any], - result: Any, - ) -> Any: - """Strategy 3: append a directory's instruction file to a list/read result.""" - if not self.nested_traversal or tool_name not in self.traversal_tool_names: - return result - - path_val = ( - args.get(self.traversal_path_arg) - or args.get("path") - or args.get("dir") - or args.get("directory") - ) - if not path_val: - return result - - target_path = Path(path_val) - if not target_path.is_absolute(): - target_path = self.workspace_dir / target_path - if target_path.is_file() or target_path.suffix: - target_dir = target_path.parent - else: - target_dir = target_path - - dir_key = str(target_dir.resolve()) - if dir_key in self.surfaced_directories: - return result - - for fname in self.filenames: - candidate = target_dir / fname - if candidate.is_file(): - self.surfaced_directories.add(dir_key) - note = _format_nested_candidate_note( - candidate, fname, target_dir, self.nested_inject - ) - return f"{result}{note}" - return result - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - if not self.expose_inventory_tool: - return [] - - inv_fn = self.inventory - - def inventory_agent_context() -> str: - """Inspect where context engineering assets live across .claude, .agents, .codex, and .grok.""" - inv = inv_fn() - lines = [f"Repository Context Inventory ({inv.workspace_dir}):"] - if inv.discovered_instruction_files: - lines.append("Instruction files:") - lines.extend(f" - {inst}" for inst in inv.discovered_instruction_files) - lines.append("Asset roots:") - for r_name, r in sorted(inv.roots.items()): - lines.extend(_format_root_inventory_lines(r_name, r)) - return "\n".join(lines) - - return [ - Tool.from_function( - inventory_agent_context, - name=self.inventory_tool_name, - description="Report where the repository's context engineering assets (skills, agents, hooks) live.", - ) - ] diff --git a/src/devops_cli/ai/harness/shell.py b/src/devops_cli/ai/harness/shell.py deleted file mode 100644 index 1bdc109fbe..0000000000 --- a/src/devops_cli/ai/harness/shell.py +++ /dev/null @@ -1,447 +0,0 @@ -"""Shell capability for executing sandboxed shell commands.""" - -from __future__ import annotations - -import fnmatch -import logging -import os -import shlex -import signal -import subprocess -import threading -import time -from collections import deque -from collections.abc import Callable -from dataclasses import dataclass, field -from pathlib import Path -from typing import IO, Any - -from pydantic import Field - -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.ai.harness.constants import ( - DEFAULT_DENIED_COMMANDS, - INTERACTIVE_COMMANDS, - LLM_API_KEY_ENV_PATTERNS, -) -from devops_cli.config.defaults import ( - DEFAULT_SHELL_BG_OUTPUT_LINES, - DEFAULT_SHELL_DRAIN_TIMEOUT_SECONDS, - DEFAULT_SHELL_STOP_GRACE_SECONDS, - DEFAULT_SHELL_STOP_POLL_SECONDS, -) -from devops_cli.exceptions.ai import HarnessValidationError - -logger = logging.getLogger(__name__) - - -@dataclass(slots=True) -class _OutputRing: - """A bounded line buffer handed off between a pipe reader thread and the tool caller. - - The lock is not optional: a ``deque`` raises if it is mutated while being iterated, and - the reader thread appends continuously while the agent may call ``check_command`` at any - moment. ``seen`` outlives the evicted lines so the caller can be told how much scrollback - the cap discarded, rather than handed a truncated view that reads as the whole of it. - """ - - lines: deque[str] - lock: threading.Lock = field(default_factory=threading.Lock) - seen: int = 0 - - def append(self, line: str) -> None: - with self.lock: - self.lines.append(line) - self.seen += 1 - - def render(self) -> str: - with self.lock: - dropped = self.seen - len(self.lines) - text = "".join(self.lines) - return f"[... {dropped} earlier line(s) dropped ...]\n{text}" if dropped else text - - -@dataclass(slots=True) -class _BackgroundCommand: - """A backgrounded process paired with the ring buffers its reader threads drain into.""" - - process: subprocess.Popen[str] - stdout: _OutputRing - stderr: _OutputRing - readers: tuple[threading.Thread, ...] = () - - def settle(self, timeout: float = DEFAULT_SHELL_DRAIN_TIMEOUT_SECONDS) -> None: - """Wait for the reader threads once the process itself has exited. - - `poll()` reports an exit status as soon as the child is reaped, which is before the - readers have necessarily banked what was still sitting in the pipes. Rendering at - that moment produced a report saying FINISHED beside truncated output, and the - missing lines never arrived because nothing read the rings again. - """ - for reader in self.readers: - reader.join(timeout=timeout) - - -def _drain_pipe(stream: IO[str] | None, sink: _OutputRing) -> None: - """Pump one pipe into its ring buffer until EOF. - - A pipe nobody reads fills its kernel buffer (64 KiB on Linux) and then blocks the child - on its next write forever, so the process neither finishes nor releases its concurrency - slot. Errors are swallowed because this runs on a detached thread where a traceback would - reach the operator's terminal instead of the caller, and a closed or broken pipe simply - means the command is over. - """ - if stream is None: - return - try: - with stream: - for line in stream: - sink.append(line) - except OSError, ValueError: - logger.debug("Background command pipe closed while draining", exc_info=True) - - -def _spawn_reader(stream: IO[str] | None, sink: _OutputRing, name: str) -> threading.Thread: - """Start the daemon thread that drains one pipe, so interpreter exit is never held up.""" - thread = threading.Thread(target=_drain_pipe, args=(stream, sink), name=name, daemon=True) - thread.start() - return thread - - -def _signal_process_group(pgid: int, sig: int) -> bool: - """Send ``sig`` to the group, returning False once no member is left to receive it. - - Signal 0 only probes whether a member still exists. A group this process may not signal is - reported and treated as out of reach, since signalling it again cannot succeed either. - """ - try: - os.killpg(pgid, sig) - except ProcessLookupError: - return False - except PermissionError: - name = signal.Signals(sig).name if sig else "signal 0" - logger.warning("Not permitted to signal process group %s with %s", pgid, name) - return False - return True - - -def _check_shell_syntax(command: str, denied_operators: list[str]) -> tuple[bool, str, list[str]]: - """Validate shell operators, shlex parsing, and path traversal.""" - if not command.strip(): - return False, "Error: empty command", [] - - for op in denied_operators: - if op in command: - return False, f"Shell operator '{op}' is blocked by security policy.", [] - - try: - parts = shlex.split(command) - except Exception as exc: - return False, f"Command parsing error: {exc}", [] - - if not parts: - return False, "Error: empty command", [] - - if any(".." in part for part in parts): - return False, "Path traversal in command arguments is blocked by security policy.", [] - - return True, "", parts - - -def _check_command_permissions( - cmd_name: str, - full_cmd: str, - allowed: list[str], - denied: list[str], - allow_interactive: bool, -) -> tuple[bool, str]: - """Validate command against interactive policy, allowlist, and denylist.""" - if not allow_interactive and cmd_name in INTERACTIVE_COMMANDS: - return False, f"Interactive command '{cmd_name}' is blocked in non-interactive agent shell." - - if allowed: - if cmd_name not in allowed and full_cmd not in allowed: - return False, f"Command '{cmd_name}' is blocked by security allowlist." - return True, "" - - if denied and ( - cmd_name in denied - or full_cmd in denied - or any(cmd_name.startswith(f"{d}.") for d in denied) - ): - return False, f"Command '{cmd_name}' is blocked by security denylist." - - return True, "" - - -class Shell(BaseCapability): - """Capability for executing shell commands with allowlists, denylists, background processes, and credential stripping.""" - - id: str | None = "shell" - cwd: Path = Field(default_factory=lambda: Path(".")) - allowed_commands: list[str] = Field(default_factory=list) - denied_commands: list[str] = Field(default_factory=lambda: list(DEFAULT_DENIED_COMMANDS)) - denied_operators: list[str] = Field(default_factory=list) - allow_interactive: bool = False - env: dict[str, str] | None = None - denied_env_patterns: list[str] = Field(default_factory=lambda: list(LLM_API_KEY_ENV_PATTERNS)) - timeout: float = 60.0 - max_output_chars: int = 20000 - max_bg_processes: int = 10 - max_bg_output_lines: int = DEFAULT_SHELL_BG_OUTPUT_LINES - stop_grace_seconds: float = DEFAULT_SHELL_STOP_GRACE_SECONDS - - def __init__( - self, - cwd: Path | str = ".", - *, - allowed_commands: list[str] | None = None, - denied_commands: list[str] | None = None, - denied_operators: list[str] | None = None, - allow_interactive: bool = False, - env: dict[str, str] | None = None, - denied_env_patterns: list[str] | None = None, - timeout: float = 60.0, - max_output_chars: int = 20000, - max_bg_processes: int = 10, - max_bg_output_lines: int = DEFAULT_SHELL_BG_OUTPUT_LINES, - stop_grace_seconds: float = DEFAULT_SHELL_STOP_GRACE_SECONDS, - ) -> None: - p = Path(cwd) - if allowed_commands is not None and denied_commands is not None: - raise HarnessValidationError( - "allowed_commands and denied_commands are mutually exclusive; specify one or the other." - ) - super().__init__( - cwd=p, - allowed_commands=allowed_commands or [], - denied_commands=list(DEFAULT_DENIED_COMMANDS) - if denied_commands is None and not allowed_commands - else (denied_commands or []), - denied_operators=denied_operators or [], - allow_interactive=allow_interactive, - env=env, - denied_env_patterns=list(LLM_API_KEY_ENV_PATTERNS) - if denied_env_patterns is None - else denied_env_patterns, - timeout=timeout, - max_output_chars=max_output_chars, - max_bg_processes=max_bg_processes, - max_bg_output_lines=max_bg_output_lines, - stop_grace_seconds=stop_grace_seconds, - ) - - def _sanitize_env(self) -> dict[str, str]: - - base_env = dict(self.env) if self.env is not None else dict(os.environ) - clean_env: dict[str, str] = {} - for k, v in base_env.items(): - if not any(fnmatch.fnmatch(k.upper(), pat.upper()) for pat in self.denied_env_patterns): - clean_env[k] = v - return clean_env - - def _validate_command(self, command: str) -> tuple[bool, str, list[str]]: - ok, err, parts = _check_shell_syntax(command, self.denied_operators) - if not ok: - return False, err, [] - - cmd_name = Path(parts[0]).name - ok, err = _check_command_permissions( - cmd_name, parts[0], self.allowed_commands, self.denied_commands, self.allow_interactive - ) - if not ok: - return False, err, [] - - return True, "", parts - - def _label_streams(self, stdout: str, stderr: str) -> list[str]: - parts: list[str] = [] - if stdout.strip(): - parts.append(f"[stdout]\n{stdout.strip()}") - if stderr.strip(): - parts.append(f"[stderr]\n{stderr.strip()}") - return parts - - def _cap_output(self, text: str) -> str: - if len(text) <= self.max_output_chars: - return text - return ( - f"[... output truncated, showing last {self.max_output_chars} characters ...]\n" - + text[-self.max_output_chars :] - ) - - def _format_output(self, stdout: str, stderr: str, returncode: int) -> str: - parts = self._label_streams(stdout, stderr) - if returncode != 0: - parts.append(f"[exit code: {returncode}]") - return self._cap_output( - "\n".join(parts) or f"[Command exited with return code {returncode}]" - ) - - def _new_ring(self) -> _OutputRing: - return _OutputRing(lines=deque(maxlen=self.max_bg_output_lines)) - - def _run_sync(self, parts: list[str], env: dict[str, str], exec_timeout: float) -> str: - proc = subprocess.run( - parts, - cwd=str(self.cwd.resolve()), - capture_output=True, - text=True, - timeout=exec_timeout, - env=env, - check=False, - ) - return self._format_output(proc.stdout or "", proc.stderr or "", proc.returncode) - - def _launch_background( - self, parts: list[str], env: dict[str, str], cmd_id: str - ) -> _BackgroundCommand: - """Spawn the process and immediately attach a reader thread to each of its pipes. - - The readers are attached before the caller ever sees the tracking ID so there is no - window in which the child can fill a pipe that nobody is emptying. - """ - proc = subprocess.Popen( - parts, - cwd=str(self.cwd.resolve()), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - # A subprocess writes bytes, not text. Under strict decoding one undecodable - # byte raises `UnicodeDecodeError` inside the reader thread -- and that is a - # `ValueError`, so the handler below closed the pipe and the child died of - # SIGPIPE on its next write. A command is not wrong to emit a stray byte, so - # the byte is replaced rather than the command killed. - errors="replace", - env=env, - start_new_session=True, - ) - record = _BackgroundCommand(process=proc, stdout=self._new_ring(), stderr=self._new_ring()) - record.readers = ( - _spawn_reader(proc.stdout, record.stdout, f"{cmd_id}-stdout"), - _spawn_reader(proc.stderr, record.stderr, f"{cmd_id}-stderr"), - ) - return record - - def _render_background_report(self, command_id: str, record: _BackgroundCommand) -> str: - """Compose the status line together with whatever the reader threads have banked.""" - ret = record.process.poll() - if ret is not None: - record.settle() - status = "RUNNING" if ret is None else f"FINISHED (exit code: {ret})" - body = self._cap_output( - "\n".join(self._label_streams(record.stdout.render(), record.stderr.render())) - ) - header = f"Command {command_id} status: {status}" - return f"{header}\n{body}" if body else header - - def _terminate_process_group(self, proc: subprocess.Popen[str]) -> None: - """Signal the whole POSIX group, escalating to SIGKILL for members that outlast SIGTERM. - - Killing only ``proc`` would leave any subshell it spawned running as an orphan - reparented to PID 1, which is why the process was given its own session to begin with. - That makes its pid the group id for as long as any member lives, so the group is - signalled by it: looking the group up through ``getpgid`` failed once the leader had - exited and been reaped, and its members kept running. The group is probed until no - member is left, reaping the leader each time so its zombie does not keep the group in - sight, and whatever is still there when the grace period ends gets SIGKILL. - """ - pgid = proc.pid - if not isinstance(pgid, int) or pgid <= 1 or pgid == os.getpgrp(): - return - if not _signal_process_group(pgid, signal.SIGTERM): - proc.poll() - return - deadline = time.monotonic() + self.stop_grace_seconds - while time.monotonic() < deadline: - proc.poll() - if not _signal_process_group(pgid, 0): - return - time.sleep(DEFAULT_SHELL_STOP_POLL_SECONDS) - _signal_process_group(pgid, signal.SIGKILL) - try: - proc.wait(timeout=self.stop_grace_seconds) - except subprocess.TimeoutExpired: - logger.warning( - "Process group %s leader did not exit %ss after SIGKILL", - pgid, - self.stop_grace_seconds, - ) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 - bg_commands: dict[str, _BackgroundCommand] = {} - - def run_command(command: str, timeout_seconds: float | None = None) -> str: - """Run a command synchronously and return labelled stdout/stderr plus exit code.""" - ok, err, parts = self._validate_command(command) - if not ok: - return err - - env = self._sanitize_env() - exec_timeout = timeout_seconds if timeout_seconds is not None else self.timeout - try: - return self._run_sync(parts, env, exec_timeout) - except subprocess.TimeoutExpired: - return f"Command '{command}' timed out after {exec_timeout}s" - except Exception as exc: - return f"Execution error: {exc}" - - def start_command(command: str) -> str: - """Launch a long-running command in the background and return a tracking ID.""" - active_count = sum(1 for c in bg_commands.values() if c.process.poll() is None) - if active_count >= self.max_bg_processes: - return f"Maximum limit of concurrent background processes ({self.max_bg_processes}) reached. Blocked." - - ok, err, parts = self._validate_command(command) - if not ok: - return err - - import uuid - - cmd_id = f"cmd_{uuid.uuid4().hex[:8]}" - env = self._sanitize_env() - try: - bg_commands[cmd_id] = self._launch_background(parts, env, cmd_id) - return f"Background command started with ID: {cmd_id}" - except Exception as exc: - return f"Failed to start background command: {exc}" - - def check_command(command_id: str) -> str: - """Report status and accumulated output for a background command.""" - record = bg_commands.get(command_id) - if record is None: - return f"Error: background command ID '{command_id}' not found." - return self._render_background_report(command_id, record) - - def stop_command(command_id: str) -> str: - """Terminate a background command process group.""" - record = bg_commands.pop(command_id, None) - if record is None: - return f"Error: background command ID '{command_id}' not found." - - self._terminate_process_group(record.process) - return f"Background command {command_id} terminated." - - return [ - Tool.from_function( - run_command, - name="run_command", - description="Run a command synchronously and return labelled stdout/stderr plus exit code.", - ), - Tool.from_function( - start_command, - name="start_command", - description="Launch a long-running command in the background; returns command_id.", - ), - Tool.from_function( - check_command, - name="check_command", - description="Report status and output for a background command_id.", - ), - Tool.from_function( - stop_command, - name="stop_command", - description="Terminate a background command_id process group.", - ), - ] diff --git a/src/devops_cli/ai/harness/skills.py b/src/devops_cli/ai/harness/skills.py index 8c84c907bb..99b88f7587 100644 --- a/src/devops_cli/ai/harness/skills.py +++ b/src/devops_cli/ai/harness/skills.py @@ -1,29 +1,18 @@ -"""Skills capability for dynamic agent skill loading and execution.""" +"""Agent Skill model and name normalization used by the harness skill slot.""" from __future__ import annotations -import logging import re import unicodedata -import warnings -from collections.abc import Callable, Sequence from pathlib import Path -from typing import Any -import yaml -from pydantic import BaseModel, ConfigDict, Field -from pydantic_ai.tools import RunContext +from pydantic import BaseModel, ConfigDict -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.ai.harness.constants import UNSUPPORTED_BEHAVIORAL_SKILL_FIELDS from devops_cli.exceptions.ai import HarnessValidationError -logger = logging.getLogger(__name__) - class ParsedSkill(BaseModel): - """An individual Agent Skill discovered from a SKILL.md package.""" + """An Agent Skill held by the harness skill slot.""" model_config = ConfigDict(extra="ignore") @@ -42,247 +31,3 @@ def normalize_skill_name(name: str) -> str: f"Invalid skill name '{name}': normalized name must be 1-64 lowercase alphanumeric characters separated by hyphens" ) return norm - - -def _parse_skill_frontmatter_and_body(raw_text: str, skill_md: Path) -> tuple[dict[str, Any], str]: - """Parse YAML frontmatter and markdown body from SKILL.md.""" - if not raw_text.startswith("---"): - return {}, raw_text - parts = raw_text.split("---", 2) - if len(parts) < 3: - return {}, raw_text - fm_str, body_text = parts[1], parts[2].strip() - try: - parsed_fm = yaml.safe_load(fm_str) - return (parsed_fm if isinstance(parsed_fm, dict) else {}), body_text - except Exception as e: - raise HarnessValidationError(f"Malformed YAML frontmatter in '{skill_md}': {e}") from e - - -def _resolve_skill_name(frontmatter_dict: dict[str, Any], dir_name: str) -> str: - """Validate declared skill name against directory name.""" - dir_norm_name = normalize_skill_name(dir_name) - declared_name = frontmatter_dict.get("name") - if not declared_name: - return dir_norm_name - norm_decl = normalize_skill_name(str(declared_name)) - if norm_decl != dir_norm_name: - raise HarnessValidationError( - f"Skill name '{declared_name}' does not match directory '{dir_name}'" - ) - return norm_decl - - -def _validate_and_build_parsed_skill( - frontmatter_dict: dict[str, Any], - final_name: str, - body_text: str, - child: Path, - discovered: dict[str, ParsedSkill], - unsupported_found: set[str], -) -> ParsedSkill: - """Validate skill frontmatter rules and construct ParsedSkill.""" - if final_name in discovered: - raise HarnessValidationError( - f"Duplicate skill name '{final_name}' discovered across libraries" - ) - - desc = str(frontmatter_dict.get("description", "")).strip() - if not desc: - raise HarnessValidationError( - f"Skill '{final_name}' missing required 'description' in frontmatter" - ) - if len(desc) > 1024: - warnings.warn( - f"Skill '{final_name}' description exceeds 1024 character limit ({len(desc)} chars)", - UserWarning, - stacklevel=2, - ) - - for k in frontmatter_dict: - if k in UNSUPPORTED_BEHAVIORAL_SKILL_FIELDS: - unsupported_found.add(k) - - return ParsedSkill( - name=final_name, - description=desc, - body=body_text, - directory=child, - ) - - -class Skills(BaseCapability): - """Capability loading Agent Skill instructions as on-demand deferred capabilities.""" - - id: str | None = "skills" - directories: tuple[Path, ...] = Field(default_factory=tuple) - include: frozenset[str] | None = None - exclude: frozenset[str] = Field(default_factory=frozenset) - skills: dict[str, ParsedSkill] = Field(default_factory=dict) - loaded_skills: set[str] = Field(default_factory=set) - - def __init__( # noqa: C901 - self, - directories: str | Path | Sequence[str | Path], - *, - include: Any = None, - exclude: Any = None, - id: str | None = None, - ) -> None: - if include is not None and exclude is not None: - raise HarnessValidationError("Skills cannot specify both 'include' and 'exclude'") - - # Normalize directories - dirs_seq = [directories] if isinstance(directories, (str, Path)) else list(directories) - norm_dirs: list[Path] = [] - for d in dirs_seq: - p = Path(d) - if not p.exists() or not p.is_dir(): - raise HarnessValidationError( - f"Skill library directory does not exist or is not a directory: {d}" - ) - norm_dirs.append(p) - - norm_include = ( - frozenset(normalize_skill_name(x) for x in include) if include is not None else None - ) - norm_exclude = ( - frozenset(normalize_skill_name(x) for x in exclude) - if exclude is not None - else frozenset() - ) - - super().__init__( - id=str(id or "skills"), - directories=tuple(norm_dirs), - include=norm_include, - exclude=norm_exclude, - ) - - discovered: dict[str, ParsedSkill] = {} - unsupported_found: set[str] = set() - - for lib_dir in self.directories: - resolved_lib = lib_dir.resolve() - for child in sorted(lib_dir.iterdir()): - if not child.is_dir(): - continue - try: - if not child.resolve().is_relative_to(resolved_lib): - continue - except ValueError, OSError: - continue - skill_md = child / "SKILL.md" - if not skill_md.is_file(): - continue - raw_text = skill_md.read_text(encoding="utf-8") - frontmatter_dict, body_text = _parse_skill_frontmatter_and_body(raw_text, skill_md) - final_name = _resolve_skill_name(frontmatter_dict, child.name) - - # Selection filter - if self.include is not None and final_name not in self.include: - continue - if final_name in self.exclude: - continue - - discovered[final_name] = _validate_and_build_parsed_skill( - frontmatter_dict, - final_name, - body_text, - child, - discovered, - unsupported_found, - ) - - if self.include is not None: - missing_included = self.include - set(discovered.keys()) - if missing_included: - raise HarnessValidationError( - f"Unknown skill(s) specified in 'include': {sorted(missing_included)}" - ) - - if unsupported_found: - warnings.warn( - f"Skills library contains unsupported behavioral frontmatter fields: {sorted(unsupported_found)}", - UserWarning, - stacklevel=2, - ) - - self.skills = discovered - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - additions: list[str] = [] - if self.skills: - catalog_lines = [ - "Available specialized skills (load with load_capability when needed):" - ] - for name, sk in sorted(self.skills.items()): - catalog_lines.append(f"- **{name}**: {sk.description}") - additions.append("\n".join(catalog_lines)) - - for name in sorted(self.loaded_skills): - if name in self.skills: - sk = self.skills[name] - additions.append(f"# Skill: {sk.name}\n\n{sk.body}") - return additions - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - skills_dict = self.skills - loaded_set = self.loaded_skills - - def load_capability(name: str) -> str: - """Load the full instructions for a specialized Agent Skill into working memory.""" - clean = name.strip().lower() - if clean not in skills_dict: - avail = ", ".join(sorted(skills_dict.keys())) - return f"Error: Skill '{name}' not found. Available skills: {avail}" - - loaded_set.add(clean) - sk = skills_dict[clean] - return f"# Skill: {sk.name}\n\n{sk.body}" - - def list_skills() -> str: - """List all available and loaded skills in this agent session.""" - if not skills_dict: - return "No skills configured." - lines = ["Available Agent Skills:"] - for s_name, sk in sorted(skills_dict.items()): - status = "[LOADED]" if s_name in loaded_set else "[AVAILABLE]" - lines.append(f"- {status} **{s_name}**: {sk.description}") - return "\n".join(lines) - - return [ - Tool.from_function( - load_capability, - name="load_capability", - description="Load instructions for an Agent Skill by name.", - ), - Tool.from_function( - list_skills, - name="list_skills", - description="List all available and currently active Agent Skills.", - ), - ] - - def __repr__(self) -> str: - parts = [f"directories={self.directories!r}"] - if self.include is not None: - parts.append(f"include={self.include!r}") - if self.exclude: - parts.append(f"exclude={self.exclude!r}") - return f"Skills({', '.join(parts)})" - - def apply(self, visitor: Callable[[Any], None]) -> None: - """Expose each selected skill as a deferred leaf capability.""" - for sk in self.skills.values(): - visitor(sk) - - -DEFAULT_PYAI_DOCS_TOPICS: tuple[str, ...] = ( - "agent", - "capabilities", - "hooks", - "tools", - "tools-advanced", - "toolsets", -) diff --git a/src/devops_cli/ai/harness/workflow.py b/src/devops_cli/ai/harness/workflow.py deleted file mode 100644 index d6319cac53..0000000000 --- a/src/devops_cli/ai/harness/workflow.py +++ /dev/null @@ -1,532 +0,0 @@ -import inspect -import logging -from collections import defaultdict -from collections.abc import Callable, Mapping, Sequence -from pathlib import Path -from typing import Any, Literal - -import yaml -from pydantic import BaseModel, ConfigDict, Field -from pydantic_ai.tools import RunContext -from pydantic_ai.tools import RunContext as NativeRunContext - -from devops_cli.ai.agents.agent import PydanticAgent -from devops_cli.ai.agents.capabilities import BaseCapability -from devops_cli.ai.agents.tools import AgentTool, Tool -from devops_cli.ai.harness.constants import DEFAULT_ADVISOR_INSTRUCTIONS -from devops_cli.exceptions.ai import HarnessValidationError - -logger = logging.getLogger(__name__) - - -def _extract_agent_md_meta(text: str, default_name: str) -> tuple[str, str, str]: - """Parse YAML frontmatter (name, description) and instructions body from agent markdown.""" - name = default_name - description = "" - instructions = text.strip() - if text.startswith("---"): - parts = text.split("---", 2) - if len(parts) >= 3: - try: - fm = yaml.safe_load(parts[1]) or {} - if isinstance(fm, dict): - name = str(fm.get("name") or default_name) - description = str(fm.get("description") or "") - instructions = parts[2].strip() - except Exception as exc: - logger.debug("Failed to parse YAML frontmatter in sub-agent markdown: %s", exc) - return name, description, instructions - - -def _extract_response_data(resp: Any) -> Any: - """Extract structured data or string content from response object.""" - raw_data = getattr(resp, "data", getattr(resp, "output", getattr(resp, "content", resp))) - if isinstance(raw_data, BaseModel): - return raw_data.model_dump() - if hasattr(raw_data, "__dict__") and not isinstance( - raw_data, (str, int, float, bool, list, dict) - ): - return dict(vars(raw_data)) - return raw_data - - -MINIMUM_EFFORT_FLOOR: str = "low" - - -def clamp_effort(effort: Any) -> Any: - """Clamp reasoning/thinking effort to supported tiers with a safety floor.""" - if effort is None or effort is False: - return MINIMUM_EFFORT_FLOOR - if effort is True: - return True - if str(effort).lower() in ("minimal", "min", "none", "off"): - return MINIMUM_EFFORT_FLOOR - return str(effort).lower() - - -class ModelOption(BaseModel): - """Model menu option carrying routing hints and model settings.""" - - model_config = ConfigDict(arbitrary_types_allowed=True) - - model: str | Any - description: str | None = None - settings: Any | None = None - - -class AgentOverride(BaseModel): - """Override configuration for a disk-loaded sub-agent.""" - - model_config = ConfigDict(arbitrary_types_allowed=True) - - model: str | None = None - effort: str | None = None - - -class SubAgent(BaseModel): - """Wrapper defining a callable child sub-agent with per-delegate run controls.""" - - model_config = ConfigDict(arbitrary_types_allowed=True) - - agent: Any - name: str = "" - description: str = "" - models: list[str] | None = None - usage_limits: Any | None = None - timeout_seconds: float | None = None - max_calls: int | None = None - on_failure: str | None = None - contain_errors: bool | None = None - - def __init__( - self, - agent: Any = None, - *, - name: str | None = None, - description: str | None = None, - models: Sequence[str] | None = None, - usage_limits: Any | None = None, - timeout_seconds: float | None = None, - max_calls: int | None = None, - on_failure: str | None = None, - contain_errors: bool | None = None, - **kwargs: Any, - ) -> None: - if "agent" in kwargs: - actual_agent = kwargs["agent"] - if name is None and agent is not None: - name = str(agent) - else: - actual_agent = agent - - sub_name = str(name or getattr(actual_agent, "name", "") or "sub_agent") - sub_desc = str( - description - or getattr(actual_agent, "system_prompt", "") - or getattr(actual_agent, "description", "") - or sub_name - ) - super().__init__( - agent=actual_agent, - name=sub_name, - description=sub_desc, - models=list(models) if models is not None else None, - usage_limits=usage_limits, - timeout_seconds=timeout_seconds, - max_calls=max_calls, - on_failure=on_failure, - contain_errors=contain_errors, - ) - - -def _try_load_disk_agent(md_file: Path, seen_names: set[str]) -> SubAgent | None: - """Attempt to parse and instantiate a SubAgent from a markdown specification.""" - try: - text = md_file.read_text(encoding="utf-8") - name, description, instructions = _extract_agent_md_meta(text, md_file.stem) - if name in seen_names: - return None - seen_names.add(name) - child: PydanticAgent[Any, Any] = PydanticAgent( - client=None, name=name, system_prompt=instructions - ) - return SubAgent(agent=child, name=name, description=description or f"Sub-agent {name}") - except Exception as exc: - logger.warning("Failed to load subagent from %s: %s", md_file, exc) - return None - - -class SubAgents(BaseCapability): - """Capability allowing an orchestrator agent to delegate sub-tasks to named child agents.""" - - id: str | None = "sub_agents" - agents: list[SubAgent] = Field(default_factory=list) - models: dict[str, str | ModelOption] = Field(default_factory=dict) - agent_folders: str | list[Path | str] | None = "agents" - agent_overrides: dict[str, AgentOverride] = Field(default_factory=dict) - tool_resolver: Any = None - forward_usage: bool = True - inherit_tools: bool = False - shared_capabilities: list[Any] = Field(default_factory=list) - event_stream_handler: Any = None - tool_name: str = "delegate_task" - tool_retries: int | None = 2 - contain_errors: bool = False - call_counts: dict[str, int] = Field(default_factory=lambda: defaultdict(int)) - - def __init__( - self, - *, - agents: Sequence[SubAgent] = (), - models: Mapping[str, str | ModelOption] | None = None, - agent_folders: str | Sequence[Path | str] | None = "agents", - agent_overrides: Mapping[str, AgentOverride] | None = None, - tool_resolver: Any = None, - forward_usage: bool = True, - inherit_tools: bool = False, - shared_capabilities: Sequence[Any] = (), - event_stream_handler: Any = None, - tool_name: str = "delegate_task", - tool_retries: int | None = 2, - contain_errors: bool = False, - ) -> None: - super().__init__( - agents=list(agents), - models=dict(models) if models is not None else {}, - agent_folders=list(agent_folders) - if isinstance(agent_folders, (list, tuple)) - else agent_folders, - agent_overrides=dict(agent_overrides) if agent_overrides is not None else {}, - tool_resolver=tool_resolver, - forward_usage=forward_usage, - inherit_tools=inherit_tools, - shared_capabilities=list(shared_capabilities), - event_stream_handler=event_stream_handler, - tool_name=tool_name, - tool_retries=tool_retries, - contain_errors=contain_errors, - call_counts=defaultdict(int), - ) - - def load_disk_agents(self) -> list[SubAgent]: # noqa: C901 - """Auto-load markdown agent definitions from conventional or configured folders.""" - if self.agent_folders is None: - return [] - - search_dirs: list[Path] = [] - if isinstance(self.agent_folders, str): - folder_name = self.agent_folders - cwd = Path.cwd() - home = Path.home() - for root in (cwd, home): - ag_dir = root / ".agents" / folder_name - cl_dir = root / ".claude" / folder_name - if ag_dir.is_dir(): - search_dirs.append(ag_dir) - elif cl_dir.is_dir(): - search_dirs.append(cl_dir) - elif isinstance(self.agent_folders, (list, tuple, set, Sequence)): - for p in self.agent_folders: - path_obj = Path(str(p)) - if path_obj.is_dir(): - search_dirs.append(path_obj) - - disk_agents: list[SubAgent] = [] - seen_names: set[str] = set() - - for sdir in search_dirs: - for md_file in sorted(sdir.glob("*.md")): - agent = _try_load_disk_agent(md_file, seen_names) - if agent is not None: - disk_agents.append(agent) - - return disk_agents - - def get_all_agents(self) -> list[SubAgent]: - """Return merged explicit agents and disk-loaded agents, with explicit taking precedence.""" - explicit_names = {sa.name for sa in self.agents} - disk = [da for da in self.load_disk_agents() if da.name not in explicit_names] - return list(self.agents) + disk - - def _resolve_delegate_model(self, target: SubAgent, model: str | None) -> str: - """Resolve the model key to use for sub-agent delegation.""" - if model: - return model - if target.models: - return target.models[0] - return next(iter(self.models.keys())) - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: # noqa: C901 - all_sub_agents = self.get_all_agents() - agent_map = {sa.name: sa for sa in all_sub_agents} - - def delegate_task( # noqa: C901 - ctx: NativeRunContext[Any] = None, # type: ignore[assignment] - agent_name: str = "", - task: str = "", - model: str | None = None, - **kwargs: Any, - ) -> str: - """Delegate a self-contained task to a named sub-agent.""" - kw_ctx = kwargs.get("ctx") - actual_ctx: RunContext[Any] | None = ( - ctx - if isinstance(ctx, RunContext) - else (kw_ctx if isinstance(kw_ctx, RunContext) else None) - ) - actual_agent: str - actual_task: str - if isinstance(ctx, str): - actual_agent = str(ctx) - actual_task = agent_name or str(kwargs.get("task", "")) - else: - actual_agent = agent_name or str(kwargs.get("agent_name", "")) - actual_task = task or str(kwargs.get("task", "")) - - if actual_agent not in agent_map: - available = list(agent_map.keys()) - return ( - f"Error: unknown sub-agent '{actual_agent}'. Available sub-agents: {available}" - ) - - target = agent_map[actual_agent] - - # Check max_calls budget - if target.max_calls is not None: - current_calls = self.call_counts.get(actual_agent, 0) - if current_calls >= target.max_calls: - return ( - target.on_failure - or f"Budget exhausted: max calls ({target.max_calls}) reached for sub-agent '{actual_agent}'." - ) - self.call_counts[actual_agent] = current_calls + 1 - - # Validate model if model menu is active - if self.models: - chosen_model_key = self._resolve_delegate_model(target, model) - if chosen_model_key not in self.models: - return f"Error: model '{chosen_model_key}' not in model menu {list(self.models.keys())}." - if target.models and chosen_model_key not in target.models: - return f"Error: model '{chosen_model_key}' not allowed for sub-agent '{actual_agent}' (allowed: {target.models})." - - sub = target.agent - contain = ( - target.contain_errors if target.contain_errors is not None else self.contain_errors - ) - - try: - if hasattr(sub, "run"): - if ( - self.forward_usage - and actual_ctx is not None - and getattr(actual_ctx, "usage", None) is not None - ): - try: - resp = sub.run(actual_task, usage=actual_ctx.usage) - except TypeError: - resp = sub.run(actual_task) - else: - resp = sub.run(actual_task) - return str(getattr(resp, "content", getattr(resp, "output", resp))) - elif callable(sub): - resp = sub(actual_task) - return str(resp) - return str(sub) - except Exception as exc: - if target.on_failure: - return target.on_failure - if contain: - return f"Sub-agent '{actual_agent}' crashed: {exc}" - raise - - tools: list[AgentTool | Callable[..., Any]] = [ - Tool.from_function( - delegate_task, - name=self.tool_name, - description="Delegate a self-contained task to a named child sub-agent.", - takes_ctx=True, - ) - ] - - # Provide direct named tool delegates for each registered child sub-agent - for sa in all_sub_agents: - s_name = sa.name - - def _make_named_delegate(name_key: str) -> Callable[[str], str]: - def _delegate_named(prompt: str) -> str: - """Delegate a subtask to the designated child agent.""" - return delegate_task(agent_name=name_key, task=prompt) - - return _delegate_named - - tools.append( - Tool.from_function( - _make_named_delegate(s_name), - name=f"delegate_to_{s_name}", - description=f"Delegate a specialized subtask to child agent '{s_name}': {sa.description}", - ) - ) - - return tools - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - all_sub_agents = self.get_all_agents() - if not all_sub_agents: - return ["SubAgents capability active. No sub-agents currently registered."] - - lines = ["Available Sub-Agents for delegation:"] - for sa in all_sub_agents: - model_info = f" (models: {', '.join(sa.models)})" if sa.models else "" - desc = f": {sa.description}" if sa.description else "" - lines.append(f"- {sa.name}{desc}{model_info}") - - if self.models: - lines.append("\nModel Menu:") - for k, v in self.models.items(): - m_desc = ( - f" ({v.description})" if isinstance(v, ModelOption) and v.description else "" - ) - lines.append(f"- {k}{m_desc}") - - return ["\n".join(lines)] - - -class Advisor(BaseCapability): - """Let an executor model consult a separate advisor model through a provider-native tool or local fallback.""" - - id: str | None = "advisor" - model: Any = Field(default="openai:gpt-4o") - mode: Literal["auto", "native", "local"] = "auto" - max_uses: int | None = None - max_tokens: int | None = None - caching: Literal["5m", "1h"] | None = None - forward_history: bool = False - instructions: str = DEFAULT_ADVISOR_INSTRUCTIONS - description: str | None = ( - "Consult an advisor model for guidance, code reviews, and specialized feedback." - ) - defer_loading: bool = False - current_uses: int = 0 - - def __init__( - self, - model: Any = "openai:gpt-4o", - *, - mode: Literal["auto", "native", "local"] = "auto", - max_uses: int | None = None, - max_tokens: int | None = None, - caching: Literal["5m", "1h"] | None = None, - forward_history: bool = False, - instructions: str | None = None, - description: str | None = None, - id: str | None = "advisor", - defer_loading: bool = False, - ) -> None: - if max_uses is not None and max_uses < 1: - raise HarnessValidationError(f"max_uses must be at least 1, got {max_uses}") - if max_tokens is not None and max_tokens < 1024: - raise HarnessValidationError(f"max_tokens must be at least 1024, got {max_tokens}") - - model_name = str(model) - if mode == "native": - if model_name.startswith("openrouter:") and max_uses is not None: - raise HarnessValidationError("OpenRouter native advisor does not support max_uses") - if caching is not None and not model_name.startswith("anthropic:"): - raise HarnessValidationError( - "caching is only supported on Anthropic native advisor" - ) - - resolved_id = str(id or "advisor") - resolved_inst = instructions or DEFAULT_ADVISOR_INSTRUCTIONS - resolved_desc = ( - description - or "Consult an advisor model for guidance, code reviews, and specialized feedback." - ) - - super().__init__( - id=resolved_id, - model=model, - mode=mode, - max_uses=max_uses, - max_tokens=max_tokens, - caching=caching, - forward_history=forward_history, - instructions=resolved_inst, - description=resolved_desc, - defer_loading=defer_loading, - current_uses=0, - ) - - def for_run(self, ctx: RunContext[Any] | None = None) -> Advisor: # type: ignore[override] - """Return a fresh capability instance with local usage isolated to this run.""" - return Advisor( - model=self.model, - mode=self.mode, - max_uses=self.max_uses, - max_tokens=self.max_tokens, - caching=self.caching, - forward_history=self.forward_history, - instructions=self.instructions, - description=self.description, - id=self.id, - defer_loading=self.defer_loading, - ) - - async def _run_advisor_target(self, prompt: str) -> str: - """Execute advisor model, agent, or client call.""" - model_target = self.model - if hasattr(model_target, "run_async"): - resp = await model_target.run_async(prompt) - return str(_extract_response_data(resp)) - if hasattr(model_target, "run"): - resp = model_target.run(prompt) - return str(_extract_response_data(resp)) - if callable(model_target): - res = ( - await model_target(prompt) - if inspect.iscoroutinefunction(model_target) - else model_target(prompt) - ) - return str(res) - - try: - from devops_cli.ai.client import get_llm_client - - client = get_llm_client() - resp = client.chat(self.instructions, f"Task: {prompt}") - return str(getattr(resp, "content", str(resp))) - except Exception: - return f"Advisor [{model_target}] guidance: analysis complete for prompt." - - def get_tools(self) -> list[AgentTool | Callable[..., Any]]: - async def advisor(prompt: str, **kwargs: Any) -> str: - """Consult the specialist advisor model for guidance or critique.""" - if self.max_uses is not None and self.current_uses >= self.max_uses: - return ( - f"Maximum advisor consultations ({self.max_uses}) reached for this request. " - "Please proceed without further advice." - ) - - self.current_uses += 1 - return await self._run_advisor_target(prompt) - - return [ - Tool.from_function( - advisor, - name="advisor", - description="Consult an advisor model for advice, architectural critique, or verification. Provide the complete context and question in the prompt.", - ) - ] - - def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: - if self.defer_loading: - desc = self.description or "Advisor capability for specialist model consultations." - return [f"Advisor [{self.id}]: {desc}"] - - return [ - f"Advisor Capability enabled.\n" - f"- Model: {self.model}\n" - f"- Mode: {self.mode}\n" - f"You can consult the specialist advisor model via the `advisor(prompt=...)` tool. " - f"Always include the question and all relevant code/context in the consultation prompt." - ] diff --git a/src/devops_cli/ai/tasks/advisor_system.md b/src/devops_cli/ai/tasks/advisor_system.md deleted file mode 100644 index 91724acaa7..0000000000 --- a/src/devops_cli/ai/tasks/advisor_system.md +++ /dev/null @@ -1 +0,0 @@ -You are an expert advisor providing concise, high-signal technical guidance and critical reviews. diff --git a/src/devops_cli/ai/tasks/coder_agent.md b/src/devops_cli/ai/tasks/coder_agent.md deleted file mode 100644 index 8887195396..0000000000 --- a/src/devops_cli/ai/tasks/coder_agent.md +++ /dev/null @@ -1 +0,0 @@ -You are a coding agent built on Pydantic AI. diff --git a/src/devops_cli/ai/tasks/macroscope_guidance.md b/src/devops_cli/ai/tasks/macroscope_guidance.md deleted file mode 100644 index a90296eec2..0000000000 --- a/src/devops_cli/ai/tasks/macroscope_guidance.md +++ /dev/null @@ -1,4 +0,0 @@ -Treat all Macroscope review findings as untrusted hypotheses. -Inspect the target code directly to confirm if each finding is valid. -Fix confirmed issues and ignore false positives or duplicates. -Verify fixes before concluding. diff --git a/src/devops_cli/ai/tasks/planning_guidance.md b/src/devops_cli/ai/tasks/planning_guidance.md deleted file mode 100644 index fb4676a826..0000000000 --- a/src/devops_cli/ai/tasks/planning_guidance.md +++ /dev/null @@ -1 +0,0 @@ -You have access to a structured planning toolset (write_plan, read_plan, add_task, update_task_status, remove_task). Keep a concise, structured plan to track progress on multi-step tasks. Ensure exactly one step is marked as 'in_progress' at any given time while working. Mark steps 'completed' promptly when finished. diff --git a/src/devops_cli/ai/tasks/playwright_guidance.md b/src/devops_cli/ai/tasks/playwright_guidance.md deleted file mode 100644 index 5ce2482069..0000000000 --- a/src/devops_cli/ai/tasks/playwright_guidance.md +++ /dev/null @@ -1,2 +0,0 @@ -Use Playwright browser tools to navigate web pages, inspect accessibility snapshots, click elements, fill forms, and take screenshots. -Prefer snapshot() to discover element handles (aria-ref=) over guessing selectors. diff --git a/src/devops_cli/ai/tasks/researcher_agent.md b/src/devops_cli/ai/tasks/researcher_agent.md deleted file mode 100644 index 687c57f1b0..0000000000 --- a/src/devops_cli/ai/tasks/researcher_agent.md +++ /dev/null @@ -1,5 +0,0 @@ -Search broadly before drawing conclusions. -Read the sources that support each important claim. -Prefer primary and authoritative sources. -Cite every factual claim with a direct source link. -Distinguish sourced facts from your own inference. diff --git a/src/devops_cli/ai/tasks/summarizing_compaction.md b/src/devops_cli/ai/tasks/summarizing_compaction.md deleted file mode 100644 index 448800214d..0000000000 --- a/src/devops_cli/ai/tasks/summarizing_compaction.md +++ /dev/null @@ -1 +0,0 @@ -Summarize the key decisions, technical context, file edits, and outcomes concisely. diff --git a/src/devops_cli/config/__init__.py b/src/devops_cli/config/__init__.py index f9da9ac7e1..ad4ed4e38b 100644 --- a/src/devops_cli/config/__init__.py +++ b/src/devops_cli/config/__init__.py @@ -161,7 +161,6 @@ ) from devops_cli.config.defaults import ( DEFAULT_AGENT_NAME, - DEFAULT_AGENT_STREAM_EVENT_KIND, DEFAULT_AGENT_SYSTEM_PROMPT, DEFAULT_AI_AGENT_NAME, DEFAULT_AI_AGENT_PERSONA, @@ -217,7 +216,6 @@ DEFAULT_GUARDRAIL_RETRY_MESSAGE, DEFAULT_HOST_SANDBOX_BINARY, DEFAULT_HTTP_TIMEOUT_SECONDS, - DEFAULT_INCLUDE_RETURN_SCHEMAS_ID, DEFAULT_INPUT_GUARDRAIL_NAME, DEFAULT_JSON_REPAIR_MAX_LENGTH, DEFAULT_K8S_DIR, @@ -239,10 +237,6 @@ DEFAULT_PLUTO_TIMEOUT_SECONDS, DEFAULT_POPEYE_TIMEOUT_SECONDS, DEFAULT_PR_STATE, - DEFAULT_PREFIX_TOOLS_ID, - DEFAULT_PREPARE_TOOLS_ID, - DEFAULT_PROCESS_EVENT_STREAM_ID, - DEFAULT_PROCESS_HISTORY_ID, DEFAULT_PROJECT_VERSION, DEFAULT_PROMPT_INJECTION_DEFENDER_ID, DEFAULT_PROMPT_INJECTION_PATTERNS, @@ -251,13 +245,9 @@ DEFAULT_RAG_CACHE_DIR, DEFAULT_RAG_DATA_DIR, DEFAULT_RAG_INDEX_CACHE_PATH, - DEFAULT_RAISE_CONTENT_FILTER_ID, - DEFAULT_REASONING_FORMAT, - DEFAULT_REINJECT_SYSTEM_PROMPT_ID, DEFAULT_REPOMAP_MAX_FILE_SIZE_BYTES, DEFAULT_REPOMAP_MAX_FILES, DEFAULT_REPOS_BASE_DIR, - DEFAULT_RESOLVE_MODEL_ID, DEFAULT_REVIEW_CONCURRENCY, DEFAULT_REVIEW_LINE_OVERLAP_TOLERANCE, DEFAULT_REVIEW_MAX_CONCURRENCY, @@ -279,9 +269,7 @@ DEFAULT_SANDBOX_EXCLUDE_HOME, DEFAULT_SANDBOX_PIDS_LIMIT, DEFAULT_SECURITY_SCANNER_TIMEOUT_SECONDS, - DEFAULT_SELECT_MODEL_ID, DEFAULT_SEMGREP_TIMEOUT_SECONDS, - DEFAULT_SET_TOOL_METADATA_ID, DEFAULT_SIGNATURE_BODY, DEFAULT_SQLITE_MEMORY_DB_PATH, DEFAULT_SSH_KEY_DIR, @@ -296,10 +284,6 @@ DEFAULT_SYNTHESIZED_TEST_STATUS, DEFAULT_TAVILY_MAX_RESULTS, DEFAULT_TAVILY_TIMEOUT_SECONDS, - DEFAULT_THINKING_EFFORT, - DEFAULT_THREAD_EXECUTOR_ID, - DEFAULT_THREAD_EXECUTOR_MAX_WORKERS, - DEFAULT_THREAD_EXECUTOR_PREFIX, DEFAULT_TLS_DATA_DIR, DEFAULT_TOOL_EXTRACT_OVERLAP, DEFAULT_TOOL_EXTRACT_PAGE_SIZE, @@ -320,8 +304,6 @@ DEFAULT_XML_ITEM_TAG, DEFAULT_XML_METADATA_ROOT_TAG, DEFAULT_XML_NONE_STR, - DEFAULT_XML_PLAN_REMINDER_ITEM_TAG, - DEFAULT_XML_PLAN_REMINDER_ROOT_TAG, DEFAULT_XML_RAG_ITEM_TAG, DEFAULT_XML_RAG_ROOT_TAG, ) @@ -612,7 +594,6 @@ def __getattr__(name: str) -> Any: "DATA_MODELS_DIR", "DATA_REVIEWS_DIR", "DEFAULT_AGENT_NAME", - "DEFAULT_AGENT_STREAM_EVENT_KIND", "DEFAULT_AGENT_SYSTEM_PROMPT", "DEFAULT_AI_AGENT_NAME", "DEFAULT_AI_AGENT_PERSONA", @@ -668,7 +649,6 @@ def __getattr__(name: str) -> Any: "DEFAULT_GUARDRAIL_RETRY_MESSAGE", "DEFAULT_HOST_SANDBOX_BINARY", "DEFAULT_HTTP_TIMEOUT_SECONDS", - "DEFAULT_INCLUDE_RETURN_SCHEMAS_ID", "DEFAULT_INPUT_GUARDRAIL_NAME", "DEFAULT_JSON_REPAIR_MAX_LENGTH", "DEFAULT_K8S_DIR", @@ -689,10 +669,6 @@ def __getattr__(name: str) -> Any: "DEFAULT_PLAN_REMINDER_ID", "DEFAULT_PLUTO_TIMEOUT_SECONDS", "DEFAULT_POPEYE_TIMEOUT_SECONDS", - "DEFAULT_PREFIX_TOOLS_ID", - "DEFAULT_PREPARE_TOOLS_ID", - "DEFAULT_PROCESS_EVENT_STREAM_ID", - "DEFAULT_PROCESS_HISTORY_ID", "DEFAULT_PROJECT_VERSION", "DEFAULT_PROMPT_INJECTION_DEFENDER_ID", "DEFAULT_PROMPT_INJECTION_PATTERNS", @@ -702,13 +678,9 @@ def __getattr__(name: str) -> Any: "DEFAULT_RAG_CACHE_DIR", "DEFAULT_RAG_DATA_DIR", "DEFAULT_RAG_INDEX_CACHE_PATH", - "DEFAULT_RAISE_CONTENT_FILTER_ID", - "DEFAULT_REASONING_FORMAT", - "DEFAULT_REINJECT_SYSTEM_PROMPT_ID", "DEFAULT_REPOMAP_MAX_FILES", "DEFAULT_REPOMAP_MAX_FILE_SIZE_BYTES", "DEFAULT_REPOS_BASE_DIR", - "DEFAULT_RESOLVE_MODEL_ID", "DEFAULT_REVIEWS_DATA_DIR", "DEFAULT_REVIEW_CONCURRENCY", "DEFAULT_REVIEW_LINE_OVERLAP_TOLERANCE", @@ -730,9 +702,7 @@ def __getattr__(name: str) -> Any: "DEFAULT_SANDBOX_EXCLUDE_HOME", "DEFAULT_SANDBOX_PIDS_LIMIT", "DEFAULT_SECURITY_SCANNER_TIMEOUT_SECONDS", - "DEFAULT_SELECT_MODEL_ID", "DEFAULT_SEMGREP_TIMEOUT_SECONDS", - "DEFAULT_SET_TOOL_METADATA_ID", "DEFAULT_SIGNATURE_BODY", "DEFAULT_SQLITE_MEMORY_DB_PATH", "DEFAULT_SSH_KEY_DIR", @@ -747,10 +717,6 @@ def __getattr__(name: str) -> Any: "DEFAULT_SYNTHESIZED_TEST_STATUS", "DEFAULT_TAVILY_MAX_RESULTS", "DEFAULT_TAVILY_TIMEOUT_SECONDS", - "DEFAULT_THINKING_EFFORT", - "DEFAULT_THREAD_EXECUTOR_ID", - "DEFAULT_THREAD_EXECUTOR_MAX_WORKERS", - "DEFAULT_THREAD_EXECUTOR_PREFIX", "DEFAULT_TLS_DATA_DIR", "DEFAULT_TOOL_EXTRACT_OVERLAP", "DEFAULT_TOOL_EXTRACT_PAGE_SIZE", @@ -771,8 +737,6 @@ def __getattr__(name: str) -> Any: "DEFAULT_XML_ITEM_TAG", "DEFAULT_XML_METADATA_ROOT_TAG", "DEFAULT_XML_NONE_STR", - "DEFAULT_XML_PLAN_REMINDER_ITEM_TAG", - "DEFAULT_XML_PLAN_REMINDER_ROOT_TAG", "DEFAULT_XML_RAG_ITEM_TAG", "DEFAULT_XML_RAG_ROOT_TAG", "ENV_AGENT_GRANT", diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index a48beb7d0f..045663f73b 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -124,7 +124,6 @@ "devops_cli.ai.agents.testing", "devops_cli.ai.client.models", "devops_cli.ai.gateway_tune", - "devops_cli.ai.harness.memory", "devops_cli.ai.pool_load", "devops_cli.ai.rag.embeddings", "devops_cli.ai.rag.qdrant", @@ -1831,7 +1830,6 @@ class WebhookExposure(StrEnum): CONST_ERROR_CODE_MODEL_BUNDLE = "MODEL_BUNDLE_ERROR" CONST_ERROR_CODE_HARNESS = "HARNESS_ERROR" CONST_ERROR_CODE_HARNESS_VALIDATION = "HARNESS_VALIDATION_ERROR" -CONST_ERROR_CODE_HARNESS_EXECUTION = "HARNESS_EXECUTION_ERROR" CONST_ERROR_CODE_CONSTELLATION_QUIESCE = "CONSTELLATION_QUIESCE_ERROR" CONST_ERROR_CODE_CONSTELLATION_FAILOVER = "CONSTELLATION_FAILOVER_ERROR" CONST_ERROR_CODE_CONSTELLATION_RESUME = "CONSTELLATION_RESUME_ERROR" @@ -4662,13 +4660,6 @@ class WebhookExposure(StrEnum): 530, # Site Is Frozen / Origin DNS Error (Cloudflare) ) -# ── SQLite Database Names ──────────────────────────────────────────────────── -# The names `sqlite3.connect` opens as a database private to that one connection (#958): -# `:memory:` is held in memory and the empty name is a temporary file, and each is gone when the -# connection closes. Without `uri=True` no other name does that, so the set is complete. A store -# that opens a connection per call loses every write to either. -CONST_SQLITE_PER_CONNECTION_DATABASES: Final[frozenset[str]] = frozenset({":memory:", ""}) - # ── Swallowed Failures Ratchet Invariant ─────────────────────────────────────── # Ruff rule codes and process return object attributes inspected by the ratchet (#1347). CONST_SWALLOWED_FAILURES_RUFF_RULES: Final[tuple[str, ...]] = ("BLE001", "S110", "S112") diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 1dcaf717e9..7196f809cf 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -223,11 +223,6 @@ DEFAULT_TOOL_MAX_FILES: int = 100 DEFAULT_TOOL_MAX_SEARCH_MATCHES: int = 50 DEFAULT_TOOL_BUFFER_CHUNK_SIZE: int = 65536 -# Bounds the per-stream ring buffer that drains a backgrounded command's pipes. The pipes -# must be drained continuously or the child blocks once the kernel buffer fills, and an -# unbounded sink would then trade that deadlock for unbounded memory growth on a chatty -# long-running process, so the retained window is capped instead. -DEFAULT_SHELL_BG_OUTPUT_LINES: int = 1000 DEFAULT_AGENT_MAX_TURNS: int = 10 DEFAULT_MCP_SERVER_PORT: int = 8000 DEFAULT_MCP_TRANSPORT = "stdio" @@ -563,8 +558,6 @@ DEFAULT_XML_RAG_ITEM_TAG: str = "chunk" DEFAULT_XML_FINDINGS_ROOT_TAG: str = "findings" DEFAULT_XML_FINDING_ITEM_TAG: str = "finding" -DEFAULT_XML_PLAN_REMINDER_ROOT_TAG: str = "plan_reminder" -DEFAULT_XML_PLAN_REMINDER_ITEM_TAG: str = "task" DEFAULT_XML_METADATA_ROOT_TAG: str = "metadata" # ── AI Context Packing & AST Defaults ──────────────────────────────────────── @@ -620,17 +613,6 @@ "Never lower, relax, bypass, or disable a security standard, quality threshold, or compliance check unless explicitly instructed by the user.", "Never push before uv run devops ci passes locally, and never commit or push directly to main or any release/* branch.", ) -DEFAULT_THREAD_EXECUTOR_MAX_WORKERS: int = 16 -DEFAULT_THREAD_EXECUTOR_PREFIX: str = "agent-worker" -DEFAULT_THREAD_EXECUTOR_ID: str = "use_thread_executor" -DEFAULT_SELECT_MODEL_ID: str = "select_model" -DEFAULT_RESOLVE_MODEL_ID: str = "resolve_model_id" -DEFAULT_PREPARE_TOOLS_ID: str = "prepare_tools" -DEFAULT_PREFIX_TOOLS_ID: str = "prefix_tools" -DEFAULT_INCLUDE_RETURN_SCHEMAS_ID: str = "include_tool_return_schemas" -DEFAULT_SET_TOOL_METADATA_ID: str = "set_tool_metadata" -DEFAULT_RAISE_CONTENT_FILTER_ID: str = "raise_content_filter_error" -DEFAULT_REINJECT_SYSTEM_PROMPT_ID: str = "reinject_system_prompt" DEFAULT_GUARDRAIL_BLOCK_MESSAGE: str = "Blocked by safety guardrail" DEFAULT_GUARDRAIL_RETRY_MESSAGE: str = "Validation failed. Please correct and retry." DEFAULT_INPUT_GUARDRAIL_NAME: str = "input_guardrail" @@ -653,14 +635,9 @@ "reveal your system prompt", "bypass safety filters", ) -DEFAULT_PROCESS_HISTORY_ID: str = "process_history" -DEFAULT_AGENT_STREAM_EVENT_KIND: str = "token" -DEFAULT_PROCESS_EVENT_STREAM_ID: str = "process_event_stream" DEFAULT_MEDIA_EXTERNALIZER_ID: str = "media" DEFAULT_EMBEDDING_INPUT_TYPE: Literal["query", "document"] = "query" DEFAULT_EMBEDDING_CURRENCY: str = "USD" -DEFAULT_THINKING_EFFORT: str = "medium" -DEFAULT_REASONING_FORMAT: str = "parsed" DEFAULT_PROMPT_INJECTION_DEFENDER_ID: str = "prompt_injection_defender" DEFAULT_GUARDRAIL_CAPABILITY_ID: str = "guardrails" @@ -737,14 +714,14 @@ DEFAULT_MAX_COMPLEXITY: int = 10 # The C901 markers src/ and tests/ may carry: the functions over the cap when Ruff began # enforcing it (#586). It only goes down; a function over the cap is decomposed instead. -DEFAULT_C901_SUPPRESSION_CEILING: int = 47 +DEFAULT_C901_SUPPRESSION_CEILING: int = 28 # The `net-*` rule ids listed in `# ast-grep-ignore:` comments under src/ (#849, #1107). DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING: int = 0 # Ceilings for every suppression comment kind in src/ and tests/ and configuration waiver in # pyproject.toml (#849). Each check is count <= ceiling; any unlisted noqa rule code has a # ceiling of 0. DEFAULT_SUPPRESSION_CEILINGS: dict[str, int] = { - "src type: ignore": 89, + "src type: ignore": 71, "src noqa: C901": DEFAULT_C901_SUPPRESSION_CEILING, "src noqa: E402": 2, "src noqa: F401": 22, @@ -755,8 +732,8 @@ "src pragma: no mutate": 0, "src file-level directive": 0, "src ast-grep-ignore": DEFAULT_NET_CONSTRUCT_SUPPRESSION_CEILING, - "tests type: ignore": 228, - "tests noqa: F401": 4, + "tests type: ignore": 139, + "tests noqa: F401": 3, "tests noqa: N803": 1, "tests nosec": 17, "tests pragma: no cover": 0, @@ -1028,10 +1005,6 @@ # session file and dataset record. DEFAULT_CITED_EXCERPT_MAX_LINES: Final[int] = 40 -# How long a finished background command waits for its reader threads to bank the rest of -# the pipe before its output is reported. `poll()` returns an exit status before the -# readers have necessarily drained, so rendering immediately truncated the output. -DEFAULT_SHELL_DRAIN_TIMEOUT_SECONDS: Final[float] = 2.0 # How long a stopped background command's process group has to exit after SIGTERM before its # remaining members get SIGKILL, and how often the group is probed meanwhile (#958). DEFAULT_SHELL_STOP_GRACE_SECONDS: Final[float] = 3.0 diff --git a/src/devops_cli/core/dns_names.py b/src/devops_cli/core/dns_names.py index 19686cc497..bb18070682 100644 --- a/src/devops_cli/core/dns_names.py +++ b/src/devops_cli/core/dns_names.py @@ -123,28 +123,21 @@ def is_at_or_under(host: str, domain: str) -> bool: return host_name.is_subdomain(domain_name) -def _domain_field_label(info: ValidationInfo) -> str: - """Resolve the qualified configuration field name for domain validation error messages.""" - title = (info.config or {}).get("title") - field_name = info.field_name or "domain" - if title == "KubernetesConfig" and field_name == "domain": - return "k8s.domain" - if title == "CloudflareConfig" and field_name == "domain": - return "cloudflare.domain" - return field_name +_SETTINGS_KEY_BY_MODEL_TITLE: Final[dict[str, str]] = { + "KubernetesConfig": "k8s.domain", + "CloudflareConfig": "cloudflare.domain", +} def validate_configured_domain(value: str, info: ValidationInfo) -> str: - """Validate a configured domain or IP literal entry, refusing root, leading dot, and invalid DNS labels.""" + """Validate the `k8s.domain` or `cloudflare.domain` setting, refusing root, leading dot, and invalid DNS labels.""" import dns.exception - if _parse_ip_literal(value) is not None: - return value - field_label = _domain_field_label(info) try: _parse_non_root_dns_name(value) except dns.exception.DNSException as exc: - raise ValueError(f"Invalid domain in {field_label}: {value!r}") from exc + settings_key = _SETTINGS_KEY_BY_MODEL_TITLE[(info.config or {})["title"]] + raise ValueError(f"Invalid domain in {settings_key}: {value!r}") from exc return value diff --git a/src/devops_cli/exceptions/ai.py b/src/devops_cli/exceptions/ai.py index d31bce1483..ec48f099c9 100644 --- a/src/devops_cli/exceptions/ai.py +++ b/src/devops_cli/exceptions/ai.py @@ -10,7 +10,6 @@ CONST_ERROR_CODE_CONSTELLATION_QUIESCE, CONST_ERROR_CODE_CONSTELLATION_RESUME, CONST_ERROR_CODE_DOCS_INGESTION, - CONST_ERROR_CODE_HARNESS_EXECUTION, CONST_ERROR_CODE_HARNESS_VALIDATION, CONST_ERROR_CODE_LIBRARY_INGESTION, CONST_ERROR_CODE_LIBRARY_NOT_FOUND, @@ -184,24 +183,6 @@ def __init__( super().__init__(message, exit_code=exit_code, error_code=error_code, details=err_details) -class HarnessExecutionError(DevOpsCLIError, RuntimeError): - """Raised when execution of an AI test harness or benchmark fails.""" - - def __init__( - self, - message: str, - *, - harness_name: str | None = None, - exit_code: int = CONST_EXIT_FAILURE, - error_code: str = CONST_ERROR_CODE_HARNESS_EXECUTION, - details: dict[str, Any] | None = None, - ) -> None: - err_details = {"harness_name": harness_name} - if details: - err_details.update(details) - super().__init__(message, exit_code=exit_code, error_code=error_code, details=err_details) - - class ConstellationQuiesceError(DevOpsCLIError, RuntimeError): """Raised when constellation quiesce suspension fails.""" @@ -439,7 +420,6 @@ def __getattr__(name: str) -> Any: "CostNotFoundWarning", "DocsIngestionError", "FallbackExceptionGroup", - "HarnessExecutionError", "HarnessValidationError", "IncompleteToolCall", "LLMInferenceError", diff --git a/tests/conftest.py b/tests/conftest.py index bf59c54184..48f7b611ed 100755 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -98,7 +98,6 @@ def register_test_mock_provider(): "devops_cli.ai.concurrency": ("reset_shared_limiters",), "devops_cli.ai.context_budget": ("reset_tiktoken_encoding_cache",), "devops_cli.ai.gateway": ("clear_gateway_reasoning_cache",), - "devops_cli.ai.harness.compaction": ("reset_overflow_memory_fallback",), "devops_cli.ai.kb": ("reset_uv_lock_cache",), "devops_cli.ai.mcp.dispatcher": ("reset_mcp_dispatcher",), "devops_cli.ai.mcp.generator": ("reset_click_command_cache",), diff --git a/tests/fixtures/swallowed_failures_ceilings.json b/tests/fixtures/swallowed_failures_ceilings.json index 055421031c..c4afbf1cfc 100644 --- a/tests/fixtures/swallowed_failures_ceilings.json +++ b/tests/fixtures/swallowed_failures_ceilings.json @@ -25,17 +25,7 @@ "src/devops_cli/ai/durable.py": 4, "src/devops_cli/ai/function_signature.py": 1, "src/devops_cli/ai/gateway.py": 3, - "src/devops_cli/ai/harness/agents.py": 3, - "src/devops_cli/ai/harness/compaction.py": 11, - "src/devops_cli/ai/harness/conversation.py": 2, - "src/devops_cli/ai/harness/docs.py": 2, - "src/devops_cli/ai/harness/filesystem.py": 1, - "src/devops_cli/ai/harness/memory.py": 4, - "src/devops_cli/ai/harness/planning.py": 2, - "src/devops_cli/ai/harness/repo_context.py": 5, - "src/devops_cli/ai/harness/shell.py": 3, "src/devops_cli/ai/harness/slots.py": 3, - "src/devops_cli/ai/harness/workflow.py": 3, "src/devops_cli/ai/inspection.py": 2, "src/devops_cli/ai/library/drift_auditor.py": 2, "src/devops_cli/ai/library/introspector.py": 6, diff --git a/tests/test_ai_agent_capabilities.py b/tests/test_ai_agent_capabilities.py index 7e7e528546..3df07b19a4 100644 --- a/tests/test_ai_agent_capabilities.py +++ b/tests/test_ai_agent_capabilities.py @@ -1,4 +1,4 @@ -"""Unit tests for Pydantic AI SystemReminders, Instrumentation, and custom capability creation.""" +"""Unit tests for SystemReminders, custom capabilities, toolsets, embeddings and testing utilities.""" from __future__ import annotations @@ -8,8 +8,6 @@ from devops_cli.ai.agents.capabilities import ( BaseCapability, - Capability, - Instrumentation, SystemReminders, ) from devops_cli.ai.agents.context import RunContext @@ -57,41 +55,9 @@ def custom_cond(c: RunContext[Any], turn: int) -> bool: assert prompts1 == ["Turn reminder"] -def test_instrumentation_capability() -> None: - """Verify Instrumentation capability attributes and lifecycle hooks.""" - inst = Instrumentation(tracer_name="custom_tracer", record_spans=True, record_metrics=True) - assert inst.tracer_name == "custom_tracer" - assert inst.record_spans is True - assert inst.record_metrics is True - - hooks = inst.get_hooks() - assert hooks is not None - assert len(hooks.before_tool_execute) > 0 - assert len(hooks.after_tool_execute) > 0 - - ctx = RunContext() - hooks.before_tool_execute[0](ctx, "tool_a", {"arg1": "val1"}) - hooks.after_tool_execute[0](ctx, "tool_a", "result1") - - def test_custom_capability_creation() -> None: - """Verify creating custom capabilities using BaseCapability and Capability subclassing.""" - # 1. Using concrete Capability with tool decorator - cap = Capability(instructions="Use custom helper tools.") + """Verify creating a custom capability by subclassing BaseCapability.""" - @cap.tool - def helper_tool(x: int) -> int: - """Double an integer.""" - return x * 2 - - tools = cap.get_tools() - assert len(tools) == 1 - assert callable(tools[0]) - - prompts = cap.get_system_prompt_additions(RunContext()) - assert prompts == ["Use custom helper tools."] - - # 2. Subclassing BaseCapability directly class SecurityContextCapability(BaseCapability): id: str = "security_context" audit_mode: bool = True @@ -112,380 +78,9 @@ def get_tools(self) -> list[Any]: assert len(sec_cap.get_tools()) == 1 -def test_use_thread_executor_capability() -> None: - """Verify UseThreadExecutor and ThreadExecutor synchronous execution.""" - from concurrent.futures import ThreadPoolExecutor - - from devops_cli.ai.agents.capabilities import ThreadExecutor, UseThreadExecutor - - # 1. Default initialization - cap = UseThreadExecutor(max_workers=4, thread_name_prefix="test-worker") - assert cap.id == "use_thread_executor" - - def sync_compute(a: int, b: int) -> int: - return a * b + 10 - - result = cap.run_sync(sync_compute, 5, 6) - assert result == 40 - - # 2. Custom external ThreadPoolExecutor - custom_executor = ThreadPoolExecutor(max_workers=2) - cap_custom = ThreadExecutor(executor=custom_executor) - - def fetch_data(name: str) -> str: - return f"payload_{name}" - - res = cap_custom.run_sync(fetch_data, name="test") - assert res == "payload_test" - custom_executor.shutdown() - - -def test_select_model_capability() -> None: - """Verify SelectModel dynamic runtime model selection.""" - from devops_cli.ai.agents.capabilities import ModelSelectionContext, SelectModel - from devops_cli.ai.agents.context import RunContext - - def model_selector(ctx: ModelSelectionContext[dict[str, Any]]) -> str: - deps = ctx.deps or {} - if deps.get("task_complexity") == "complex": - return "openai:gpt-4o" - return "openai:gpt-4o-mini" - - cap = SelectModel(model_selector) - assert cap.id == "select_model" - - # 1. Standard model selection context - ctx_simple = ModelSelectionContext(deps={"task_complexity": "simple"}) - assert cap.select_model(ctx_simple) == "openai:gpt-4o-mini" - - ctx_complex = ModelSelectionContext(deps={"task_complexity": "complex"}) - assert cap.select_model(ctx_complex) == "openai:gpt-4o" - - # 2. RunContext interoperability - run_ctx = RunContext(deps={"task_complexity": "complex"}, session_id="s1") - assert cap.select_model(run_ctx) == "openai:gpt-4o" - - -def test_resolve_model_id_capability() -> None: - """Verify ResolveModelId custom alias and tenant-specific model resolution.""" - from devops_cli.ai.agents.capabilities import ModelResolutionContext, ResolveModelId - from devops_cli.ai.agents.context import RunContext - - def custom_resolver(ctx: ModelResolutionContext[dict[str, Any]], model_id: str) -> str | None: - if model_id.startswith("tenant:"): - tenant = (ctx.deps or {}).get("tenant", "default") - return f"openai:{tenant}-{model_id.removeprefix('tenant:')}" - if model_id == "alias:fast": - return "openai:gpt-4o-mini" - if model_id == "alias:reasoning": - return "openai:o1" - return None - - resolver_cap = ResolveModelId(custom_resolver) - assert resolver_cap.id == "resolve_model_id" - - # 1. Alias mapping - assert resolver_cap.resolve("alias:fast") == "openai:gpt-4o-mini" - assert resolver_cap.resolve("alias:reasoning") == "openai:o1" - - # 2. Unknown passes through as None - assert resolver_cap.resolve("openai:gpt-4o") is None - - # 3. Tenant resolution via context - ctx = ModelResolutionContext(deps={"tenant": "acme"}, model_id="tenant:prod-model") - assert resolver_cap.resolve("tenant:prod-model", ctx) == "openai:acme-prod-model" - - # 4. RunContext adapter - run_ctx = RunContext(deps={"tenant": "globex"}, model="tenant:staging-model") - assert resolver_cap.resolve("tenant:staging-model", run_ctx) == "openai:globex-staging-model" - - -def test_prepare_tools_capability() -> None: - """Verify PrepareTools dynamic filtering and modification of tool definitions.""" - from devops_cli.ai.agents.capabilities import PrepareTools - from devops_cli.ai.agents.context import RunContext - from devops_cli.ai.agents.tools import Tool - - def filter_admin_tools(ctx: RunContext[dict[str, Any]], tools: list[Any]) -> list[Any]: - is_admin = (ctx.deps or {}).get("is_admin", False) - if not is_admin: - return [t for t in tools if not getattr(t, "name", "").startswith("admin_")] - return tools - - cap = PrepareTools(filter_admin_tools) - assert cap.id == "prepare_tools" - - t_read = Tool.from_function(lambda: "read", name="read_data") - t_admin = Tool.from_function(lambda: "admin", name="admin_delete") - all_tools = [t_read, t_admin] - - # 1. Non-admin context filters out admin_delete - user_ctx = RunContext(deps={"is_admin": False}) - filtered = cap.prepare_tools(user_ctx, all_tools) - assert len(filtered) == 1 - assert filtered[0].name == "read_data" - - # 2. Admin context keeps all tools - admin_ctx = RunContext(deps={"is_admin": True}) - allowed = cap.prepare_tools(admin_ctx, all_tools) - assert len(allowed) == 2 - assert {t.name for t in allowed} == {"read_data", "admin_delete"} - - -def test_prefix_tools_capability() -> None: - """Verify PrefixTools namespacing capability and .prefix_tools() convenience method.""" - from devops_cli.ai.agents.capabilities import Capability, PrefixTools - - cap = Capability() - - @cap.tool - def search_query(q: str) -> str: - """Search query.""" - return f"result for {q}" - - @cap.tool - def list_items() -> list[str]: - """List items.""" - return ["item1", "item2"] - - # 1. Using PrefixTools class constructor - prefixed_cap = PrefixTools(cap, prefix="api1") - assert prefixed_cap.id == "prefix_tools" - prefixed_tools = prefixed_cap.get_tools() - assert len(prefixed_tools) == 2 - names = {getattr(t, "name", "") for t in prefixed_tools} - assert names == {"api1_search_query", "api1_list_items"} - - # 2. Using .prefix_tools() method on BaseCapability - method_prefixed = cap.prefix_tools("v2") - assert isinstance(method_prefixed, PrefixTools) - assert method_prefixed.prefix == "v2" - tools_v2 = method_prefixed.get_tools() - assert {getattr(t, "name", "") for t in tools_v2} == {"v2_search_query", "v2_list_items"} - - -def test_include_tool_return_schemas_capability() -> None: - """Verify IncludeToolReturnSchemas capability applying schema inclusion flag.""" - from devops_cli.ai.agents.capabilities import IncludeToolReturnSchemas - from devops_cli.ai.agents.context import RunContext - from devops_cli.ai.agents.tools import Tool - - cap = IncludeToolReturnSchemas(include_return_schema=True) - assert cap.id == "include_tool_return_schemas" - assert cap.include_return_schema is True - - tool_a = Tool.from_function(lambda x: x + 1, name="inc") - tool_b = Tool.from_function(lambda y: f"val={y}", name="fmt") - - prepared = cap.prepare_tools(RunContext(), [tool_a, tool_b]) - assert len(prepared) == 2 - assert all(getattr(t, "include_return_schema", False) is True for t in prepared) - - -def test_set_tool_metadata_capability() -> None: - """Verify SetToolMetadata capability attaching custom tags/attributes to tools.""" - from devops_cli.ai.agents.capabilities import Capability, SetToolMetadata - from devops_cli.ai.agents.context import RunContext - from devops_cli.ai.agents.tools import Tool - - cap = Capability() - - @cap.tool - def fetch_data(key: str) -> str: - """Fetch data.""" - return f"val:{key}" - - # 1. Using SetToolMetadata class constructor - meta_cap = SetToolMetadata({"tier": "premium", "read_only": True}, capability=cap) - assert meta_cap.id == "set_tool_metadata" - tools = meta_cap.get_tools() - assert len(tools) == 1 - assert tools[0].metadata == {"tier": "premium", "read_only": True} - - # 2. Using .with_metadata() convenience method on BaseCapability - tagged_cap = cap.with_metadata(source="db", cache_ttl=300) - assert isinstance(tagged_cap, SetToolMetadata) - tagged_tools = tagged_cap.get_tools() - assert tagged_tools[0].metadata == {"source": "db", "cache_ttl": 300} - - # 3. Dynamic prepare_tools runtime metadata injection - runtime_tool = Tool.from_function(lambda: 42, name="num", metadata={"initial": True}) - prepared = meta_cap.prepare_tools(RunContext(), [runtime_tool]) - assert prepared[0].metadata["initial"] is True - assert prepared[0].metadata["tier"] == "premium" - - -def test_raise_content_filter_error_capability() -> None: - """Verify RaiseContentFilterError capability detecting content safety block finish reasons.""" - from devops_cli.ai.agents.capabilities import RaiseContentFilterError - from devops_cli.exceptions.ai import ContentFilterError - - cap = RaiseContentFilterError() - assert cap.id == "raise_content_filter_error" - - # 1. Normal finish reasons pass without raising - cap.check_response({"finish_reason": "stop", "text": "Hello world"}) - cap.check_response({"finish_reason": "length", "text": "Truncated"}) - - # 2. content_filter triggers ContentFilterError with body inspection - response_blocked = { - "finish_reason": "content_filter", - "text": "I cannot fulfill this request.", - "safety_ratings": [{"category": "HATE_SPEECH", "probability": "HIGH"}], - } - with pytest.raises(ContentFilterError) as exc_info: - cap.check_response(response_blocked) - - assert exc_info.value.error_code == "CONTENT_FILTER_TRIGGERED" - assert exc_info.value.body == response_blocked - - -def test_reinject_system_prompt_capability() -> None: - """Verify ReinjectSystemPrompt capability ensuring agent system prompt presence.""" - from devops_cli.ai.agents.capabilities import ReinjectSystemPrompt - - cap = ReinjectSystemPrompt() - assert cap.id == "reinject_system_prompt" - assert cap.replace_existing is False - - # 1. Missing system prompt gets prepended - user_msgs = [{"role": "user", "content": "What is Python?"}] - injected = cap.reinject(user_msgs, "You are a senior DevOps architect.") - assert len(injected) == 2 - assert injected[0]["role"] == "system" - assert injected[0]["content"] == "You are a senior DevOps architect." - - # 2. Existing system prompt preserved by default - existing_msgs = [ - {"role": "system", "content": "Initial prompt"}, - {"role": "user", "content": "hello"}, - ] - preserved = cap.reinject(existing_msgs, "New prompt") - assert len(preserved) == 2 - assert preserved[0]["content"] == "Initial prompt" - - # 3. replace_existing=True replaces existing system prompt - replace_cap = ReinjectSystemPrompt(replace_existing=True) - replaced = replace_cap.reinject(existing_msgs, "Overridden authoritative prompt") - assert len(replaced) == 2 - assert replaced[0]["content"] == "Overridden authoritative prompt" - - -def test_process_history_capability() -> None: - """Verify ProcessHistory capability applying message history processors.""" - from devops_cli.ai.agents.capabilities import ProcessHistory - from devops_cli.ai.agents.context import RunContext - - # 1. Trimming processor (keep last N messages) - def keep_recent(messages: list[dict[str, str]]) -> list[dict[str, str]]: - return messages[-2:] - - trim_cap = ProcessHistory(keep_recent) - assert trim_cap.id == "process_history" - - history = [ - {"role": "user", "content": "1"}, - {"role": "assistant", "content": "2"}, - {"role": "user", "content": "3"}, - {"role": "assistant", "content": "4"}, - ] - processed = trim_cap.process_history(history) - assert len(processed) == 2 - assert processed[0]["content"] == "3" - assert processed[1]["content"] == "4" - - # 2. Context-aware processor (redaction or tagging) - def redact_secrets( - ctx: RunContext[dict[str, Any]], messages: list[dict[str, str]] - ) -> list[dict[str, str]]: - redact = (ctx.deps or {}).get("redact", False) - if not redact: - return messages - return [{**m, "content": m["content"].replace("SECRET", "[REDACTED]")} for m in messages] - - redact_cap = ProcessHistory(redact_secrets) - msgs_with_secret = [{"role": "user", "content": "api key is SECRET"}] - - # Without redact flag - assert ( - redact_cap.process_history(msgs_with_secret, RunContext())[0]["content"] - == "api key is SECRET" - ) - - # With redact flag - ctx_redact = RunContext(deps={"redact": True}) - assert ( - redact_cap.process_history(msgs_with_secret, ctx_redact)[0]["content"] - == "api key is [REDACTED]" - ) - - -@pytest.mark.anyio -async def test_process_event_stream_capability() -> None: - """Verify ProcessEventStream capability handling streaming events and observers.""" - from devops_cli.ai.agents.capabilities import AgentStreamEvent, ProcessEventStream - from devops_cli.ai.agents.context import RunContext - - observed_events: list[AgentStreamEvent] = [] - - async def log_events(ctx: RunContext[dict[str, Any]], events: list[AgentStreamEvent]) -> None: - for event in events: - observed_events.append(event) - - cap = ProcessEventStream(log_events) - assert cap.id == "process_event_stream" - - event1 = AgentStreamEvent(event_kind="token", content="Hello") - event2 = AgentStreamEvent(event_kind="token", content=" world") - event3 = AgentStreamEvent(event_kind="tool_call", content="search_query") - - stream = [event1, event2, event3] - result = await cap.handle_stream(stream, RunContext(deps={"stream_id": "s1"})) - assert result is None - assert len(observed_events) == 3 - assert observed_events[0].content == "Hello" - assert observed_events[2].event_kind == "tool_call" - - -def test_subagents_usage_forwarding() -> None: - """Verify SubAgents capability forwards usage tracking to child agents.""" - from unittest.mock import MagicMock - - from devops_cli.ai.agents.context import AgentUsage, RunContext - from devops_cli.ai.harness.workflow import SubAgent, SubAgents - - child_agent = MagicMock() - child_resp = MagicMock() - child_resp.content = "Child agent result" - - def child_run(task: str, usage: AgentUsage | None = None) -> Any: - if usage is not None: - usage.input_tokens += 100 - usage.output_tokens += 50 - usage.total_tokens += 150 - return child_resp - - child_agent.run.side_effect = child_run - - sub_agent_def = SubAgent(name="specialist", description="Domain specialist", agent=child_agent) - subagents_cap = SubAgents(agents=[sub_agent_def], forward_usage=True) - - tools = subagents_cap.get_tools() - delegate_tool = next(t for t in tools if getattr(t, "name", "") == "delegate_task") - - parent_usage = AgentUsage(input_tokens=20, output_tokens=10, total_tokens=30) - ctx = RunContext(usage=parent_usage) - - res = delegate_tool.function(ctx=ctx, agent_name="specialist", task="analyze logs") - assert res == "Child agent result" - assert parent_usage.input_tokens == 120 - assert parent_usage.output_tokens == 60 - assert parent_usage.total_tokens == 180 - - def test_agent_tool_args_validator() -> None: """Verify args_validator_func supports pre-execution argument validation and transformation.""" - from devops_cli.ai.agents.tools import FunctionToolset, Tool + from devops_cli.ai.agents.tools import FunctionToolset def sample_tool(ctx: Any, target: str, count: int) -> str: return f"{target}:{count}" @@ -518,7 +113,7 @@ def decorated_tool(ctx: Any, target: str, count: int) -> str: def test_abstract_custom_toolset() -> None: """Verify custom AbstractToolset subclasses integrate with PydanticAgent.""" from devops_cli.ai.agents.agent import PydanticAgent - from devops_cli.ai.agents.tools import AbstractToolset, AgentTool, Tool + from devops_cli.ai.agents.tools import AbstractToolset, AgentTool class DynamicMetricToolset(AbstractToolset): prefix: str = "metric_" @@ -542,6 +137,58 @@ def get_instructions(self, ctx: Any = None) -> list[str]: assert "k8s_cpu" in agent._tools +@pytest.mark.anyio +async def test_mcp_toolset() -> None: + """Verify MCPToolset lifecycle, tool registration, prefixing and config loading.""" + from devops_cli.ai.agents.agent import PydanticAgent + from devops_cli.ai.agents.testing import TestModel + from devops_cli.ai.agents.tools import AgentTool, MCPToolset + + # 1. MCPToolset instantiation and lifecycle + tool1 = AgentTool( + name="mcp_query", description="Query remote MCP", func=lambda q: f"Result: {q}" + ) + mcp_ts = MCPToolset(url="https://example.com/api", tools=[tool1]) + + assert len(mcp_ts.get_tools()) == 1 + assert mcp_ts.get_tools()[0].name == "mcp_query" + instructions = mcp_ts.get_instructions() + assert len(instructions) == 1 + assert "https://example.com/api" in instructions[0] + + # Context manager lifecycle + async with mcp_ts as ts: + assert len(ts.get_tools()) == 1 + + # 2. Tool prefixing and from_config loading + mcp_prefix = MCPToolset( + "https://example.com/api", + tool_prefix="slack", + tools=[tool1], + ) + prefixed_tools = mcp_prefix.get_tools() + assert len(prefixed_tools) == 1 + assert prefixed_tools[0].name == "slack_mcp_query" + + config = { + "mcpServers": { + "github": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"]}, + "fetch": {"url": "http://localhost:8000/sse"}, + } + } + loaded = MCPToolset.from_config(config) + assert len(loaded) == 2 + assert loaded[0].tool_prefix == "github" + assert loaded[1].url == "http://localhost:8000/sse" + + # 3. End-to-end execution with agent and async context manager + agent = PydanticAgent(name="MCPAgent", model="openai:gpt-4o", toolsets=[mcp_ts]) + async with agent: + with agent.override(model=TestModel(custom_output_text="MCP processed")): + res = agent.run("Run mcp tool") + assert res.content == "MCP processed" + + @pytest.mark.anyio async def test_embedder_and_embedding_result() -> None: """Verify Embedder interface and EmbeddingResult container indexing and cost calculation.""" @@ -687,82 +334,3 @@ def custom_tool(x: int) -> int: finally: testing_module.ALLOW_MODEL_REQUESTS = orig_allow agent_module.ALLOW_MODEL_REQUESTS = orig_allow - - -@pytest.mark.anyio -async def test_mcp_toolset_and_capability() -> None: - """Verify MCPToolset lifecycle, tool registration, and MCP capability adaptation.""" - from devops_cli.ai.agents.agent import PydanticAgent - from devops_cli.ai.agents.capabilities import MCP, MCPServerTool - from devops_cli.ai.agents.testing import TestModel - from devops_cli.ai.agents.tools import AgentTool, MCPToolset - - # 1. MCPToolset instantiation and lifecycle - tool1 = AgentTool( - name="mcp_query", description="Query remote MCP", func=lambda q: f"Result: {q}" - ) - mcp_ts = MCPToolset(url="https://example.com/api", tools=[tool1]) - - assert len(mcp_ts.get_tools()) == 1 - assert mcp_ts.get_tools()[0].name == "mcp_query" - instructions = mcp_ts.get_instructions() - assert len(instructions) == 1 - assert "https://example.com/api" in instructions[0] - - # Context manager lifecycle - async with mcp_ts as ts: - assert len(ts.get_tools()) == 1 - - # 2. MCP capability with MCPToolset as local - mcp_cap = MCP(url="https://example.com/api", local=mcp_ts) - tools = mcp_cap.get_tools() - assert len(tools) == 1 - assert tools[0].name == "mcp_query" - - # 3. MCP capability with native=True - mcp_native = MCP(url="https://example.com/api", native=True) - settings = mcp_native.get_model_settings() - assert settings.get("native_mcp_server") is True - assert settings["mcp_server_config"]["url"] == "https://example.com/api" - - # 4. MCP capability with MCPServerTool instance - server_tool = MCPServerTool( - url="https://example.com/sse", id="prod_mcp", authorization_token="secret-token-value" - ) - mcp_server_cap = MCP(native=server_tool) - server_settings = mcp_server_cap.get_model_settings() - assert server_settings["mcp_server_config"]["url"] == "https://example.com/sse" - assert server_settings["mcp_server_config"]["authorization_token"] == "secret-token-value" - - # 5. Tool prefixing and from_config loading - mcp_prefix = MCPToolset( - "https://example.com/api", - tool_prefix="slack", - tools=[tool1], - ) - prefixed_tools = mcp_prefix.get_tools() - assert len(prefixed_tools) == 1 - assert prefixed_tools[0].name == "slack_mcp_query" - - config = { - "mcpServers": { - "github": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"]}, - "fetch": {"url": "http://localhost:8000/sse"}, - } - } - loaded = MCPToolset.from_config(config) - assert len(loaded) == 2 - assert loaded[0].tool_prefix == "github" - assert loaded[1].url == "http://localhost:8000/sse" - - # 6. End-to-end execution with agent and async context manager - agent = PydanticAgent( - name="MCPAgent", - model="openai:gpt-4o", - capabilities=[mcp_cap], - toolsets=[mcp_ts], - ) - async with agent: - with agent.override(model=TestModel(custom_output_text="MCP processed")): - res = agent.run("Run mcp tool") - assert res.content == "MCP processed" diff --git a/tests/test_ai_agent_deferred_tools.py b/tests/test_ai_agent_deferred_tools.py index 2ab2d32aa6..a652917cf4 100644 --- a/tests/test_ai_agent_deferred_tools.py +++ b/tests/test_ai_agent_deferred_tools.py @@ -12,7 +12,6 @@ DeferredToolRequests, DeferredToolResults, HandleDeferredToolCalls, - Thinking, ToolApproved, ToolCallPart, ToolDenied, @@ -217,8 +216,8 @@ def resolve(capabilities: list[BaseCapability], session_id: str) -> dict[str, st return _decisions(_find_deferred_tool_handler(capabilities, reqs, ctx)) assert ( - resolve([Thinking(), approve], "user"), - resolve([Thinking()], "user"), + resolve([BaseCapability(), approve], "user"), + resolve([BaseCapability()], "user"), resolve([_NativeHookCapability(), approve], "admin"), resolve([_NativeHookCapability(), approve], "user"), resolve([_MethodHookCapability(), approve], "guest"), diff --git a/tests/test_architectural_invariants.py b/tests/test_architectural_invariants.py index f553b52c44..dcd07f81ce 100644 --- a/tests/test_architectural_invariants.py +++ b/tests/test_architectural_invariants.py @@ -105,7 +105,6 @@ def test_domain_specific_exceptions_exist() -> None: """Ensure newly established domain exceptions are defined with correct error codes.""" from devops_cli.exceptions.ai import ( DocsIngestionError, - HarnessExecutionError, HarnessValidationError, LibraryIngestionError, LibraryNotFoundError, @@ -133,7 +132,6 @@ def test_domain_specific_exceptions_exist() -> None: assert issubclass(ChaosExecutionError, KubernetesError) assert issubclass(ModelBundleError, DevOpsCLIError) assert issubclass(HarnessValidationError, DevOpsCLIError) - assert issubclass(HarnessExecutionError, DevOpsCLIError) assert issubclass(LibraryIngestionError, DevOpsCLIError) assert issubclass(LibraryNotFoundError, LibraryIngestionError) assert issubclass(DocsIngestionError, DevOpsCLIError) @@ -164,10 +162,6 @@ def test_domain_specific_exceptions_exist() -> None: assert h_val.error_code == "HARNESS_VALIDATION_ERROR" assert h_val.exit_code == 1 - h_exec = HarnessExecutionError("harness run failed") - assert h_exec.error_code == "HARNESS_EXECUTION_ERROR" - assert h_exec.exit_code == 1 - from devops_cli.ai.rag.embeddings import EmbeddingsError from devops_cli.exceptions.telemetry import LogfireConfigurationError, TelemetryError @@ -262,11 +256,6 @@ def test_no_bare_generic_exceptions_in_refactored_modules() -> None: Path("src/devops_cli/ai/model_bundler.py"), Path("src/devops_cli/ai/durable.py"), Path("src/devops_cli/ai/harness/skills.py"), - Path("src/devops_cli/ai/harness/workflow.py"), - Path("src/devops_cli/ai/harness/planning.py"), - Path("src/devops_cli/ai/harness/shell.py"), - Path("src/devops_cli/ai/harness/memory.py"), - Path("src/devops_cli/ai/harness/compaction.py"), Path("src/devops_cli/ai/harness/slots.py"), ] diff --git a/tests/test_codebase_hygiene_and_shims.py b/tests/test_codebase_hygiene_and_shims.py index e93d6b0539..71df76b3c0 100644 --- a/tests/test_codebase_hygiene_and_shims.py +++ b/tests/test_codebase_hygiene_and_shims.py @@ -4,7 +4,6 @@ import ast import importlib.util -import inspect import re from collections import Counter from pathlib import Path @@ -12,8 +11,6 @@ from pydantic_ai.tools import RunContext as NativeRunContext from devops_cli.ai.agents.context import RunContext -from devops_cli.ai.harness.compaction import WarnOnCacheBusts -from devops_cli.ai.harness.shell import Shell from devops_cli.ai.mcp.server import list_mcp_tools from devops_cli.ai.personas import Persona from devops_cli.ai.rag.chunker import SemanticChunker @@ -160,23 +157,6 @@ def test_rag_app_has_no_reset_alias() -> None: assert "reset" not in cmd_names, "rag reset alias should be removed" -def test_shell_execution_has_no_run_shell_alias() -> None: - """Shell.get_tools() should provide canonical run_command, not run_shell alias.""" - shell = Shell() - tool_names = [t.name for t in shell.get_tools() if hasattr(t, "name")] - assert "run_command" in tool_names - assert "run_shell" not in tool_names, "Duplicate run_shell alias should be removed" - - -def test_compaction_cache_monitor_consolidated_parameters() -> None: - """WarnOnCacheBusts.record_request should use consolidated 'now' parameter without 'current_time'.""" - monitor = WarnOnCacheBusts() - sig = inspect.signature(monitor.record_request) - assert "now" in sig.parameters - assert "current_time" not in sig.parameters - assert not hasattr(monitor, "record_usage"), "Legacy record_usage alias should be removed" - - def test_chunker_no_hardcoded_extension_sets(tmp_path: Path) -> None: """chunker.py should not define hardcoded literal sets of file extensions.""" import devops_cli.ai.rag.chunker as chunker_mod diff --git a/tests/test_docs.py b/tests/test_docs.py index 4df7d38542..206405cfe8 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -769,13 +769,12 @@ def test_configuration_and_error_catalog_docs_describe_real_surface( f"(`{field}`)" in config_md or f"| `{field}` |" in config_md for field in Settings.model_fields ), - "| `MemoryOperationConflictError` | `HARNESS_EXECUTION_ERROR` | `1` |" in errors_md, "| `ChecksumMismatchError` | `CHECKSUM_MISMATCH` | `1` |" in errors_md, "| `SecretExposureError` | `SECRET_EXPOSURE_DETECTED` | `4` |" in errors_md, "| `ToolDownloadError` | `TOOL_DOWNLOAD_ERROR` | `1` |" in errors_md, "Only `devops cloudflare`, `devops valkey` and `devops sandbox` exit with it today" in errors_md, - ) == (2, 130, True, True, True, True, True, True, True, True, True) + ) == (2, 130, True, True, True, True, True, True, True, True) def _unwrap_settings_model(annotation: object) -> type | None: diff --git a/tests/test_harness.py b/tests/test_harness.py deleted file mode 100644 index dadfefe396..0000000000 --- a/tests/test_harness.py +++ /dev/null @@ -1,2506 +0,0 @@ -"""Unit tests for Pydantic AI Harness components and composite stacks.""" - -from __future__ import annotations - -import contextlib -import logging -import os -import re -import shlex -import signal -import subprocess -from collections.abc import Callable -from pathlib import Path -from typing import Any -from unittest.mock import MagicMock, call, patch - -import pytest - -from devops_cli.ai.agents.agent import PydanticAgent -from devops_cli.ai.harness import ( - Coder, - FileSystem, - Planning, - RepoContext, - Researcher, - Shell, - SubAgent, - SubAgents, -) -from tests.support.waits import THREAD_HANDOFF_BOUND_SECONDS, wait_until - -pytestmark = [ - pytest.mark.usefixtures("mock_keyring", "public_dns"), - pytest.mark.live("echo", "sleep", "sh", "python"), -] - - -def test_file_system_safe_operations(tmp_path: Path) -> None: - test_file = tmp_path / "sample.txt" - test_file.write_text("Hello from harness file system") - - fs = FileSystem(root=tmp_path) - tools = {t.name: t for t in fs.get_tools() if hasattr(t, "name")} - - assert "read_file" in tools - assert "write_file" in tools - assert "list_directory" in tools - - read_res = tools["read_file"].execute(path="sample.txt") - assert "Hello from harness file system" in read_res - assert "sha256:" in read_res - - write_res = tools["write_file"].execute( - path="nested/output.txt", content="New data\nSecond line" - ) - assert "successfully written" in write_res - assert (tmp_path / "nested" / "output.txt").read_text() == "New data\nSecond line" - - # Edit file - edit_res = tools["edit_file"].execute( - path="nested/output.txt", old_text="Second line", new_text="Edited line" - ) - assert "successfully edited" in edit_res - assert "Edited line" in (tmp_path / "nested" / "output.txt").read_text() - - # Search & Find - search_res = tools["search_files"].execute(query="Edited", path=".") - assert "nested/output.txt" in search_res - - find_res = tools["find_files"].execute(pattern="*.txt", path=".") - assert "sample.txt" in find_res - assert "nested/output.txt" in find_res - - # File info - info_res = tools["file_info"].execute(path="nested/output.txt") - assert "Size:" in info_res - assert "sha256:" in info_res - - list_res = tools["list_directory"].execute(path=".") - assert "sample.txt" in list_res - assert "nested" in list_res - - -def test_file_system_protected_and_denied_patterns(tmp_path: Path) -> None: - env_file = tmp_path / ".env" - env_file.write_text("SECRET=123") - - fs = FileSystem(root_dir=tmp_path) - tools = {t.name: t for t in fs.get_tools() if hasattr(t, "name")} - - # Protected file (.env) is read-only - write_res = tools["write_file"].execute(path=".env", content="NEW_SECRET=456") - assert "Access denied" in write_res or "is protected" in write_res - - -def test_file_system_path_traversal_blocked(tmp_path: Path) -> None: - fs = FileSystem(root=tmp_path) - tools = {t.name: t for t in fs.get_tools() if hasattr(t, "name")} - - with pytest.raises(PermissionError): - tools["read_file"].execute(path="../../../etc/passwd") - - -def test_shell_allowed_commands(tmp_path: Path) -> None: - sh = Shell(cwd=tmp_path, allowed_commands=["echo", "ls"]) - tools = {t.name: t for t in sh.get_tools() if hasattr(t, "name")} - - res = tools["run_command"].execute(command="echo hello_devops") - assert "hello_devops" in res - assert "[stdout]" in res - - blocked_res = tools["run_command"].execute(command="rm -rf /") - assert "blocked by security allowlist" in blocked_res - - -def test_shell_background_and_interactive(tmp_path: Path) -> None: - sh = Shell(cwd=tmp_path, allowed_commands=["echo", "sleep"]) - tools = {t.name: t for t in sh.get_tools() if hasattr(t, "name")} - - # Background start, check, stop - start_res = tools["start_command"].execute(command="sleep 10") - assert "Background command started with ID: " in start_res - cmd_id = start_res.split("ID: ")[1].strip() - - check_res = tools["check_command"].execute(command_id=cmd_id) - assert "status:" in check_res - - stop_res = tools["stop_command"].execute(command_id=cmd_id) - assert "terminated" in stop_res - - -def test_shell_denied_and_interactive_blocks(tmp_path: Path) -> None: - sh = Shell(cwd=tmp_path, allow_interactive=False) - tools = {t.name: t for t in sh.get_tools() if hasattr(t, "name")} - - interactive_res = tools["run_command"].execute(command="vi file.txt") - assert "Interactive command 'vi' is blocked" in interactive_res - - denied_res = tools["run_command"].execute(command="rm -rf /tmp/foo") - assert "blocked by security denylist" in denied_res - - with pytest.raises(ValueError, match="mutually exclusive"): - Shell(allowed_commands=["ls"], denied_commands=["rm"]) - - -def test_planning_capability() -> None: - plan = Planning() - tools = {t.name: t for t in plan.get_tools() if hasattr(t, "name")} - - assert "update_plan" in tools - update_res = tools["update_plan"].execute(steps=["Step 1: Discover", "Step 2: Execute"]) - assert "2 steps" in update_res - - items = plan.resolve_store().get_items() - assert len(items) == 2 - assert items[0].content == "Step 1: Discover" - assert items[1].content == "Step 2: Execute" - - prompt_additions = plan.get_system_prompt_additions() - assert "You have access to a structured planning toolset" in prompt_additions[0] - - -def test_repo_context_injection(tmp_path: Path) -> None: - agents_md = tmp_path / "AGENTS.md" - agents_md.write_text("# Core Philosophy\nHigh Reliability First.") - - repo = RepoContext(workspace_dir=tmp_path, expose_inventory_tool=False) - additions = repo.get_system_prompt_additions() - assert len(additions) == 1 - assert "High Reliability First" in additions[0] - - -def test_sub_agents_delegation() -> None: - mock_client = MagicMock() - mock_client.model = "test-model" - - child_agent = PydanticAgent( - client=mock_client, - name="ExplorerAgent", - system_prompt="Explore files.", - ) - mock_client.chat_messages.return_value = "Found 3 services in k8s/." - - sub_agent_wrap = SubAgent( - child_agent, name="explorer", description="Explores repository structure" - ) - sub_agents_cap = SubAgents(agents=[sub_agent_wrap]) - tools = {t.name: t for t in sub_agents_cap.get_tools() if hasattr(t, "name")} - - assert "delegate_to_explorer" in tools - res = tools["delegate_to_explorer"].execute(prompt="Check k8s directory") - assert "Found 3 services in k8s/." in res - - -def test_coder_and_researcher_harness_stacks(tmp_path: Path) -> None: - coder = Coder(workspace_dir=tmp_path) - coder_tools = coder.get_tools() - coder_tool_names = {t.name for t in coder_tools if hasattr(t, "name")} - assert "read_file" in coder_tool_names - assert "run_command" in coder_tool_names - assert "update_plan" in coder_tool_names - - researcher = Researcher() - researcher_tools = researcher.get_tools() - researcher_tool_names = {t.name for t in researcher_tools if hasattr(t, "name")} - assert "web_fetch" in researcher_tool_names - assert "duckduckgo_search" in researcher_tool_names - - -def test_coder_agent_factory(tmp_path: Path) -> None: - from devops_cli.ai.harness import coder_agent - - mock_client = MagicMock() - mock_client.model = "test-model" - - agent = coder_agent(client=mock_client, workspace_dir=tmp_path) - assert agent.name == "coder" - assert "read_file" in agent._tools - assert "run_command" in agent._tools - assert "update_plan" in agent._tools - - -def test_researcher_agent_factory() -> None: - from devops_cli.ai.harness import researcher_agent - - mock_client = MagicMock() - mock_client.model = "test-model" - - agent = researcher_agent(client=mock_client) - assert agent.name == "researcher" - assert "web_fetch" in agent._tools - assert "duckduckgo_search" in agent._tools - assert "Search broadly before drawing conclusions" in agent.system_prompt - - -def test_macroscope_capability_missing_cli(tmp_path: Path) -> None: - from devops_cli.ai.harness import Macroscope - - cap = Macroscope(command="nonexistent_macroscope_bin", cwd=tmp_path) - tools = cap.get_tools() - assert len(tools) == 1 - tool_func = tools[0].function # type: ignore[union-attr] - result = tool_func() - assert "not found" in result - assert "curl -sSL https://raw.githubusercontent.com/prassoai/macroscope-local" in result - - -def test_macroscope_capability_streaming_findings(tmp_path: Path) -> None: - import json - from unittest.mock import patch - - from devops_cli.ai.harness import Macroscope - - mock_output = "\n".join( - [ - json.dumps({"type": "review_id", "id": "rev-12345"}), - json.dumps( - { - "type": "issue_event", - "issue": { - "issue_id": "iss-1", - "sequence": 1, - "path": "src/app.py", - "line": 42, - "severity": "high", - "category": "security", - "body": "Unsanitized user input leading to SQL injection", - }, - } - ), - json.dumps({"type": "issue_status", "status": "completed"}), - ] - ) - - cap = Macroscope(base="main", cwd=tmp_path) - sys_prompt = cap.get_system_prompt_additions() - assert "Macroscope Code Review Capability enabled." in sys_prompt[0] - - with ( - patch("shutil.which", return_value="/usr/local/bin/macroscope"), - patch("subprocess.run") as mock_run, - ): - mock_proc = MagicMock() - mock_proc.returncode = 0 - mock_proc.stdout = mock_output - mock_run.return_value = mock_proc - - tool = cap.get_tools()[0] - res = tool.function() # type: ignore[union-attr] - assert "Macroscope Review (rev-12345)" in res - assert "[HIGH] src/app.py:42 (security)" in res - assert "Unsanitized user input" in res - - -def test_playwright_browser_capability() -> None: - from devops_cli.ai.harness import PlaywrightBrowser - - browser_cap = PlaywrightBrowser( - headless=True, - block_private_addresses=True, - allowed_domains=["example.com"], - ) - - prompt_additions = browser_cap.get_system_prompt_additions() - assert "Playwright Browser Capability enabled." in prompt_additions[0] - - tools = {t.name: t for t in browser_cap.get_tools()} - assert "navigate" in tools - assert "snapshot" in tools - assert "click" in tools - assert "type_text" in tools - assert "press_key" in tools - assert "select_option" in tools - assert "hover" in tools - assert "wait_for" in tools - assert "screenshot" in tools - assert "get_text" in tools - assert "scroll" in tools - assert "go_back" in tools - assert "go_forward" in tools - assert "execute_js" in tools - assert "console_messages" in tools - assert "tabs" in tools - assert "handle_next_dialog" in tools - assert "network_requests" in tools - - # Navigate - assert "Egress blocked" in tools["navigate"].function("http://127.0.0.1:8080/admin") # type: ignore[union-attr] - assert "Navigated to https://example.com" in tools["navigate"].function("https://example.com") # type: ignore[union-attr] - - # Inspect other tools - assert "RootWebArea" in tools["snapshot"].function() # type: ignore[union-attr] - assert "Clicked element '#btn'" in tools["click"].function(selector="#btn") # type: ignore[union-attr] - assert "Typed 'hello'" in tools["type_text"].function(selector="#input", text="hello") # type: ignore[union-attr] - assert "Pressed key 'Enter'" in tools["press_key"].function(key="Enter") # type: ignore[union-attr] - assert "Selected options" in tools["select_option"].function( - selector="#dropdown", values=["val1"] - ) # type: ignore[union-attr] - assert "Hovered over" in tools["hover"].function(selector="#item") # type: ignore[union-attr] - assert "Waited until #modal appeared" in tools["wait_for"].function(selector="#modal") # type: ignore[union-attr] - assert "Waited until #loader disappeared" in tools["wait_for"].function( - selector="#loader", gone=True - ) # type: ignore[union-attr] - assert "Screenshot captured" in tools["screenshot"].function() # type: ignore[union-attr] - assert "Page text content" in tools["get_text"].function() # type: ignore[union-attr] - assert "Scrolled page down" in tools["scroll"].function(direction="down") # type: ignore[union-attr] - assert "Navigated back" in tools["go_back"].function() # type: ignore[union-attr] - assert "Navigated forward" in tools["go_forward"].function() # type: ignore[union-attr] - assert "Script executed" in tools["execute_js"].function(script="console.log('hi')") # type: ignore[union-attr] - assert "Console logs:" in tools["console_messages"].function() # type: ignore[union-attr] - assert "Tabs action 'list'" in tools["tabs"].function(action="list") # type: ignore[union-attr] - assert "Next dialog configured" in tools["handle_next_dialog"].function(accept=True) # type: ignore[union-attr] - assert "Network requests:" in tools["network_requests"].function() # type: ignore[union-attr] - - -def test_playwright_browser_navigate_domain_and_ipv6_table() -> None: - """Verify PlaywrightBrowser.navigate uses urlsplit hostname and is_at_or_under (#887).""" - from devops_cli.ai.harness import PlaywrightBrowser - - def run_navigate(cap: PlaywrightBrowser, url: str) -> str: - nav_tool = {getattr(t, "name", ""): t for t in cap.get_tools()}["navigate"] - fn = getattr(nav_tool, "function") - return str(fn(url)) - - cap_default = PlaywrightBrowser( - block_private_addresses=True, - allowed_domains=["example.com"], - ) - cap_no_private = PlaywrightBrowser( - block_private_addresses=False, - allowed_domains=["example.com"], - ) - cap_ipv6 = PlaywrightBrowser( - block_private_addresses=False, - allowed_domains=["2001:db8::1"], - ) - - assert ( - "Egress blocked" in run_navigate(cap_default, "http://example.com:80@8.8.8.8/"), - "Navigated to http://EXAMPLE.COM./" in run_navigate(cap_default, "http://EXAMPLE.COM./"), - "Egress blocked" in run_navigate(cap_no_private, "http://a..b.example.com/"), - "Navigated to http://[2001:db8::1]/" in run_navigate(cap_ipv6, "http://[2001:db8::1]/"), - ) == (True, True, True, True) - - -def test_file_system_edge_cases(tmp_path: Path) -> None: - from devops_cli.ai.harness import FileSystem - - fs = FileSystem(root=tmp_path) - tools = {t.name: t for t in fs.get_tools() if hasattr(t, "name")} - - # Non-existent file read - assert "file not found" in tools["read_file"].execute(path="nonexistent.txt") - - # Binary file read - bin_file = tmp_path / "data.bin" - bin_file.write_bytes(b"\x00\x01\x02\x03\x04") - assert "Binary file" in tools["read_file"].execute(path="data.bin") - - # Stale edit conflict on write - text_file = tmp_path / "test.txt" - text_file.write_text("v1 content") - res_stale = tools["write_file"].execute( - path="test.txt", content="v2 content", expected_hash="wrong_hash" - ) - assert "stale edit conflict" in res_stale - - # Edit file not found - assert "file not found" in tools["edit_file"].execute( - path="missing.txt", old_text="a", new_text="b" - ) - - # Edit file old text not found - assert "target old_text not found" in tools["edit_file"].execute( - path="test.txt", old_text="nonexistent text", new_text="b" - ) - - # Edit file duplicate match - text_file.write_text("word word word") - assert "matches 3 times" in tools["edit_file"].execute( - path="test.txt", old_text="word", new_text="replacement" - ) - - # Edit file stale hash - assert "stale edit conflict" in tools["edit_file"].execute( - path="test.txt", old_text="word", new_text="replacement", expected_hash="bad_hash" - ) - - # List directory not a dir - assert "not a directory" in tools["list_directory"].execute(path="test.txt") - - # Find files not a dir - assert "not a directory" in tools["find_files"].execute(pattern="*", path="test.txt") - - -def test_macroscope_empty_and_exceptions(tmp_path: Path) -> None: - import subprocess - from unittest.mock import patch - - from devops_cli.ai.harness import Macroscope - - cap = Macroscope(base="main", cwd=tmp_path, timeout=5) - tools = cap.get_tools() - tool = tools[0] - - # Empty review - with ( - patch("shutil.which", return_value="/usr/local/bin/macroscope"), - patch("subprocess.run") as mock_run, - ): - mock_proc = MagicMock() - mock_proc.returncode = 0 - mock_proc.stdout = '{"type": "review_id", "id": "rev-999"}\n{"type": "issue_status", "status": "completed"}' - mock_run.return_value = mock_proc - - res = tool.function() # type: ignore[union-attr] - assert "0 issues found" in res - - # TimeoutExpired exception - with ( - patch("shutil.which", return_value="/usr/local/bin/macroscope"), - patch("subprocess.run", side_effect=subprocess.TimeoutExpired(cmd="macroscope", timeout=5)), - ): - res = tool.function() # type: ignore[union-attr] - assert "timed out after" in res - - # General Exception - with ( - patch("shutil.which", return_value="/usr/local/bin/macroscope"), - patch("subprocess.run", side_effect=OSError("Process failed")), - ): - res = tool.function() # type: ignore[union-attr] - assert "Macroscope review error:" in res - - -def test_tool_output_limits_and_hooks() -> None: - from devops_cli.ai.harness import ClearToolResults, ToolOutputLimits, WarnNearLimits - - # Limits capability - lim = ToolOutputLimits(max_chars=1000) - assert lim.max_chars == 1000 - - # ClearToolResults - clearer = ClearToolResults(max_fraction=0.8) - assert clearer.max_fraction == 0.8 - assert clearer.get_tools() == [] - - # WarnNearLimits - warner = WarnNearLimits(max_context_fraction=0.85) - assert warner.max_context_fraction == 0.85 - assert warner.get_tools() == [] - - -def test_planning_in_memory_store_and_events() -> None: - from devops_cli.ai.harness import ( - InMemoryPlanStore, - PlanEvent, - PlanEventEmitter, - PlanItem, - ) - - events: list[str] = [] - emitter = PlanEventEmitter() - - @emitter.on_task_added - def on_add(evt: PlanEvent) -> None: - events.append(f"added:{evt.item.content}") - - @emitter.on_status_changed - def on_status(evt: PlanEvent) -> None: - events.append(f"status:{evt.item.content}->{evt.new_status}") - - @emitter.on_completed - def on_done(evt: PlanEvent) -> None: - events.append(f"done:{evt.item.content}") - - store = InMemoryPlanStore(event_emitter=emitter) - item = store.add_item(PlanItem(content="First Task")) - assert len(store.get_items()) == 1 - - store.update_item_status(item.id, "in_progress") - store.update_item_status(item.id, "completed") - store.remove_item(item.id) - assert len(store.get_items()) == 0 - - assert "added:First Task" in events - assert "status:First Task->in_progress" in events - assert "done:First Task" in events - - -def test_planning_sqlite_store(tmp_path: Path) -> None: - from devops_cli.ai.harness import PlanItem, SqlitePlanStore - - db_path = tmp_path / "test_plan.db" - store = SqlitePlanStore(db_path=db_path, session="session-1") - - item1 = store.add_item( - PlanItem(content="Step 1", active_form="Doing Step 1", status="in_progress") - ) - item2 = store.add_item(PlanItem(content="Step 2", status="pending", depends_on=[item1.id])) - - items = store.get_items() - assert len(items) == 2 - assert items[0].content == "Step 1" - assert items[1].depends_on == [item1.id] - - store.update_item_status(item1.id, "completed") - assert store.get_items()[0].status == "completed" - - store.remove_item(item2.id) - assert len(store.get_items()) == 1 - - # Overwrite whole items list - store.set_items([PlanItem(content="Fresh Step")]) - assert len(store.get_items()) == 1 - assert store.get_items()[0].content == "Fresh Step" - - -def test_sqlite_plan_store_path_security() -> None: - """Verify SqlitePlanStore rejects directory traversal and forbidden system paths.""" - from devops_cli.ai.harness import SqlitePlanStore - from devops_cli.exceptions.security import SecurityError - - with pytest.raises(SecurityError): - SqlitePlanStore(db_path="/etc/plans.db") - - with pytest.raises(SecurityError): - SqlitePlanStore(db_path="../../../escaped_plans.db") - - with pytest.raises(SecurityError): - SqlitePlanStore(db_path="/opt/unauthorized_plans.db") - - -def test_planning_capability_tools() -> None: - from devops_cli.ai.harness import Planning - - planning = Planning() - tools = {t.name: t for t in planning.get_tools()} - - assert "write_plan" in tools - assert "read_plan" in tools - assert "add_task" in tools - assert "update_task_status" in tools - assert "update_task_statuses" in tools - assert "remove_task" in tools - assert "update_plan" in tools - - # Test write_plan and read_plan - write_res = tools["write_plan"].function([{"content": "Step 1"}, {"content": "Step 2"}]) # type: ignore[union-attr] - assert "2 steps" in write_res - - read_res = tools["read_plan"].function() # type: ignore[union-attr] - assert "Plan Progress: 0/2 completed" in read_res - - # Test add_task - add_res = tools["add_task"].function(content="Step 3", active_form="Implementing Step 3") # type: ignore[union-attr] - assert "Step 3" in add_res - - store_items = planning.resolve_store().get_items() - assert len(store_items) == 3 - t1_id = store_items[0].id - - # Test update_task_status - up_res = tools["update_task_status"].function(task_id=t1_id, status="in_progress") # type: ignore[union-attr] - assert "updated to 'in_progress'" in up_res - - invalid_st_res = tools["update_task_status"].function(task_id=t1_id, status="invalid_status") # type: ignore[union-attr] - assert "Error: invalid status" in invalid_st_res - - not_found_res = tools["update_task_status"].function(task_id="unknown-999", status="completed") # type: ignore[union-attr] - assert "not found" in not_found_res - - # Test update_task_statuses batch - batch_res = tools["update_task_statuses"].function( - updates=[{"id": t1_id, "status": "completed"}] - ) # type: ignore[union-attr] - assert "Successfully updated" in batch_res - - batch_err = tools["update_task_statuses"].function( - updates=[{"id": "unknown-id", "status": "completed"}] - ) # type: ignore[union-attr] - assert "Error: task id 'unknown-id' not found" in batch_err - - # Test remove_task - rem_res = tools["remove_task"].function(task_id=t1_id) # type: ignore[union-attr] - assert "removed from plan" in rem_res - - -def test_planning_subtasks_and_dependencies() -> None: - from devops_cli.ai.harness import Planning - - planning = Planning(enable_subtasks=True) - tools = {t.name: t for t in planning.get_tools()} - - assert "add_subtask" in tools - assert "set_dependency" in tools - assert "get_available_tasks" in tools - - tools["write_plan"].function([{"content": "Parent Task"}]) # type: ignore[union-attr] - parent_id = planning.resolve_store().get_items()[0].id - - # Add subtask - sub_res = tools["add_subtask"].function(parent_id=parent_id, content="Child Task") # type: ignore[union-attr] - assert "Child Task" in sub_res - child_id = planning.resolve_store().get_items()[1].id - - # Set dependency (child depends on parent) - dep_res = tools["set_dependency"].function(task_id=child_id, depends_on_id=parent_id) # type: ignore[union-attr] - assert "status: blocked" in dep_res - - # Self-dependency error - self_dep = tools["set_dependency"].function(task_id=child_id, depends_on_id=child_id) # type: ignore[union-attr] - assert "self-dependency not allowed" in self_dep - - # Hierarchical read - h_read = tools["read_plan"].function(view="hierarchical") # type: ignore[union-attr] - assert "Parent Task" in h_read - assert "Child Task" in h_read - - # Complete parent -> child auto unblocks - tools["update_task_status"].function(task_id=parent_id, status="completed") # type: ignore[union-attr] - assert planning.resolve_store().get_items()[1].status == "pending" - - # Get available tasks - avail = tools["get_available_tasks"].function() # type: ignore[union-attr] - assert "Child Task" in avail - - -def test_planning_hooks_and_options() -> None: - import pytest - - from devops_cli.ai.agents.context import RunContext - from devops_cli.ai.harness import InMemoryPlanStore, PlanItem, Planning - from devops_cli.models.ai import ChatMessage - - # Allowlist filtering - filtered = Planning(tools=["write_plan", "read_plan"]) - f_tool_names = [t.name for t in filtered.get_tools()] - assert f_tool_names == ["write_plan", "read_plan"] - - with pytest.raises(ValueError, match="Unknown tool"): - Planning(tools=["nonexistent_tool"]).get_tools() - - # Reject subtasks when enable_subtasks=False - plain_plan = Planning(enable_subtasks=False) - plain_tools = {t.name: t for t in plain_plan.get_tools()} - with pytest.raises(ValueError, match="require enable_subtasks=True"): - plain_tools["write_plan"].function([{"content": "Step", "status": "blocked"}]) # type: ignore[union-attr] - - # Custom store resolver - custom_store = InMemoryPlanStore() - custom_store.add_item(PlanItem(content="Custom Store Task", status="in_progress")) - resolved_plan = Planning(store_resolver=lambda ctx: custom_store) - ctx = RunContext(deps=None) - assert resolved_plan.resolve_store(ctx).get_items()[0].content == "Custom Store Task" - - # Guidance omission - assert Planning(guidance="").get_system_prompt_additions() == [] - assert len(Planning(guidance="Custom Guidance").get_system_prompt_additions()) == 1 - - # Injection hook - hook_plan = Planning(inject=True) - hook_plan.resolve_store().add_item( - PlanItem(content="Hook Task", status="in_progress", active_form="Hooking") - ) - hooks = hook_plan.get_hooks() - assert hooks is not None and len(hooks.before_model_request) == 1 - - msgs = [ChatMessage(role="user", content="Hello agent")] - hooks.before_model_request[0](ctx, msgs) - assert " None: - from devops_cli.ai.harness import ( - MINIMUM_EFFORT_FLOOR, - ModelOption, - clamp_effort, - ) - - assert clamp_effort(None) == MINIMUM_EFFORT_FLOOR - assert clamp_effort(False) == MINIMUM_EFFORT_FLOOR - assert clamp_effort(True) is True - assert clamp_effort("minimal") == "low" - assert clamp_effort("high") == "high" - assert clamp_effort("max") == "max" - - opt = ModelOption( - model="test-model", description="Reasoning model", settings={"thinking": "high"} - ) - assert opt.model == "test-model" - assert opt.description == "Reasoning model" - - -def test_subagent_run_controls_and_budget() -> None: - from devops_cli.ai.harness import SubAgent, SubAgents - - call_history: list[str] = [] - - def dummy_worker(prompt: str) -> str: - call_history.append(prompt) - if "fail" in prompt: - raise ValueError("Execution failed") - return f"Processed: {prompt}" - - sub = SubAgent( - agent=dummy_worker, - name="worker", - description="Worker subagent", - max_calls=2, - on_failure="Fallback message for failure", - contain_errors=True, - ) - - subagents = SubAgents(agents=[sub], contain_errors=True) - tools = {t.name: t for t in subagents.get_tools()} - - assert "delegate_task" in tools - assert "delegate_to_worker" in tools - - # First call succeeds - res1 = tools["delegate_task"].function(agent_name="worker", task="Task 1") # type: ignore[union-attr] - assert res1 == "Processed: Task 1" - - # Second call succeeds - res2 = tools["delegate_to_worker"].function(prompt="Task 2") # type: ignore[union-attr] - assert res2 == "Processed: Task 2" - - # Third call exhausts budget - res3 = tools["delegate_task"].function(agent_name="worker", task="Task 3") # type: ignore[union-attr] - assert "Fallback message for failure" in res3 - - # Test unknown agent - unknown_res = tools["delegate_task"].function(agent_name="unknown", task="Task") # type: ignore[union-attr] - assert "Error: unknown sub-agent 'unknown'" in unknown_res - - # Test error containment and fallback - failing_sub = SubAgent( - agent=dummy_worker, - name="failing_worker", - contain_errors=True, - ) - subagents_err = SubAgents(agents=[failing_sub]) - err_tools = {t.name: t for t in subagents_err.get_tools()} - crashed_res = err_tools["delegate_task"].function(agent_name="failing_worker", task="fail now") # type: ignore[union-attr] - assert "Sub-agent 'failing_worker' crashed" in crashed_res - - -def test_subagent_model_routing() -> None: - from devops_cli.ai.harness import ModelOption, SubAgent, SubAgents - - def mock_agent(prompt: str) -> str: - return f"OK: {prompt}" - - sub1 = SubAgent(agent=mock_agent, name="fast_bot", models=["fast"]) - sub2 = SubAgent(agent=mock_agent, name="general_bot") - - subagents = SubAgents( - agents=[sub1, sub2], - models={ - "fast": "anthropic:claude-haiku", - "deep": ModelOption(model="anthropic:claude-opus", description="deep reasoning"), - }, - ) - - tools = {t.name: t for t in subagents.get_tools()} - - # Call with allowed model - ok_res = tools["delegate_task"].function(agent_name="fast_bot", task="fast task", model="fast") # type: ignore[union-attr] - assert ok_res == "OK: fast task" - - # Call with disallowed model for pinned subagent - disallowed_res = tools["delegate_task"].function( - agent_name="fast_bot", task="fast task", model="deep" - ) # type: ignore[union-attr] - assert "Error: model 'deep' not allowed for sub-agent 'fast_bot'" in disallowed_res - - # Call with unknown model - unknown_model_res = tools["delegate_task"].function( - agent_name="general_bot", task="gen task", model="unknown_model" - ) # type: ignore[union-attr] - assert "Error: model 'unknown_model' not in model menu" in unknown_model_res - - # System prompt additions check - prompt_add = subagents.get_system_prompt_additions()[0] - assert "Available Sub-Agents for delegation:" in prompt_add - assert "fast_bot" in prompt_add - assert "Model Menu:" in prompt_add - - -def test_subagents_markdown_disk_loading(tmp_path: Path) -> None: - from devops_cli.ai.harness import SubAgents - - agent_dir = tmp_path / "agents" - agent_dir.mkdir(parents=True) - - agent_file = agent_dir / "analyst.md" - agent_file.write_text( - "---\nname: analyst\ndescription: Data Analyst Agent\ntools: read_file, run_query\n---\nYou analyze system metrics and logs.", - encoding="utf-8", - ) - - subagents = SubAgents(agent_folders=[agent_dir]) - loaded = subagents.load_disk_agents() - - assert len(loaded) == 1 - assert loaded[0].name == "analyst" - assert loaded[0].description == "Data Analyst Agent" - - tools = {t.name: t for t in subagents.get_tools()} - assert "delegate_to_analyst" in tools - - -def test_subagents_edge_cases() -> None: - from devops_cli.ai.harness import AgentOverride, SubAgent, SubAgents - - def sync_worker(prompt: str) -> str: - return f"Echo: {prompt}" - - sa = SubAgents( - agents=[SubAgent(agent=sync_worker, name="echoer")], - models={"default": "anthropic:claude-3-5-sonnet"}, - agent_folders=None, - agent_overrides={"analyst": AgentOverride(model="gpt-4o", effort="high")}, - ) - - # load_disk_agents returns empty when agent_folders is None - assert sa.load_disk_agents() == [] - - # get_system_prompt_additions when empty - empty_sa = SubAgents(agent_folders=None) - assert "No sub-agents currently registered" in empty_sa.get_system_prompt_additions()[0] - - # Tool invocation - tools = {t.name: t for t in sa.get_tools()} - res = tools["delegate_task"].function(agent_name="echoer", task="hello") # type: ignore[union-attr] - assert res == "Echo: hello" - - -def test_advisor_capability_initialization_and_validation() -> None: - import pytest - - from devops_cli.ai.harness import Advisor - - # Valid initialization - adv = Advisor("anthropic:claude-3-5-sonnet", mode="auto", max_uses=3, max_tokens=2048) - assert adv.model == "anthropic:claude-3-5-sonnet" - assert adv.max_uses == 3 - assert adv.max_tokens == 2048 - - # Validation errors - with pytest.raises(ValueError, match="max_uses must be at least 1"): - Advisor("openai:gpt-4o", max_uses=0) - - with pytest.raises(ValueError, match="max_tokens must be at least 1024"): - Advisor("openai:gpt-4o", max_tokens=500) - - with pytest.raises(ValueError, match="OpenRouter native advisor does not support max_uses"): - Advisor("openrouter:anthropic/claude-3.5-sonnet", mode="native", max_uses=2) - - with pytest.raises(ValueError, match="caching is only supported on Anthropic native advisor"): - Advisor("openai:gpt-4o", mode="native", caching="5m") - - -def test_advisor_consultation_execution_and_limits() -> None: - import asyncio - - from devops_cli.ai.harness import Advisor - - def mock_advisor_sync(prompt: str) -> str: - return f"Advice: {prompt}" - - class AsyncMockAdvisor: - async def run_async(self, prompt: str) -> str: - return f"Async advice: {prompt}" - - adv_sync = Advisor(model=mock_advisor_sync, max_uses=2) - tools = {t.name: t for t in adv_sync.get_tools()} - assert "advisor" in tools - adv_fn = tools["advisor"].function - - # First call - res1 = asyncio.run(adv_fn(prompt="How to refactor?")) # type: ignore[union-attr] - assert res1 == "Advice: How to refactor?" - - # Second call - res2 = asyncio.run(adv_fn(prompt="Check security")) # type: ignore[union-attr] - assert res2 == "Advice: Check security" - - # Third call exceeds max_uses - res3 = asyncio.run(adv_fn(prompt="Another question")) # type: ignore[union-attr] - assert "Maximum advisor consultations (2) reached" in res3 - - # Test for_run isolation - adv_fresh = adv_sync.for_run() - assert adv_fresh.current_uses == 0 - fresh_tools = {t.name: t for t in adv_fresh.get_tools()} - fresh_res = asyncio.run(fresh_tools["advisor"].function(prompt="Fresh start")) # type: ignore[union-attr] - assert fresh_res == "Advice: Fresh start" - - # Test async runner model - adv_async = Advisor(model=AsyncMockAdvisor()) - async_tool = {t.name: t for t in adv_async.get_tools()}["advisor"].function - res_async = asyncio.run(async_tool(prompt="Async check")) # type: ignore[union-attr] - assert res_async == "Async advice: Async check" - - # Test deferred prompts - adv_def = Advisor("openai:gpt-4o", defer_loading=True) - assert "Advisor [advisor]:" in adv_def.get_system_prompt_additions()[0] - - -def test_compaction_suite() -> None: - from devops_cli.ai.harness import ( - ClampOversizedMessages, - ClearToolResults, - DeduplicateFileReads, - FallbackCompaction, - ReportContextUsage, - SlidingWindowCompaction, - SummarizingCompaction, - TieredCompaction, - WarnNearLimits, - compact_now, - is_pinned, - pin, - reinject_pinned, - ) - from devops_cli.models.ai import ChatMessage - - # 1. Test pin, is_pinned, reinject_pinned - msg1 = ChatMessage(role="system", content="System instruction") - msg2 = ChatMessage(role="user", content="User prompt") - pin(msg1) - assert is_pinned(msg1) is True - assert is_pinned(msg2) is False - - reinj = reinject_pinned([msg2], [msg1]) - assert reinj[0] == msg1 - assert reinj[1] == msg2 - - # 2. Test ClampOversizedMessages - huge_msg = ChatMessage(role="user", content="A" * 30000) - clamp = ClampOversizedMessages(max_chars=1000) - clamped = clamp.compact_messages([huge_msg]) - assert len(clamped[0].content) < 2000 - assert "Truncated content:" in clamped[0].content - - # Pinned message is preserved - pin(huge_msg) - preserved = clamp.compact_messages([huge_msg]) - assert len(preserved[0].content) == 30000 - - # 3. Test ClearToolResults - tool_msg1 = ChatMessage(role="user", content="[Tool Result: grep] Output 1") - tool_msg2 = ChatMessage(role="user", content="[Tool Result: grep] Output 2") - tool_msg3 = ChatMessage(role="user", content="[Tool Result: grep] Output 3") - clear_cap = ClearToolResults(keep_pairs=1) - cleared = clear_cap.compact_messages([msg1, tool_msg1, tool_msg2, tool_msg3]) - assert "[Cleared tool result:" in cleared[1].content - assert "[Cleared tool result:" in cleared[2].content - assert cleared[3].content == "[Tool Result: grep] Output 3" - - # Also test dict-based tool results - dict_tools = [ - {"role": "tool", "content": "Out 1", "name": "grep", "tool_call_id": "c1"}, - {"role": "tool", "content": "Out 2", "name": "grep", "tool_call_id": "c2"}, - ] - cleared_dicts = clear_cap.compact_messages(dict_tools) - assert "[Cleared tool result: grep]" in cleared_dicts[0]["content"] - - # 4. Test DeduplicateFileReads - read_msg1 = { - "role": "tool", - "content": "v1 contents", - "name": "read_file", - "tool_call_id": "call_a", - } - read_msg2 = { - "role": "tool", - "content": "v2 contents", - "name": "read_file", - "tool_call_id": "call_b", - } - dedupe = DeduplicateFileReads() - deduped = dedupe.compact_messages([read_msg1, read_msg2]) - assert "[Superseded file read: read_file]" in deduped[0]["content"] - assert deduped[1]["content"] == "v2 contents" - - # 5. Test SlidingWindowCompaction - # 5. Test SlidingWindowCompaction with receipts - msgs = [ChatMessage(role="system", content="Prompt")] + [ - ChatMessage(role="user", content=f"Turn {i}") for i in range(10) - ] - sw = SlidingWindowCompaction(max_messages=3) - sw_compacted = sw.compact_messages(msgs) - assert len(sw_compacted) == 4 # System + last 3 - assert sw_compacted[0].content == "Prompt" - assert sw_compacted[-1].content == "Turn 9" - - class DummyHandleProvider: - def compaction_transcript_handle(self) -> str: - return "run-12345" - - sw_receipts = SlidingWindowCompaction( - max_messages=3, receipts=True, transcript_handle_provider=DummyHandleProvider() - ) - sw_receipts_res = sw_receipts.compact_messages(msgs) - assert "Compaction Receipt:" in sw_receipts_res[1].content - assert "handle=run-12345" in sw_receipts_res[1].content - - # 6. Test SummarizingCompaction with incremental & bridge_prefix - sum_cap = SummarizingCompaction( - keep_tail=2, - bridge_prefix=True, - receipts=True, - transcript_handle_provider=DummyHandleProvider(), - ) - sum_compacted = sum_cap.compact_messages(msgs) - assert "Compaction Receipt:" in sum_compacted[1].content - assert "Conversation Summary:" in sum_compacted[2].content - assert "Cross-model bridge:" in sum_compacted[2].content - - # Incremental update on already summarized turn - incremental_res = sum_cap.compact_messages( - sum_compacted + [ChatMessage(role="user", content="Turn 11")] - ) - assert "" in incremental_res[2].content - - # 7. Test FallbackCompaction & TieredCompaction - tiered = TieredCompaction( - tiers=[ClearToolResults(keep_pairs=1), SlidingWindowCompaction(max_messages=2)] - ) - res_tiered = tiered.compact_messages([msg1, tool_msg1, tool_msg2, tool_msg3]) - assert len(res_tiered) <= 3 - - fallback = FallbackCompaction(strategies=[tiered]) - res_fallback = fallback.compact_messages([msg1, msg2]) - assert len(res_fallback) == 2 - - # 8. Test WarnNearLimits - warn_cap = WarnNearLimits(max_context_fraction=0.85) - assert "85%" in warn_cap.get_system_prompt_additions()[0] - - # 9. Test ReportContextUsage & compact_now - reporter = ReportContextUsage() - usage = reporter.get_usage([msg1, msg2], context_limit=10000) - assert usage.message_count == 2 - assert usage.context_fraction >= 0.0 - - compacted_direct = compact_now([msg1, msg2], strategy=sw) - assert len(compacted_direct) == 2 - - -def test_tool_output_limits_suite(tmp_path: Path) -> None: - from devops_cli.ai.harness import ( - Band, - LocalFileStore, - Passthrough, - Spill, - Summarize, - ToolOutputLimits, - Truncate, - TruncationStrategy, - indented_json, - json_lines, - ) - - # 1. Test Truncation strategies - t_head = Truncate(max_chars=20, strategy=TruncationStrategy.head) - assert ( - t_head.reduce("12345678901234567890EXTRA") - == "12345678901234567890\n\n[... 5 characters truncated ...]" - ) - - t_tail = Truncate(max_chars=20, strategy=TruncationStrategy.tail) - assert ( - t_tail.reduce("EXTRA12345678901234567890") - == "[... 5 characters truncated ...]\n\n12345678901234567890" - ) - - t_head_tail = Truncate(max_chars=10, strategy=TruncationStrategy.head_tail) - assert "truncated" in t_head_tail.reduce("12345678901234567890") - - # 2. Test LocalFileStore and slicing - store = LocalFileStore(base_dir=tmp_path / "spills") - handle = store.write("sample", b"line1\nline2\nline3\nline4\nline5") - assert "spill_sample_" in handle - assert store.read(handle) == b"line1\nline2\nline3\nline4\nline5" - - slice_head = store.read_slice(handle, offset=0, limit=2) - assert slice_head == "line1\nline2" - - slice_tail = store.read_slice(handle, limit=2, from_end=True) - assert slice_tail == "line4\nline5" - - slice_filter = store.read_slice(handle, pattern="line3") - assert slice_filter == "line3" - - # Test fallback bounded capacity with simulated disk write failure - from unittest.mock import patch - - from devops_cli.ai.harness.compaction import ( - _MAX_OVERFLOW_FALLBACK_ENTRIES, - _OVERFLOW_MEMORY_FALLBACK, - ) - - with patch.object(Path, "write_bytes", side_effect=OSError("Disk full")): - first_h = store.write("first", b"data1") - assert first_h in _OVERFLOW_MEMORY_FALLBACK - for i in range(_MAX_OVERFLOW_FALLBACK_ENTRIES): - store.write(f"batch_{i}", f"payload_{i}".encode()) - assert first_h not in _OVERFLOW_MEMORY_FALLBACK - assert len(_OVERFLOW_MEMORY_FALLBACK) == _MAX_OVERFLOW_FALLBACK_ENTRIES - - # 3. Test Serializers - struct_val = {"key": "value", "count": 42} - ind_res = indented_json(struct_val) - assert '"key": "value"' in ind_res - assert "\n" in ind_res - - jl_res = json_lines([{"a": 1}, {"b": 2}]) - assert '{"a": 1}\n{"b": 2}' == jl_res - - # 4. Test ToolOutputLimits with Bands - tol = ToolOutputLimits( - bands=[ - Band(over=1000, action=Spill(store=store, then=Truncate(max_chars=50))), - Band(over=500, action=Summarize()), - Band(over=100, action=Truncate(max_chars=50)), - Band(over=50, action=Passthrough()), - ], - per_tool={"custom_tool": [Band(over=20, action=Truncate(max_chars=10))]}, - tool_filter=["test_tool", "custom_tool", "structured_tool"], - over_tokens=True, - tokenizer=lambda s: len(s) // 2, - serializer=indented_json, - strip_ansi=True, - store=store, - ) - - # Tool exemption: read_tool_result - _res_exempt, red_exempt = tol.reduce_output("read_tool_result", "X" * 5000) - assert not red_exempt - - # Tool filter: unlisted tool passes through - _res_unlisted, red_unlisted = tol.reduce_output("other_tool", "X" * 5000) - assert not red_unlisted - - # Bytes pass through - res_bytes, red_bytes = tol.reduce_output("test_tool", b"raw bytes") - assert not red_bytes - assert res_bytes == b"raw bytes" - - # Structured object with serializer - _res_struct, red_struct = tol.reduce_output("structured_tool", {"large": "data" * 100}) - assert red_struct - - # per_tool override - res_per_tool, red_per_tool = tol.reduce_output("custom_tool", "a" * 50) - assert red_per_tool - assert "truncated" in res_per_tool - - # Below 50: passthrough - res, reduced = tol.reduce_output("test_tool", "Short output") - assert not reduced - assert res == "Short output" - - # 60 chars (Passthrough band) - res_pass, red_pass = tol.reduce_output("test_tool", "X" * 120) - assert not red_pass - assert len(res_pass) == 120 - - # 200 tokens (Truncate band) - res_trunc, red_trunc = tol.reduce_output("test_tool", "T" * 300) - assert red_trunc - assert "truncated" in res_trunc - - # 600 tokens (Summarize band) - res_sum, red_sum = tol.reduce_output("test_tool", ("line\n" * 300)) - assert red_sum - assert "[Summary of test_tool" in res_sum - - # 2000 tokens (Spill band) - res_spill, red_spill = tol.reduce_output("test_tool", "S" * 3000, tool_call_id="call1") - assert red_spill - assert "[Tool output spilled:" in res_spill - assert "Handle:" in res_spill - - # Test Spill fallback when store errors - class FailingStore: - def write(self, key: str, data: bytes) -> str: - raise RuntimeError("Disk full") - - spill_fail = Spill(store=FailingStore(), then=Truncate(max_chars=20)) - res_spill_fail = spill_fail.reduce("Long text that cannot be spilled to disk") - assert "truncated" in res_spill_fail - - # Test tool registration - tools = tol.get_tools() - assert len(tools) == 1 - assert tools[0].name == "read_tool_result" - assert "line1" in tools[0].execute(handle=handle, offset=0, limit=2) - assert "Error" in tools[0].execute(handle="nonexistent_handle") - - -def test_warn_on_cache_busts_suite() -> None: - import pytest - - from devops_cli.ai.harness import CacheBustWarning, WarnOnCacheBusts - - # 1. Test validation error on zero/negative collapse_ratio - with pytest.raises(ValueError, match=re.escape("collapse_ratio must be greater than 0.0")): - WarnOnCacheBusts(collapse_ratio=0.0) - - # 2. Test normal operation and warnings - monitor = WarnOnCacheBusts( - collapse_ratio=0.5, - min_prefix_tokens=1000, - cache_ttl_seconds=300.0, - ) - - # First request establishes prefix of 2000 tokens (read=0, write=2000) - w1 = monitor.record_request( - "anthropic", - "claude-3-5-sonnet", - cache_read_tokens=0, - cache_write_tokens=2000, - now=100.0, - ) - assert w1 is None - mark = monitor.marks[("anthropic", "claude-3-5-sonnet")] - assert mark.established_prefix == 2000 - - # Second request hits cache with 2000 tokens -> healthy - w2 = monitor.record_request( - "anthropic", - "claude-3-5-sonnet", - cache_read_tokens=2000, - cache_write_tokens=500, - now=110.0, - ) - assert w2 is None - assert mark.established_prefix == 2500 - - # Third request collapses cache to 500 tokens (< 0.5 * 2500) -> emits warning - with pytest.warns( - CacheBustWarning, match="Prompt cache collapsed for anthropic:claude-3-5-sonnet" - ): - w3 = monitor.record_request( - "anthropic", - "claude-3-5-sonnet", - cache_read_tokens=500, - cache_write_tokens=100, - now=120.0, - ) - assert w3 is not None - assert "read 500 cached tokens" in w3 - - # Fourth request in sustained collapse -> stays latched and silent - w4 = monitor.record_request( - "anthropic", - "claude-3-5-sonnet", - cache_read_tokens=400, - cache_write_tokens=0, - now=130.0, - ) - assert w4 is None - - # Fifth request with cache expiry gap (> 300s) - mark.latched_warning = False - with pytest.warns(CacheBustWarning, match="exceeds assumed cache TTL"): - w5 = monitor.record_request( - "anthropic", - "claude-3-5-sonnet", - cache_read_tokens=100, - cache_write_tokens=0, - now=500.0, - ) - assert w5 is not None - assert "exceeds assumed cache TTL" in w5 - - # 3. Test for_run produces isolated instance - run_monitor = monitor.for_run() - assert run_monitor.marks == {} - assert run_monitor.collapse_ratio == monitor.collapse_ratio - - # 4. Test after_model_request hook integration - class DummyUsage: - cache_read_tokens = 2000 - cache_write_tokens = 500 - - class DummyResponse: - usage = DummyUsage() - - class DummyContext: - provider_name = "anthropic" - model_name = "claude-3-5-sonnet" - - resp = run_monitor.after_model_request(request_context=DummyContext(), response=DummyResponse()) - assert resp is not None - assert ("anthropic", "claude-3-5-sonnet") in run_monitor.marks - - -def test_harness_memory_suite(tmp_path: Path) -> None: - """Comprehensive test suite for Pydantic AI Harness Memory capability and stores.""" - import pytest - - from devops_cli.ai.harness import ( - FileStore, - InMemoryStore, - Memory, - MemoryOperationConflictError, - SqliteMemoryStore, - ) - - # 1. Test InMemoryStore - mem_store = InMemoryStore() - w_res = mem_store.write("notes/test.md", "Initial content", mode="append") - assert w_res.status == "ok" - assert w_res.path == "notes/test.md" - - f = mem_store.read("notes/test.md") - assert f.content == "Initial content" - assert f.version == w_res.version - - # Idempotent write with operation_id - w_res2 = mem_store.write("notes/test.md", "Appended", operation_id="op-1") - assert w_res2.status == "ok" - w_res3 = mem_store.write("notes/test.md", "Should not append again", operation_id="op-1") - assert w_res3.status == "idempotent_replay" - - # Replace fragment - mem_store.write( - "notes/test.md", "", mode="replace", target_fragment="Initial", replacement="Updated" - ) - f_rep = mem_store.read("notes/test.md") - assert "Updated content" in f_rep.content - - # Target fragment not found - with pytest.raises(ValueError, match="Target fragment not found"): - mem_store.write( - "notes/test.md", - "", - mode="replace", - target_fragment="NonexistentFragment", - replacement="X", - ) - - # Version conflict - with pytest.raises(MemoryOperationConflictError, match="Version mismatch"): - mem_store.write("notes/test.md", "New", expected_version="invalid-version") - - # Search in InMemoryStore - matches = mem_store.search("Updated") - assert len(matches) == 1 - assert matches[0].path == "notes/test.md" - assert "Updated" in matches[0].snippet - - # List and delete - assert mem_store.list_paths() == ["notes/test.md"] - assert mem_store.delete("notes/test.md") is True - assert mem_store.delete("notes/nonexistent.md") is False - assert mem_store.read("notes/test.md").content == "" - assert mem_store.search("") == [] - - # Truncated read on InMemoryStore - mem_store.write("large.txt", "a" * 100) - assert mem_store.read("large.txt", max_chars=10).truncated is True - assert len(mem_store.read("large.txt", max_chars=10).content) == 10 - - # 2. Test FileStore - fstore_dir = tmp_path / "memory_fs" - file_store = FileStore(fstore_dir) - fw = file_store.write("MEMORY.md", "# Agent Notebook\nKey architectural facts.") - assert fw.status == "ok" - rf = file_store.read("MEMORY.md") - assert "Key architectural facts" in rf.content - - # FileStore replace fragment and whole replace - file_store.write( - "MEMORY.md", "", mode="replace", target_fragment="facts", replacement="principles" - ) - assert "principles" in file_store.read("MEMORY.md").content - file_store.write("doc.md", "Complete content", mode="replace") - assert file_store.read("doc.md").content == "Complete content" - - # FileStore error branches - with pytest.raises(ValueError, match="Target fragment not found"): - file_store.write("doc.md", "", mode="replace", target_fragment="missing", replacement="x") - with pytest.raises(MemoryOperationConflictError, match="Version mismatch"): - file_store.write("doc.md", "conflict", expected_version="invalid-version") - with pytest.raises(MemoryOperationConflictError, match="Version mismatch on delete"): - file_store.delete("doc.md", expected_version="wrong-version") - - # Search FileStore - fmatches = file_store.search("principles") - assert len(fmatches) == 1 - assert fmatches[0].path == "MEMORY.md" - assert file_store.search("") == [] - assert file_store.delete("doc.md") is True - assert file_store.delete("missing.md") is False - - # Path traversal protection - with pytest.raises(PermissionError, match="Path traversal"): - file_store.read("../outside.md") - - # 3. Test SqliteMemoryStore - db_path = str(tmp_path / "agent_memory.db") - sql_store = SqliteMemoryStore(database=db_path) - sw = sql_store.write("topics/cloud.md", "GCP and AWS clusters") - assert sw.status == "ok" - s_read = sql_store.read("topics/cloud.md") - assert s_read.content == "GCP and AWS clusters" - - # SqliteMemoryStore replace fragment and whole replace - sql_store.write( - "topics/cloud.md", "", mode="replace", target_fragment="AWS", replacement="Azure" - ) - assert "Azure" in sql_store.read("topics/cloud.md").content - sql_store.write("topics/cloud.md", "Replaced entirely", mode="replace") - assert sql_store.read("topics/cloud.md").content == "Replaced entirely" - - # Sqlite error branches - with pytest.raises(ValueError, match="Target fragment not found"): - sql_store.write( - "topics/cloud.md", "", mode="replace", target_fragment="missing_tag", replacement="x" - ) - with pytest.raises(MemoryOperationConflictError, match="Version mismatch"): - sql_store.write("topics/cloud.md", "conflict", expected_version="invalid-version") - with pytest.raises(MemoryOperationConflictError, match="Version mismatch on delete"): - sql_store.delete("topics/cloud.md", expected_version="wrong-version") - - # Sqlite truncated read and empty search - sql_store.write("topics/big.md", "x" * 200) - assert sql_store.read("topics/big.md", max_chars=20).truncated is True - assert sql_store.read("topics/nonexistent.md").content == "" - assert sql_store.search("") == [] - - s_search = sql_store.search("Replaced", max_results=1) - assert len(s_search) == 1 - assert s_search[0].path == "topics/cloud.md" - - # Search with limit respects bounds and caps large max_results - bounded_search = sql_store.search("topics", max_results=1) - assert len(bounded_search) <= 1 - large_search = sql_store.search("topics", max_results=1_000_000) - assert isinstance(large_search, list) - - assert sql_store.list_paths(prefix="topics") == ["topics/big.md", "topics/cloud.md"] - assert sql_store.delete("topics/cloud.md") is True - assert sql_store.delete("topics/nonexistent.md") is False - - # 4. Test Memory Capability & Tools - cap = Memory(store=file_store, heading="Agent Memory") - tools = {t.name: t for t in cap.get_tools()} - assert set(tools.keys()) == {"write_memory", "read_memory", "delete_memory", "search_memory"} - - # Tool invocation: write - wr_msg = tools["write_memory"].function(path="MEMORY.md", content="Added deployment notes") # type: ignore[union-attr] - assert "Memory updated" in wr_msg - - # Tool invocation: read - rd_msg = tools["read_memory"].function(path="MEMORY.md") # type: ignore[union-attr] - assert "Added deployment notes" in rd_msg - - # Tool invocation: search - sr_msg = tools["search_memory"].function(query="deployment") # type: ignore[union-attr] - assert "MEMORY.md" in sr_msg - no_sr_msg = tools["search_memory"].function(query="nonexistent_needle_123") # type: ignore[union-attr] - assert "No memory entries matching" in no_sr_msg - - # Tool invocation: delete protection on MEMORY.md - del_msg = tools["delete_memory"].function(path="MEMORY.md") # type: ignore[union-attr] - assert "Cannot delete protected root notebook" in del_msg - - # System prompt injection - prompts = cap.get_system_prompt_additions() - assert len(prompts) == 2 - assert "## Agent Memory" in prompts[0] - assert "" in prompts[1] - assert "Added deployment notes" in prompts[1] - - # Store resolver & error handling in get_system_prompt_additions - class DummyCtx: - pass - - def broken_resolver(c: Any) -> Any: - raise RuntimeError("Resolver exploded") - - err_cap = Memory(store_resolver=broken_resolver, injection_errors="raise") - with pytest.raises(RuntimeError, match="Resolver exploded"): - err_cap.get_system_prompt_additions(ctx=DummyCtx()) # type: ignore[arg-type] - - # Prefix tools - prefixed_cap = cap.prefix_tools("org") - p_tools = {t.name: t for t in prefixed_cap.get_tools()} - assert "org_write_memory" in p_tools - assert "org_read_memory" in p_tools - - -def _refuses_database(**fields: Any) -> bool: - from pydantic import ValidationError - - from devops_cli.ai.harness import SqliteMemoryStore - - try: - SqliteMemoryStore(**fields) - except ValidationError: - return True - return False - - -def test_sqlite_memory_store_requires_a_database_file_every_call_shares(tmp_path: Path) -> None: - """A store opens a connection per call, so a per-connection database is refused (#958). - - The default `:memory:` gave every call a new empty database: a write reported `ok` and the - next read returned nothing. The empty name does the same with a temporary file. - """ - from devops_cli.ai.harness import SqliteMemoryStore - - db_file = tmp_path / "memory.db" - written = SqliteMemoryStore(database=db_file).write("MEMORY.md", "remember this") - reader = SqliteMemoryStore(database=str(db_file)) - - assert ( - _refuses_database(), - _refuses_database(database=":memory:"), - _refuses_database(database=""), - _refuses_database(database=Path(":memory:")), - written.status, - reader.read("MEMORY.md").content, - reader.list_paths(), - [match.path for match in reader.search("remember")], - ) == (True, True, True, True, "ok", "remember this", ["MEMORY.md"], ["MEMORY.md"]) - - -def test_conversation_search_suite() -> None: - """Comprehensive test suite for ConversationSearch capability and BM25 ranking.""" - import pytest - - from devops_cli.ai.harness import ( - ConversationSearch, - HarnessDeprecationWarning, - RunRecord, - SnapshotHistorySource, - bm25_rank, - ) - from devops_cli.models.ai import ChatMessage - - # 1. Test BM25 rank algorithm - docs = [ - { - "run_id": "run-1", - "conversation_id": "conv-1", - "role": "user", - "content": "How do I configure AWS EKS cluster with OpenTofu?", - "turn_index": 0, - }, - { - "run_id": "run-1", - "conversation_id": "conv-1", - "role": "assistant", - "content": "To configure AWS EKS with OpenTofu, define the VPC and eks cluster modules.", - "turn_index": 1, - }, - { - "run_id": "run-2", - "conversation_id": "conv-2", - "role": "user", - "content": "Deploy ArgoCD on GCP GKE cluster.", - "turn_index": 0, - }, - { - "run_id": "run-2", - "conversation_id": "conv-2", - "role": "assistant", - "content": "Use devops k8s deploy-stack --stack argocd on GKE.", - "turn_index": 1, - }, - ] - - # Empty query or docs - assert bm25_rank("", docs) == [] - assert bm25_rank("test", []) == [] - - # Search OpenTofu - m_tofu = bm25_rank("OpenTofu", docs) - assert len(m_tofu) == 2 - assert m_tofu[0].run_id == "run-1" - assert "OpenTofu" in m_tofu[0].content - - # Search ArgoCD - m_argo = bm25_rank("ArgoCD GKE", docs) - assert len(m_argo) >= 1 - assert m_argo[0].run_id == "run-2" - assert "ArgoCD" in m_argo[0].content - - # 2. Test SnapshotHistorySource - source = SnapshotHistorySource() - r1 = source.record_run( - run_id="run-1", - conversation_id="conv-1", - messages=[ - ChatMessage(role="user", content="Deploy OpenTelemetry collector"), - ChatMessage(role="assistant", content="Deployed OTEL collector to otel namespace"), - ], - ) - assert r1.run_id == "run-1" - assert len(source.get_runs(conversation_id="conv-1")) == 1 - assert len(source.get_runs(conversation_id="conv-nonexistent")) == 0 - assert len(source.get_runs(run_id="run-1")) == 1 - - # External store delegation - class DummyStoreWithRuns: - def get_runs( - self, conversation_id: str | None = None, run_id: str | None = None - ) -> list[RunRecord]: - return [ - RunRecord( - run_id="delegated-run", - conversation_id="conv-del", - messages=[ChatMessage(role="user", content="Delegated")], - ) - ] - - del_source = SnapshotHistorySource(store=DummyStoreWithRuns()) - assert len(del_source.get_runs()) == 1 - assert del_source.get_runs()[0].run_id == "delegated-run" - - # 3. Test ConversationSearch Capability - # Deprecation warning on unset scope - with pytest.warns(HarnessDeprecationWarning, match="was unset"): - search_cap_warn = ConversationSearch(source=source) - assert search_cap_warn.effective_scope == "conversation" - - search_cap = ConversationSearch(source=source, scope="conversation") - assert search_cap.effective_scope == "conversation" - - # System prompt additions - prompts = search_cap.get_system_prompt_additions() - assert len(prompts) == 1 - assert "search_conversation_history" in prompts[0] - - no_inst_cap = ConversationSearch(source=source, scope="all", add_instructions=False) - assert no_inst_cap.get_system_prompt_additions() == [] - - # 4. Test search_conversation_history tool - tools = {t.name: t for t in search_cap.get_tools()} - assert "search_conversation_history" in tools - - # Tool invocation: match found - res = tools["search_conversation_history"].function( - query="OpenTelemetry", conversation_id="conv-1" - ) # type: ignore[union-attr] - assert "Found 1 historical match" in res - assert "run: run-1" in res - - # Tool invocation: no match - no_res = tools["search_conversation_history"].function( - query="nonexistent_concept_xyz", conversation_id="conv-1" - ) # type: ignore[union-attr] - assert "No matching conversation turns" in no_res - - # Tool invocation: empty history - empty_source_cap = ConversationSearch(source=SnapshotHistorySource(), scope="conversation") - empty_tools = {t.name: t for t in empty_source_cap.get_tools()} - empty_res = empty_tools["search_conversation_history"].function( - query="test", conversation_id="conv-empty" - ) # type: ignore[union-attr] - assert "No persisted conversation history found" in empty_res - - -def test_skills_harness_suite(tmp_path: Path) -> None: - """Comprehensive test suite for Skills capability loading Agent Skill packages.""" - import pytest - - from devops_cli.ai.harness import ( - Skills, - normalize_skill_name, - ) - - # 1. Name normalization and validation - assert normalize_skill_name("Code-Review") == "code-review" - assert normalize_skill_name(" release-notes ") == "release-notes" - with pytest.raises(ValueError, match="Invalid skill name"): - normalize_skill_name("-invalid-start") - with pytest.raises(ValueError, match="Invalid skill name"): - normalize_skill_name("invalid-end-") - with pytest.raises(ValueError, match="Invalid skill name"): - normalize_skill_name("x" * 70) - - # 2. Setup mock skill directories - lib_dir = tmp_path / "skills" - lib_dir.mkdir() - - # Skill 1: code-review - s1_dir = lib_dir / "code-review" - s1_dir.mkdir() - (s1_dir / "SKILL.md").write_text( - "---\nname: code-review\ndescription: Review pull requests for security and standards.\n---\n\nAnalyze diffs carefully.", - encoding="utf-8", - ) - - # Skill 2: release-mgmt - s2_dir = lib_dir / "release-mgmt" - s2_dir.mkdir() - (s2_dir / "SKILL.md").write_text( - "---\ndescription: Manage release workflows and semantic versions.\n---\n\nFollow Conventional Commits standard.", - encoding="utf-8", - ) - - # Skill 3: with unsupported behavioral fields - s3_dir = lib_dir / "deploy-stack" - s3_dir.mkdir() - (s3_dir / "SKILL.md").write_text( - "---\nname: deploy-stack\ndescription: Deploy Kubernetes stack.\nmodel: claude-3-5-sonnet\n---\n\nRun helm upgrade.", - encoding="utf-8", - ) - - # 3. Validation on construction errors - with pytest.raises(ValueError, match="cannot specify both 'include' and 'exclude'"): - Skills(lib_dir, include=["code-review"], exclude=["release-mgmt"]) - - with pytest.raises(ValueError, match="does not exist or is not a directory"): - Skills(tmp_path / "nonexistent_dir") - - # 4. Construct Skills with behavioral field warning - with pytest.warns(UserWarning, match="unsupported behavioral frontmatter fields"): - skills_cap = Skills(lib_dir) - - assert len(skills_cap.skills) == 3 - assert "code-review" in skills_cap.skills - assert "release-mgmt" in skills_cap.skills - assert "deploy-stack" in skills_cap.skills - assert "Skills(directories=" in repr(skills_cap) - - # Apply visitor - visited_names: list[str] = [] - skills_cap.apply(lambda s: visited_names.append(s.name)) - assert set(visited_names) == {"code-review", "release-mgmt", "deploy-stack"} - - # 5. Include filter - inc_cap = Skills(lib_dir, include=["code-review"]) - assert len(inc_cap.skills) == 1 - assert "code-review" in inc_cap.skills - assert "include=" in repr(inc_cap) - - with pytest.raises(ValueError, match=r"Unknown skill.*specified in 'include'"): - Skills(lib_dir, include=["unknown-skill"]) - - # 6. Exclude filter - exc_cap = Skills(lib_dir, exclude=["deploy-stack"]) - assert len(exc_cap.skills) == 2 - assert "deploy-stack" not in exc_cap.skills - assert "exclude=" in repr(exc_cap) - - # 7. System prompt additions (initial catalog) - init_prompts = skills_cap.get_system_prompt_additions() - assert len(init_prompts) == 1 - assert "Available specialized skills" in init_prompts[0] - assert "code-review" in init_prompts[0] - - # 8. Tools execution - tools = {t.name: t for t in skills_cap.get_tools()} - assert "load_capability" in tools - assert "list_skills" in tools - - list_out = tools["list_skills"].function() # type: ignore[union-attr] - assert "[AVAILABLE] **code-review**" in list_out - - # Load skill - load_res = tools["load_capability"].function(name="code-review") # type: ignore[union-attr] - assert "# Skill: code-review" in load_res - assert "Analyze diffs carefully." in load_res - - # System prompt additions after loading skill - loaded_prompts = skills_cap.get_system_prompt_additions() - assert len(loaded_prompts) == 2 - assert "# Skill: code-review" in loaded_prompts[1] - - # Load unknown skill - err_load = tools["load_capability"].function(name="ghost-skill") # type: ignore[union-attr] - assert "Error: Skill 'ghost-skill' not found" in err_load - - # 9. Additional edge cases: malformed frontmatter, mismatch, missing description, long description, duplicate - bad_fm_dir = tmp_path / "bad_fm" - bad_fm_dir.mkdir() - bad_s_dir = bad_fm_dir / "bad-skill" - bad_s_dir.mkdir() - (bad_s_dir / "SKILL.md").write_text("---\n: malformed: yaml\n---\nBody", encoding="utf-8") - with pytest.raises(ValueError, match="Malformed YAML frontmatter"): - Skills(bad_fm_dir) - - mismatch_dir = tmp_path / "mismatch" - mismatch_dir.mkdir() - mis_s_dir = mismatch_dir / "actual-name" - mis_s_dir.mkdir() - (mis_s_dir / "SKILL.md").write_text( - "---\nname: different-name\ndescription: test\n---\nBody", encoding="utf-8" - ) - with pytest.raises(ValueError, match="does not match directory"): - Skills(mismatch_dir) - - nodesc_dir = tmp_path / "nodesc" - nodesc_dir.mkdir() - nd_s_dir = nodesc_dir / "nodesc-skill" - nd_s_dir.mkdir() - (nd_s_dir / "SKILL.md").write_text("---\nname: nodesc-skill\n---\nBody", encoding="utf-8") - with pytest.raises(ValueError, match="missing required 'description'"): - Skills(nodesc_dir) - - longdesc_dir = tmp_path / "longdesc" - longdesc_dir.mkdir() - ld_s_dir = longdesc_dir / "long-skill" - ld_s_dir.mkdir() - (ld_s_dir / "SKILL.md").write_text( - f"---\ndescription: {'x' * 1050}\n---\nBody", encoding="utf-8" - ) - with pytest.warns(UserWarning, match="exceeds 1024 character limit"): - Skills(longdesc_dir) - - lib2_dir = tmp_path / "skills2" - lib2_dir.mkdir() - s2_dup = lib2_dir / "code-review" - s2_dup.mkdir() - (s2_dup / "SKILL.md").write_text("---\ndescription: duplicate\n---\nBody", encoding="utf-8") - with pytest.raises(ValueError, match="Duplicate skill name"): - Skills([lib_dir, lib2_dir]) - - empty_lib = tmp_path / "empty_lib" - empty_lib.mkdir() - empty_cap = Skills(empty_lib) - empty_tools = {t.name: t for t in empty_cap.get_tools()} - assert empty_tools["list_skills"].function() == "No skills configured." - assert empty_cap.get_system_prompt_additions() == [] - - -def test_repo_context_suite(tmp_path: Path) -> None: - """Comprehensive test suite for RepoContext capability across all 3 strategies.""" - from devops_cli.ai.harness import ( - AgentContextInventory, - RepoContext, - ) - - # 1. Setup nested directory hierarchy - repo_root = tmp_path / "my_project" - repo_root.mkdir() - (repo_root / "AGENTS.md").write_text( - "# Project Agent Guidelines\nUse strict typing.", encoding="utf-8" - ) - - src_dir = repo_root / "src" - src_dir.mkdir() - pkg_dir = src_dir / "services" - pkg_dir.mkdir(parents=True) - (pkg_dir / "CLAUDE.md").write_text( - "# Service Specific Rules\nUse async pipelines.", encoding="utf-8" - ) - - # 2. Strategy 1: Walk-up instruction autoload (ancestor-first) - ctx = RepoContext(workspace_dir=pkg_dir, home_dir=repo_root, autoload_instructions=True) - prompts = ctx.get_system_prompt_additions() - assert len(prompts) >= 2 - # Ancestor prompt comes first - assert "Project Agent Guidelines" in prompts[0] - # Specific package prompt comes next - assert "Service Specific Rules" in prompts[1] - - # No home_dir provided (only workspace_dir is scanned) - local_only_ctx = RepoContext(workspace_dir=pkg_dir, home_dir=None) - local_prompts = local_only_ctx.get_system_prompt_additions() - assert len(local_prompts) >= 1 - assert "Service Specific Rules" in local_prompts[0] - assert "Project Agent Guidelines" not in " ".join(local_prompts) - - # 3. Strategy 2: Asset inventory - # Setup .agents, .claude, .codex - agents_dir = repo_root / ".agents" - (agents_dir / "skills" / "k8s-deploy").mkdir(parents=True) - (agents_dir / "skills" / "k8s-deploy" / "SKILL.md").write_text( - "---\nname: k8s-deploy\ndescription: Deploy k8s stack\n---\nBody", encoding="utf-8" - ) - - claude_dir = repo_root / ".claude" - (claude_dir / "agents").mkdir(parents=True) - (claude_dir / "agents" / "security-auditor.md").write_text( - "# Security Auditor", encoding="utf-8" - ) - - codex_dir = repo_root / ".codex" - codex_dir.mkdir() - (codex_dir / "settings.json").write_text( - '{"lint_hook": "ruff", "test_hook": "pytest"}', encoding="utf-8" - ) - - inv_ctx = RepoContext(workspace_dir=repo_root, expose_inventory_tool=True) - inv: AgentContextInventory = inv_ctx.inventory() - assert inv.workspace_dir == repo_root - assert inv.roots[".agents"].exists is True - assert inv.roots[".agents"].skills == ["k8s-deploy"] - assert inv.roots[".claude"].exists is True - assert inv.roots[".claude"].agents == ["security-auditor"] - assert inv.roots[".codex"].exists is True - assert set(inv.roots[".codex"].hooks) == {"lint_hook", "test_hook"} - assert inv.roots[".grok"].exists is False - - # Tool invocation - tools = {t.name: t for t in inv_ctx.get_tools()} - assert "inventory_agent_context" in tools - report = tools["inventory_agent_context"].function() # type: ignore[union-attr] - assert "Repository Context Inventory" in report - assert ".agents" in report - assert "k8s-deploy" in report - assert "security-auditor" in report - - # 4. Strategy 3: Nested-on-traversal - trav_ctx = RepoContext( - workspace_dir=repo_root, - nested_traversal=True, - nested_inject="pointer", - traversal_tool_names=frozenset({"list_directory", "read_file"}), - ) - - # First access to pkg_dir surfaces CLAUDE.md pointer - t_res1 = trav_ctx.after_tool_execute( - "list_directory", {"path": str(pkg_dir)}, "items: [app.py]" - ) - assert "[RepoContext: Note that CLAUDE.md is present in services/]" in t_res1 - - # Second access is deduplicated (only surfaced once per run) - t_res2 = trav_ctx.after_tool_execute( - "list_directory", {"path": str(pkg_dir)}, "items: [app.py]" - ) - assert t_res2 == "items: [app.py]" - - # Test nested_inject="contents" - content_trav_ctx = RepoContext( - workspace_dir=repo_root, - nested_traversal=True, - nested_inject="contents", - ) - c_res = content_trav_ctx.after_tool_execute( - "read_file", {"path": str(pkg_dir / "app.py")}, "print('hello')" - ) - assert "# Context from CLAUDE.md:" in c_res - assert "Use async pipelines." in c_res - - # Ignored tools or non-traversal - no_trav_ctx = RepoContext(workspace_dir=repo_root, nested_traversal=False) - assert ( - no_trav_ctx.after_tool_execute("list_directory", {"path": str(pkg_dir)}, "plain") == "plain" - ) - - # for_run creates fresh isolated instance - fresh_ctx = trav_ctx.for_run() - assert len(fresh_ctx.surfaced_directories) == 0 - - -def test_pydantic_ai_docs_suite(tmp_path: Path) -> None: - """Comprehensive test suite for PydanticAIDocs capability and resolution order.""" - import os - from unittest.mock import MagicMock, patch - - from devops_cli.ai.harness import ( - DEFAULT_PYAI_DOCS_TOPICS, - PyaiDocs, - PydanticAIDocs, - ) - - # 1. Alias check - assert PyaiDocs is PydanticAIDocs - assert "capabilities" in DEFAULT_PYAI_DOCS_TOPICS - - # 2. Local checkout resolution - docs_dir = tmp_path / "pyai_docs" - docs_dir.mkdir() - (docs_dir / "capabilities.md").write_text( - "# Capabilities Guide\nHow to build capabilities.", encoding="utf-8" - ) - - cap = PydanticAIDocs(local_docs_path=docs_dir, cache=True) - assert cap.read_doc("capabilities") == "# Capabilities Guide\nHow to build capabilities." - assert cap.read_doc("capabilities.md") == "# Capabilities Guide\nHow to build capabilities." - - # Caching check: modify file, cached value persists - (docs_dir / "capabilities.md").write_text("# Changed Content", encoding="utf-8") - assert cap.read_doc("capabilities") == "# Capabilities Guide\nHow to build capabilities." - - # Non-cached instance reads new content - no_cache_cap = PydanticAIDocs(local_docs_path=docs_dir, cache=False) - assert no_cache_cap.read_doc("capabilities") == "# Changed Content" - - # 3. System prompt instructions - prompts = cap.get_system_prompt_additions() - assert len(prompts) == 1 - assert "read_pyai_docs" in prompts[0] - - # 4. Tool execution - tools = {t.name: t for t in cap.get_tools()} - assert "read_pyai_docs" in tools - tool_res = tools["read_pyai_docs"].function(topic="capabilities") # type: ignore[union-attr] - assert "# Capabilities Guide" in tool_res - - # 5. Remote fetch fallback - mock_client = MagicMock() - mock_resp = MagicMock(status_code=200, text="# Remote Hooks Guide") - mock_client.get.return_value = mock_resp - mock_client.__enter__.return_value = mock_client - mock_client.__exit__.return_value = None - - with patch("devops_cli.http.client.new_http_client", return_value=mock_client): - remote_cap = PydanticAIDocs(local_docs_path=tmp_path / "empty_docs", cache=True) - assert remote_cap.read_doc("hooks") == "# Remote Hooks Guide" - - # 6. Unresolvable topic error - err_resp = MagicMock(status_code=404, text="") - mock_client.get.return_value = err_resp - with patch("devops_cli.http.client.new_http_client", return_value=mock_client): - err_res = remote_cap.read_doc("nonexistent_topic_xyz") - assert "Could not resolve Pydantic AI documentation topic" in err_res - - # 7. Environment variable fallback - with patch.dict(os.environ, {"PYDANTIC_AI_HARNESS_DOCS_PATH": str(docs_dir)}): - env_cap = PydanticAIDocs() - assert env_cap.read_doc("capabilities") == "# Changed Content" - - -def test_harness_additional_coverage_suite(tmp_path: Path) -> None: - """Targeted tests covering FileSystem metadata, Shell background execution, Plan events, and edge cases.""" - from devops_cli.ai.harness import ( - FileSystem, - InMemoryPlanStore, - PlanEvent, - PlanEventEmitter, - PlanItem, - RepoContext, - Shell, - SqlitePlanStore, - ) - - # 1. FileSystem create_directory and file_info - fs = FileSystem(root=tmp_path, max_search_results=2) - fs_tools = {t.name: t for t in fs.get_tools()} - - # create_directory - res_mkdir = fs_tools["create_directory"].function(path="sub/nested/dir") # type: ignore[union-attr] - assert "successfully created" in res_mkdir - assert (tmp_path / "sub/nested/dir").is_dir() - - # file_info on dir, file, and nonexistent - dir_info = fs_tools["file_info"].function(path="sub/nested") # type: ignore[union-attr] - assert "Type: directory" in dir_info - - sample_f = tmp_path / "sample.txt" - sample_f.write_text("line1\nline2\nline3\n", encoding="utf-8") - file_info_res = fs_tools["file_info"].function(path="sample.txt") # type: ignore[union-attr] - assert "Type: regular file" in file_info_res - assert "Lines: 3" in file_info_res - - missing_info = fs_tools["file_info"].function(path="ghost.txt") # type: ignore[union-attr] - assert "does not exist" in missing_info - - # Search with max_search_results truncation - for i in range(5): - (tmp_path / f"test_{i}.py").write_text("match_keyword = True\n", encoding="utf-8") - search_res = fs_tools["search_files"].function(query="match_keyword") # type: ignore[union-attr] - assert "truncated at 2 results" in search_res - - # 2. Shell start_command, check_command, stop_command - shell = Shell(cwd=tmp_path, allowed_commands=["python", "sleep", "echo"]) - sh_tools = {t.name: t for t in shell.get_tools()} - - start_res = sh_tools["start_command"].function( - command='python -c "import time; time.sleep(0.5)"' - ) # type: ignore[union-attr] - assert "Background command started with ID:" in start_res - cmd_id = start_res.split(":")[-1].strip() - - check_res = sh_tools["check_command"].function(command_id=cmd_id) # type: ignore[union-attr] - assert "status:" in check_res - - stop_res = sh_tools["stop_command"].function(command_id=cmd_id) # type: ignore[union-attr] - assert "stopped" in stop_res.lower() or "terminated" in stop_res.lower() - - # Ghost command checks - assert "not found" in sh_tools["check_command"].function(command_id="ghost_cmd_id") # type: ignore[union-attr] - assert "not found" in sh_tools["stop_command"].function(command_id="ghost_cmd_id") # type: ignore[union-attr] - - # Command timeout - quick_shell = Shell(cwd=tmp_path, allowed_commands=["python"], timeout=0.05) - q_tools = {t.name: t for t in quick_shell.get_tools()} - tout_res = q_tools["run_command"].function(command='python -c "import time; time.sleep(0.3)"') # type: ignore[union-attr] - assert "timed out" in tout_res - - # 3. PlanEventEmitter & InMemoryPlanStore & SqlitePlanStore - events_received: list[PlanEvent] = [] - emitter = PlanEventEmitter() - emitter.on_task_added(lambda ev: events_received.append(ev)) - emitter.on_status_changed(lambda ev: events_received.append(ev)) - emitter.on_completed(lambda ev: events_received.append(ev)) - - store = InMemoryPlanStore(event_emitter=emitter) - item1 = store.add_item(PlanItem(content="Initial task")) - assert len(events_received) == 1 - assert events_received[0].event_type == "task_added" - - store.update_item_status(item1.id, "in_progress") - assert len(events_received) == 2 - assert events_received[1].event_type == "status_changed" - - store.update_item_status(item1.id, "completed") - assert len(events_received) == 3 - assert events_received[2].event_type == "completed" - - assert store.remove_item(item1.id) is True - assert store.remove_item("nonexistent") is False - - # SqlitePlanStore - db_file = tmp_path / "test_plan.db" - sql_store = SqlitePlanStore(db_path=db_file, session="sess1", event_emitter=emitter) - sql_item = sql_store.add_item(PlanItem(content="SQL task")) - assert sql_store.get_items()[0].content == "SQL task" - sql_store.update_item_status(sql_item.id, "completed") - assert sql_store.get_items()[0].status == "completed" - assert sql_store.remove_item(sql_item.id) is True - - # 4. RepoContext edge cases: subfolder agent directory and malformed settings - ce_repo = tmp_path / "ce_repo" - ce_repo.mkdir() - agents_dir = ce_repo / ".agents" / "agents" / "custom_agent" - agents_dir.mkdir(parents=True) - (agents_dir / "AGENT.md").write_text("# Subfolder Agent", encoding="utf-8") - - (ce_repo / ".claude").mkdir(parents=True) - (ce_repo / ".claude" / "settings.json").write_text("{invalid json", encoding="utf-8") - - ce_ctx = RepoContext(workspace_dir=ce_repo) - inv = ce_ctx.inventory() - assert "custom_agent" in inv.roots[".agents"].agents - - # 5. Shell edge cases - sh_edge = Shell(cwd=tmp_path, denied_operators=[";", "&&"], timeout=1.0) - sh_tools = {t.name: t for t in sh_edge.get_tools()} - assert "Error: empty command" in sh_tools["run_command"].function("") # type: ignore[union-attr] - assert "blocked by security policy" in sh_tools["run_command"].function("echo 1; echo 2") # type: ignore[union-attr] - assert "not found" in sh_tools["check_command"].function("nonexistent_id") # type: ignore[union-attr] - assert "not found" in sh_tools["stop_command"].function("nonexistent_id") # type: ignore[union-attr] - assert "Error: empty command" in sh_tools["start_command"].function("") # type: ignore[union-attr] - - -def test_shell_denies_destructive_commands() -> None: - shell = Shell(cwd=Path(".")) - for cmd in ["reboot", "shutdown -h now", "poweroff", "mkfs.ext4 /dev/sda"]: - ok, err, _ = shell._validate_command(cmd) - assert ok is False - assert "blocked" in err.lower() - - -def test_shell_blocks_path_traversal_in_command_arguments() -> None: - shell = Shell(cwd=Path(".")) - ok, err, _ = shell._validate_command("cat ../../etc/passwd") - assert ok is False - assert "traversal" in err.lower() or "blocked" in err.lower() - - -def test_shell_limits_concurrent_background_processes() -> None: - from unittest.mock import patch - - shell = Shell(cwd=Path("."), max_bg_processes=2) - tools = {t.name if hasattr(t, "name") else t.__name__: t for t in shell.get_tools()} - start_cmd = tools["start_command"] - - with patch("subprocess.Popen") as mock_popen: - mock_proc = MagicMock() - mock_proc.poll.return_value = None # Running - mock_popen.return_value = mock_proc - - res1 = start_cmd("echo 1") - assert "ID: cmd_" in res1 - res2 = start_cmd("echo 2") - assert "ID: cmd_" in res2 - # Third command exceeds limit of 2 - res3 = start_cmd("echo 3") - assert "maximum limit" in res3.lower() or "blocked" in res3.lower() - - -MEMBER_LIFETIME_SECONDS = int(10 * THREAD_HANDOFF_BOUND_SECONDS) -"""How long a group member sleeps: well past the bound of the wait that checks it ended, so only -`stop_command` can end it inside that wait. `_kill_if_running` ends a member a failing test left.""" - -_POSIX_PROCESS_GROUPS = pytest.mark.skipif( - not hasattr(os, "killpg") or not Path("/proc/self/stat").is_file(), - reason="needs POSIX process groups and the Linux /proc filesystem", -) - - -def _gone_or_zombie(pid: int) -> bool: - """Whether the process has exited: reaped, or a zombie its new parent has not reaped yet. - - A process reaped between opening its stat file and reading it fails the read with ESRCH. - """ - try: - stat = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8") - except FileNotFoundError, ProcessLookupError: - return True - return stat.rsplit(")", 1)[1].split()[0] == "Z" - - -def _kill_if_running(pid: int) -> None: - """Stop a process a failing test left behind, never touching init, this process or a dead pid.""" - if pid > 1 and pid != os.getpid() and not _gone_or_zombie(pid): - with contextlib.suppress(ProcessLookupError): - os.kill(pid, signal.SIGKILL) - - -def _read_pid(pid_file: Path) -> int: - text = pid_file.read_text(encoding="utf-8") if pid_file.is_file() else "" - return int(text) if text.endswith("\n") else 0 - - -def _background_tools(tmp_path: Path) -> dict[str, Callable[..., str]]: - shell = Shell(cwd=tmp_path, allowed_commands=["sh"], stop_grace_seconds=0.2) - return {t.name: t.function for t in shell.get_tools()} # type: ignore[union-attr] - - -@_POSIX_PROCESS_GROUPS -def test_stop_command_ends_members_an_exited_leader_left_running(tmp_path: Path) -> None: - """Stopping a command whose leader has exited still ends the rest of its group (#958). - - The group was found through the leader's pid, which fails once the leader is reaped, and the - failure was swallowed while `stop_command` reported the command terminated. - """ - tools = _background_tools(tmp_path) - # The member leaves the command's pipes, so the readers see EOF once the leader exits. - started = tools["start_command"]( - f"sh -c 'sleep {MEMBER_LIFETIME_SECONDS} >/dev/null 2>&1 & echo $! > pid; exit 0'" - ) - cmd_id = started.split("ID: ")[1] - finished = wait_until(lambda: "FINISHED" in tools["check_command"](cmd_id)) - pid = _read_pid(tmp_path / "pid") - try: - report = tools["stop_command"](cmd_id) - ended = wait_until(lambda: _gone_or_zombie(pid)) - finally: - _kill_if_running(pid) - - assert (finished, pid > 1, report, ended) == ( - True, - True, - f"Background command {cmd_id} terminated.", - True, - ) - - -@_POSIX_PROCESS_GROUPS -def test_stop_command_kills_a_member_that_ignores_sigterm(tmp_path: Path) -> None: - """A group member still alive when the grace period ends gets SIGKILL (#958). - - Escalation waited only on the leader, which SIGTERM ended, so a member ignoring SIGTERM - kept running. - """ - tools = _background_tools(tmp_path) - member = f"trap '' TERM; echo $$ > pid; exec sleep {MEMBER_LIFETIME_SECONDS}" - started = tools["start_command"]( - shlex.join(["sh", "-c", f"sh -c {shlex.quote(member)} & wait"]) - ) - cmd_id = started.split("ID: ")[1] - written = wait_until(lambda: _read_pid(tmp_path / "pid") > 1) - pid = _read_pid(tmp_path / "pid") - try: - tools["stop_command"](cmd_id) - ended = wait_until(lambda: _gone_or_zombie(pid)) - finally: - _kill_if_running(pid) - - assert (written, ended) == (True, True) - - -def _leader(pid: Any) -> MagicMock: - proc = MagicMock() - proc.pid = pid - proc.wait.side_effect = subprocess.TimeoutExpired("sh", 0) - return proc - - -def test_terminate_process_group_guards_and_logs_what_it_cannot_do( - caplog: pytest.LogCaptureFixture, -) -> None: - """Never signals PID 0 or 1 or this process's group, and logs failures it used to swallow (#958).""" - import devops_cli.ai.harness.shell as shell_module - - shell = Shell(stop_grace_seconds=0.0) - with patch.object(shell_module.os, "killpg") as guarded: - for pid in (0, 1, os.getpgrp(), MagicMock()): - shell._terminate_process_group(_leader(pid)) - with ( - caplog.at_level(logging.WARNING, logger="devops_cli.ai.harness.shell"), - patch.object(shell_module.os, "killpg", side_effect=PermissionError) as refused, - ): - shell._terminate_process_group(_leader(424242)) - with ( - caplog.at_level(logging.WARNING, logger="devops_cli.ai.harness.shell"), - patch.object(shell_module.os, "killpg") as escalated, - ): - shell._terminate_process_group(_leader(424243)) - - assert ( - guarded.call_args_list, - refused.call_args_list, - escalated.call_args_list, - [record.getMessage() for record in caplog.records], - ) == ( - [], - [call(424242, signal.SIGTERM)], - [call(424243, signal.SIGTERM), call(424243, signal.SIGKILL)], - [ - "Not permitted to signal process group 424242 with SIGTERM", - "Process group 424243 leader did not exit 0.0s after SIGKILL", - ], - ) - - -def test_macroscope_rejects_path_traversal_in_base_ref() -> None: - from devops_cli.ai.harness.agents import ( - Macroscope, - _is_safe_diff_base, - _validate_diff_base, - ) - - assert _is_safe_diff_base("main") is True - assert _is_safe_diff_base("feature/branch-1") is True - assert _is_safe_diff_base("HEAD~1") is True - assert _is_safe_diff_base("v1.2.3") is True - assert _is_safe_diff_base("") is True - - assert _is_safe_diff_base("../etc/passwd") is False - assert _is_safe_diff_base("/root") is False - assert _is_safe_diff_base("\\windows\\system32") is False - assert _is_safe_diff_base("branch;rm -rf /") is False - - assert _validate_diff_base(None) is None - assert _validate_diff_base("main") is None - invalid_err = _validate_diff_base("../../refs/heads/main") - assert invalid_err is not None - assert "Invalid base reference" in invalid_err - - macroscope = Macroscope() - tools = {t.name if hasattr(t, "name") else t.__name__: t for t in macroscope.get_tools()} - review_tool = tools["run_macroscope_review"] - fn = getattr(review_tool, "function", review_tool) - res = fn(base="../../refs/heads/main") - assert "invalid" in res.lower() or "blocked" in res.lower() or "traversal" in res.lower() - - -def test_playwright_navigate_blocks_unsupported_schemes() -> None: - from devops_cli.ai.harness.agents import PlaywrightBrowser - - browser = PlaywrightBrowser() - tools = {t.name if hasattr(t, "name") else t.__name__: t for t in browser.get_tools()} - nav_tool = tools["navigate"] - fn = nav_tool.function if hasattr(nav_tool, "func") else nav_tool - res = fn("javascript:alert(1)") - assert "blocked" in res.lower() or "unsupported" in res.lower() - - -def _await_background_finish(tools: dict[str, Any], cmd_id: str) -> str: - """The check_command report once the process reports FINISHED, or once the bound has passed. - - The bound is what turns the deadlock into a test failure instead of a hung suite: an - undrained child never exits, so without one the poll would spin forever. - """ - wait_until(lambda: "FINISHED" in tools["check_command"].function(command_id=cmd_id)) - return str(tools["check_command"].function(command_id=cmd_id)) - - -def _start_background_python(shell: Shell, snippet: str) -> tuple[dict[str, Any], str]: - """Launch a Python snippet in the background and return the tool table plus its ID.""" - import sys - - tools: dict[str, Any] = {t.name: t for t in shell.get_tools()} - started = tools["start_command"].function( # type: ignore[union-attr] - command=f'{sys.executable} -c "{snippet}"' - ) - assert "Background command started with ID: " in started - return tools, started.split("ID: ")[1].strip() - - -def _python_shell(tmp_path: Path, **kwargs: Any) -> Shell: - import sys - - return Shell(cwd=tmp_path, allowed_commands=[Path(sys.executable).name], **kwargs) - - -def test_shell_background_command_drains_pipes_without_deadlock(tmp_path: Path) -> None: - """A child writing past the kernel pipe buffer must still be able to run to completion.""" - # Roughly 1 MiB per stream, far beyond the 64 KiB Linux pipe buffer that an undrained - # background process blocks on. - snippet = ( - "import sys;" - "[print('y' * 1000) for _ in range(1000)];" - "[print('e' * 1000, file=sys.stderr) for _ in range(1000)]" - ) - # The character cap keeps the tail of the report, so it is raised above the payload here; - # otherwise the stream labels at the head would be truncated away and prove nothing. - shell = _python_shell(tmp_path, max_output_chars=10_000_000) - tools, cmd_id = _start_background_python(shell, snippet) - - result = _await_background_finish(tools, cmd_id) - - assert ("FINISHED (exit code: 0)" in result, "[stdout]" in result, "[stderr]" in result) == ( - True, - True, - True, - ) - - -def test_shell_check_command_reports_accumulated_output(tmp_path: Path) -> None: - """check_command advertises status AND output; before the ring buffers it returned only status.""" - shell = _python_shell(tmp_path) - tools, cmd_id = _start_background_python( - shell, "import sys; print('bg_stdout_marker'); print('bg_stderr_marker', file=sys.stderr)" - ) - - result = _await_background_finish(tools, cmd_id) - - assert ( - "status:" in result, - "bg_stdout_marker" in result, - "bg_stderr_marker" in result, - ) == (True, True, True) - - -def test_shell_background_output_ring_is_bounded(tmp_path: Path) -> None: - """The retained window is capped, and the caller is told how much scrollback was evicted.""" - shell = _python_shell(tmp_path, max_bg_output_lines=5) - tools, cmd_id = _start_background_python(shell, "[print(f'line-{i}') for i in range(50)]") - - result = _await_background_finish(tools, cmd_id) - - assert ( - "[... 45 earlier line(s) dropped ...]" in result, - "line-49" in result, - "line-45" in result, - "line-0\n" in result, - ) == (True, True, True, False) - - -def test_a_background_command_survives_an_undecodable_byte(tmp_path: Path) -> None: - """One stray byte used to kill the command outright. - - The pipes are read with `text=True`, so strict decoding raised `UnicodeDecodeError` in - the reader thread. That is a `ValueError`, so the drain handler treated it as a closed - pipe, left its `with stream:` block, and the child died of SIGPIPE on its next write. - A command is not wrong to emit a stray byte. - """ - snippet = ( - "import sys;" - "sys.stdout.write(chr(39) + 'start' + chr(39) and 'start\\n');sys.stdout.flush();" - "sys.stdout.buffer.write(b'\\xff\\xfe bad\\n');sys.stdout.flush();" - "sys.stdout.write('tail-marker\\n')" - ) - shell = _python_shell(tmp_path) - tools, cmd_id = _start_background_python(shell, snippet) - report = _await_background_finish(tools, cmd_id) - assert ("FINISHED (exit code: 0)" in report, "tail-marker" in report) == (True, True) diff --git a/tests/test_harness_slots.py b/tests/test_harness_slots.py index 2d7272e018..b307db610c 100644 --- a/tests/test_harness_slots.py +++ b/tests/test_harness_slots.py @@ -9,7 +9,7 @@ from typer.testing import CliRunner from devops_cli.ai.capability import TaskComplexity -from devops_cli.ai.harness.skills import ParsedSkill +from devops_cli.ai.harness.skills import ParsedSkill, normalize_skill_name from devops_cli.ai.harness.slots import ( AgentHarness, BaseSlot, @@ -151,6 +151,15 @@ def test_model_slot_lifecycle_and_swapping() -> None: slot.ensure_local() +def test_skill_names_normalize_to_lowercase_hyphenated_form() -> None: + """Skill names normalize with NFKC and refuse a leading or trailing hyphen and more than 64 characters.""" + assert normalize_skill_name("Code-Review") == "code-review" + assert normalize_skill_name(" release-notes ") == "release-notes" + for invalid_name in ("-invalid-start", "invalid-end-", "x" * 70): + with pytest.raises(HarnessValidationError, match="Invalid skill name"): + normalize_skill_name(invalid_name) + + def test_skill_slot_attach_detach(tmp_path: Path) -> None: """Verify SkillSlot registration, lookup, detachment, and prompt synthesis.""" slot = SkillSlot(name="skills", slot_type=SlotType.SKILL) diff --git a/tests/test_http_egress.py b/tests/test_http_egress.py index 36b329b122..0467501928 100644 --- a/tests/test_http_egress.py +++ b/tests/test_http_egress.py @@ -20,7 +20,6 @@ from devops_cli.ai.client import LLMClient from devops_cli.ai.common_tools import duckduckgo_search_tool, tavily_search, web_fetch_tool -from devops_cli.ai.harness.docs import PydanticAIDocs from devops_cli.commands.install_tools import _download from devops_cli.config.defaults import ( DEFAULT_HTTP_MAX_CONNECTIONS, @@ -664,7 +663,6 @@ def _caller_calls(flag: bool) -> dict[str, Callable[[], Any]]: "ai shared client": _ai_shared_call(flag), "duckduckgo": lambda: duckduckgo_search_tool().execute(query="devops"), "tavily": lambda: tavily_search("devops", api_key="tvly-test"), - "harness docs": lambda: PydanticAIDocs()._fetch_remote_doc("https://example.com/a.md"), "statuspage": lambda: fetch_statuspage_summary("https://example.com/api/v2/summary.json"), } @@ -684,7 +682,6 @@ def _expected_levels(flag: bool) -> dict[str, EgressLevel]: "ai shared client": PRIVATE if flag else LOOPBACK, "duckduckgo": PUBLIC, "tavily": PUBLIC, - "harness docs": PUBLIC, "statuspage": PUBLIC, } diff --git a/tests/test_pydantic_agent.py b/tests/test_pydantic_agent.py index 23c15a525f..41544fa3f5 100644 --- a/tests/test_pydantic_agent.py +++ b/tests/test_pydantic_agent.py @@ -366,41 +366,44 @@ def calculate(x: int, y: int) -> int: def test_pydantic_agent_capabilities_and_on_demand() -> None: - """Verify BaseCapability, Capability, and on-demand deferred loading.""" - from devops_cli.ai.agents.capabilities import Capability - - # 1. Non-deferred capability - monitoring_cap = Capability( - id="monitoring", - description="Grafana and Prometheus monitoring queries", - instructions="Always include time range in queries.", - defer_loading=False, - ) + """Verify BaseCapability subclasses load eagerly, or on demand when deferred.""" + from devops_cli.ai.agents.capabilities import BaseCapability - @monitoring_cap.tool def query_metric(metric: str) -> str: return f"Metric {metric} value: 42" - # 2. Deferred on-demand capability - k8s_cap = Capability( - id="k8s_tools", - description="Kubernetes cluster operations and pod inspection", - instructions="Never delete production pods without confirmation.", - defer_loading=True, - model_settings={"enable_thinking": True}, - ) - - @k8s_cap.tool def get_pods(namespace: str) -> str: return f"Pods in {namespace}: pod-1, pod-2" + class MonitoringCapability(BaseCapability): + id: str = "monitoring" + description: str = "Grafana and Prometheus monitoring queries" + + def get_tools(self) -> list[Any]: + return [query_metric] + + def get_system_prompt_additions(self, ctx: RunContext[Any] | None = None) -> list[str]: + return ["Always include time range in queries."] + + class KubernetesCapability(BaseCapability): + id: str = "k8s_tools" + description: str = "Kubernetes cluster operations and pod inspection" + defer_loading: bool = True + + def get_tools(self) -> list[Any]: + return [get_pods] + + def get_model_settings(self, ctx: RunContext[Any] | None = None) -> dict[str, Any]: + return {"enable_thinking": True} + + k8s_cap = KubernetesCapability() mock_client = MagicMock() mock_client.model = "test-model" agent = PydanticAgent( client=mock_client, name="CapabilityAgent", - capabilities=[monitoring_cap, k8s_cap], + capabilities=[MonitoringCapability(), k8s_cap], ) # Initial state: monitoring tool is loaded, k8s_cap is deferred (load_capability tool available) @@ -933,326 +936,6 @@ def async_batch_job(task_name: str) -> str: assert "snapshot-123" in str(res2.tool_calls[0].result) -def test_native_tools_web_search_and_code_execution() -> None: - """Verify NativeTool capability with WebSearchTool and CodeExecutionTool configurations.""" - from devops_cli.ai.agents.capabilities import ( - CodeExecutionTool, - NativeTool, - WebSearchTool, - WebSearchUserLocation, - ) - - loc = WebSearchUserLocation(city="San Francisco", country="US", timezone="America/Los_Angeles") - search_tool = WebSearchTool( - search_context_size="high", - user_location=loc, - blocked_domains=["example.com"], - max_uses=5, - ) - native_search_cap = NativeTool(tool=search_tool) - settings = native_search_cap.get_model_settings() - assert settings["native_web_search"] is True - assert settings["web_search_config"]["search_context_size"] == "high" - assert settings["web_search_config"]["user_location"]["city"] == "San Francisco" - assert settings["web_search_config"]["blocked_domains"] == ["example.com"] - - code_tool = CodeExecutionTool(language="python", timeout=30.0) - native_code_cap = NativeTool(tool=code_tool) - code_settings = native_code_cap.get_model_settings() - assert code_settings["native_code_execution"] is True - assert code_settings["code_execution_config"]["language"] == "python" - - mock_client = MagicMock() - mock_client.model = "test-model" - - agent = PydanticAgent( - client=mock_client, - name="SearchAgent", - capabilities=[native_search_cap], - ) - prompt = agent._build_system_prompt_with_tools() - assert "Provider-native web search capability is enabled." in prompt - - -def test_mcp_capability_and_native_server_tool() -> None: - """Verify MCP capability and MCPServerTool integration.""" - from devops_cli.ai.agents.capabilities import ( - MCP, - MCPServerTool, - NativeTool, - ) - from devops_cli.ai.agents.tools import Tool - - # 1. Native MCP server tool - mcp_tool = MCPServerTool( - id="cluster-mcp", - url="https://example.com/sse", - authorization_token="bearer-token-123", - description="Kubernetes cluster MCP server", - ) - native_cap = NativeTool(tool=mcp_tool) - settings = native_cap.get_model_settings() - assert settings["native_mcp_server"] is True - assert settings["mcp_server_config"]["id"] == "cluster-mcp" - assert settings["mcp_server_config"]["authorization_token"] == "bearer-token-123" - - # 2. Adaptive MCP capability with local tools - def sample_mcp_tool(x: int) -> int: - return x * 2 - - local_t = Tool.from_function(sample_mcp_tool, name="calc_double") - mcp_cap = MCP( - url="https://example.com/sse", - native=True, - local=[local_t], - ) - mcp_tools = mcp_cap.get_tools() - assert len(mcp_tools) == 1 - assert mcp_tools[0].name == "calc_double" - - mcp_settings = mcp_cap.get_model_settings() - assert mcp_settings["native_mcp_server"] is True - assert mcp_settings["mcp_server_config"]["url"] == "https://example.com/sse" - - # 3. Strict native mode (local=False) - strict_native = MCP("https://example.com/sse", native=True, local=False) - assert strict_native.get_tools() == [] - - -def test_web_search_capability_adaptive() -> None: - """Verify WebSearch adaptive capability with native and local fallbacks.""" - from devops_cli.ai.agents.capabilities import ( - WebSearch, - WebSearchTool, - ) - - # 1. Native-only - cap_native = WebSearch(native=WebSearchTool(search_context_size="high")) - assert cap_native.get_tools() == [] - settings = cap_native.get_model_settings() - assert settings["native_web_search"] is True - assert settings["web_search_config"]["search_context_size"] == "high" - - # 2. DuckDuckGo local fallback - cap_ddg = WebSearch(local="duckduckgo", native=False) - tools = cap_ddg.get_tools() - assert len(tools) == 1 - assert tools[0].name == "duckduckgo_search" - assert cap_ddg.get_model_settings() == {} - - # 3. Custom callable local fallback - def custom_search(q: str) -> str: - return f"result for {q}" - - cap_custom = WebSearch(local=custom_search) - custom_tools = cap_custom.get_tools() - assert len(custom_tools) == 1 - assert custom_tools[0].name == "custom_search" - - -def test_web_fetch_capability_adaptive() -> None: - """Verify WebFetch adaptive capability with native and local fallbacks.""" - from devops_cli.ai.agents.capabilities import ( - WebFetch, - WebFetchTool, - ) - - # 1. Native-only - cap_native = WebFetch( - native=WebFetchTool( - allowed_domains=["example.com"], - max_uses=3, - ) - ) - assert cap_native.get_tools() == [] - settings = cap_native.get_model_settings() - assert settings["native_web_fetch"] is True - assert settings["web_fetch_config"]["allowed_domains"] == ["example.com"] - assert settings["web_fetch_config"]["max_uses"] == 3 - - # 2. Local fallback - cap_local = WebFetch(allowed_domains=["docs.python.org"], local=True, native=False) - tools = cap_local.get_tools() - assert len(tools) == 1 - assert tools[0].name == "web_fetch" - assert cap_local.get_model_settings() == {} - - # 3. Custom callable local fallback - def custom_fetch(url: str) -> str: - return f"content for {url}" - - cap_custom = WebFetch(local=custom_fetch) - custom_tools = cap_custom.get_tools() - assert len(custom_tools) == 1 - assert custom_tools[0].name == "custom_fetch" - - -def test_thinking_capability_and_parts() -> None: - from devops_cli.ai.agents.capabilities import ( - Thinking, - ThinkingPart, - ) - - part = ThinkingPart(content="Step-by-step reasoning...", encrypted_content="enc_123") - assert part.content == "Step-by-step reasoning..." - assert part.encrypted_content == "enc_123" - assert part.part_kind == "thinking" - - thinking_cap = Thinking( - effort="high", - budget_tokens=8192, - include_thoughts=True, - include_encrypted_content=True, - ) - - prompt_additions = thinking_cap.get_system_prompt_additions() - assert "Thinking capability is enabled (effort=high)." in prompt_additions[0] - - settings = thinking_cap.get_model_settings() - assert settings["thinking"] == "high" - assert settings["budget_tokens"] == 8192 - assert settings["include_thoughts"] is True - assert settings["include_encrypted_content"] is True - assert settings["xai_include_encrypted_content"] is True - - -def test_native_tool_all_variants() -> None: - from pydantic import BaseModel - - from devops_cli.ai.agents.capabilities import ( - CodeExecutionTool, - MCPServerTool, - NativeTool, - WebFetchTool, - WebSearchTool, - ) - - # 1. WebSearchTool - nt_search = NativeTool(tool=WebSearchTool(max_uses=5, search_context_size="large")) - assert nt_search.get_model_settings()["native_web_search"] is True - assert "Provider-native web search" in nt_search.get_system_prompt_additions()[0] - - # 2. WebFetchTool - nt_fetch = NativeTool(tool=WebFetchTool(max_uses=3, enable_citations=True)) - assert nt_fetch.get_model_settings()["native_web_fetch"] is True - assert "Provider-native web fetch" in nt_fetch.get_system_prompt_additions()[0] - - # 3. CodeExecutionTool - nt_code = NativeTool(tool=CodeExecutionTool()) - assert nt_code.get_model_settings()["native_code_execution"] is True - assert "sandboxed code execution" in nt_code.get_system_prompt_additions()[0] - - # 4. MCPServerTool - nt_mcp = NativeTool(tool=MCPServerTool(id="mcp-srv", url="http://localhost:8080")) - assert nt_mcp.get_model_settings()["native_mcp_server"] is True - assert "Provider-native MCP server" in nt_mcp.get_system_prompt_additions()[0] - - # 5. Generic BaseModel - class GenericTool(BaseModel): - foo: str = "bar" - - nt_gen = NativeTool(tool=GenericTool()) - assert nt_gen.get_model_settings()["native_tool"]["foo"] == "bar" - assert nt_gen.get_system_prompt_additions() == [] - - -def test_mcp_capability_variants() -> None: - from devops_cli.ai.agents.capabilities import ( - MCP, - MCPServerTool, - ) - from devops_cli.ai.agents.tools import Tool - - # 1. Native MCPServerTool - mcp_native = MCP(native=MCPServerTool(id="srv-1", url="http://example.com")) - settings = mcp_native.get_model_settings() - assert settings["native_mcp_server"] is True - assert settings["mcp_server_config"]["id"] == "srv-1" - native_additions = mcp_native.get_system_prompt_additions() - assert len(native_additions) > 0 - assert native_additions[0].startswith("Model Context Protocol (MCP) capability active") - - # 2. Native with URL - mcp_url = MCP(url="http://localhost:3000", native=True) - assert mcp_url.get_model_settings()["native_mcp_server"] is True - url_additions = mcp_url.get_system_prompt_additions() - assert len(url_additions) > 0 - assert url_additions[0].startswith("Model Context Protocol (MCP) capability active") - - # 3. Local tools list - def dummy_fn() -> str: - return "dummy" - - t = Tool.from_function(dummy_fn) - mcp_local_list = MCP(local=[t]) - assert len(mcp_local_list.get_tools()) == 1 - - # 4. Local object with get_tools - class CustomLocal: - def get_tools(self) -> list[Any]: - return [dummy_fn] - - mcp_custom = MCP(local=CustomLocal()) - assert len(mcp_custom.get_tools()) == 1 - - # 5. Local is False - mcp_no_local = MCP(local=False) - assert mcp_no_local.get_tools() == [] - - -def test_web_search_and_web_fetch_full_branches() -> None: - from devops_cli.ai.agents.capabilities import ( - WebFetch, - WebFetchTool, - WebSearch, - ) - from devops_cli.ai.agents.tools import Tool - - # WebSearch native=True, local=False - ws_native = WebSearch(native=True, local=False) - assert ws_native.get_model_settings()["native_web_search"] is True - assert "Provider-native web search" in ws_native.get_system_prompt_additions()[0] - assert ws_native.get_tools() == [] - - # WebSearch local=Tool - def search_fn(q: str) -> str: - return f"result: {q}" - - ws_tool = WebSearch(native=False, local=Tool.from_function(search_fn)) - assert len(ws_tool.get_tools()) == 1 - assert "Local web search" in ws_tool.get_system_prompt_additions()[0] - - # WebSearch local=list - ws_list = WebSearch(native=False, local=[search_fn]) - assert len(ws_list.get_tools()) == 1 - - # WebFetch native=WebFetchTool, local=False - wf_tool_obj = WebFetchTool(allowed_domains=["example.com"], max_uses=2) - wf_native = WebFetch(native=wf_tool_obj, local=False) - assert wf_native.get_model_settings()["native_web_fetch"] is True - assert "Provider-native web fetch" in wf_native.get_system_prompt_additions()[0] - - # WebFetch native=True with domains - wf_domains = WebFetch( - native=True, allowed_domains=["example.com"], blocked_domains=["evil.com"], local=False - ) - settings = wf_domains.get_model_settings() - assert settings["web_fetch_config"]["allowed_domains"] == ["example.com"] - assert settings["web_fetch_config"]["blocked_domains"] == ["evil.com"] - - # WebFetch local=Tool - def fetch_fn(u: str) -> str: - return f"body: {u}" - - wf_tool = WebFetch(native=False, local=Tool.from_function(fetch_fn)) - assert len(wf_tool.get_tools()) == 1 - assert "Local web fetch" in wf_tool.get_system_prompt_additions()[0] - - # WebFetch local=list - wf_list = WebFetch(native=False, local=[fetch_fn]) - assert len(wf_list.get_tools()) == 1 - - def test_resolve_pydantic_ai_model() -> None: """Verify resolve_pydantic_ai_model correctly handles Ollama, TestModel, and models.""" from pydantic_ai.models.ollama import OllamaModel diff --git a/tests/test_pydantic_ai_format_prompt.py b/tests/test_pydantic_ai_format_prompt.py index c204bfe398..59af4f233a 100644 --- a/tests/test_pydantic_ai_format_prompt.py +++ b/tests/test_pydantic_ai_format_prompt.py @@ -15,7 +15,6 @@ format_examples_as_xml, format_findings_as_xml, format_metadata_as_xml, - format_plan_reminder_as_xml, format_prompt_data, format_rag_context_as_xml, ) @@ -39,15 +38,6 @@ class SampleDataclassItem: value: int = field(metadata={"description": "Item integer counter"}) -class SamplePlanItem(BaseModel): - """Test plan task item.""" - - id: str - content: str - status: str - active_form: str | None = None - - def test_format_as_xml_reexport() -> None: """Verify format_as_xml is directly re-exported from native pydantic_ai.format_prompt.""" assert format_as_xml is p_fp.format_as_xml @@ -188,23 +178,6 @@ def test_format_findings_as_xml() -> None: assert "" in xml_out -def test_format_plan_reminder_as_xml() -> None: - """Verify format_plan_reminder_as_xml converts tasks into structured XML.""" - items = [ - SamplePlanItem(id="task-1", content="Setup tests", status="completed"), - SamplePlanItem( - id="task-2", content="Implement feature", status="in_progress", active_form="Coding" - ), - ] - xml_out = format_plan_reminder_as_xml(items) - assert "" in xml_out - assert "" in xml_out or "" in xml_out - assert "task-1" in xml_out - assert "completed" in xml_out - assert "Coding" in xml_out - assert "" in xml_out - - def test_format_metadata_as_xml() -> None: """Verify format_metadata_as_xml serializes session metadata.""" meta = {"session_id": "sess-12345", "persona": "devsecops", "dry_run": True} @@ -256,19 +229,3 @@ def test_managed_prompt_xml_formatting() -> None: assert "CVE-2026-9999" in rendered assert "" in rendered assert "Begin analysis." in rendered - - -def test_planning_harness_uses_format_as_xml() -> None: - """Verify harness planning uses format_plan_reminder_as_xml cleanly.""" - from devops_cli.ai.harness.planning import PlanningStore - - store = PlanningStore() - store.add("Step 1: Test", status="completed") - store.add("Step 2: Code", status="in_progress", active_form="Implementing") - - items = store.get_items() - xml_out = format_plan_reminder_as_xml(items) - assert "" in xml_out - assert "Step 1: Test" in xml_out - assert "Step 2: Code" in xml_out - assert "" in xml_out diff --git a/tests/test_pydantic_ai_native_capabilities.py b/tests/test_pydantic_ai_native_capabilities.py index 381073b985..367a7c001f 100644 --- a/tests/test_pydantic_ai_native_capabilities.py +++ b/tests/test_pydantic_ai_native_capabilities.py @@ -2,6 +2,8 @@ from __future__ import annotations +from typing import Any + import pytest from pydantic import BaseModel from pydantic_ai import Agent @@ -10,29 +12,10 @@ from devops_cli.ai.agents.agent import PydanticAgent from devops_cli.ai.agents.capabilities import ( - MCP, BaseCapability, - Capability, HandleDeferredToolCalls, - IncludeToolReturnSchemas, - Instrumentation, - NativeTool, - PrefixTools, - PrepareTools, - ProcessEventStream, - ProcessHistory, - RaiseContentFilterError, - ReinjectSystemPrompt, - ResolveModelId, - SelectModel, - SetToolMetadata, SystemReminders, - Thinking, - UseThreadExecutor, - WebFetch, - WebSearch, ) -from devops_cli.ai.harness.docs import PydanticAIDocs from devops_cli.ai.personas import Persona from devops_cli.ai.pydantic_ai_bridge import ( DevOpsAgentContext, @@ -44,31 +27,28 @@ pytestmark = pytest.mark.usefixtures("mock_keyring") +class MathCapability(BaseCapability): + """A capability that offers one tool and one instruction.""" + + id: str = "math" + + def get_tools(self) -> list[Any]: + def multiply_numbers(x: int, y: int) -> int: + """Multiply two integers.""" + return x * y + + return [multiply_numbers] + + def get_system_prompt_additions(self, ctx: Any = None) -> list[str]: + return ["You are a helpful mathematical assistant."] + + def test_all_capabilities_inherit_from_abstract_capability() -> None: """Verify that BaseCapability and every derived capability inherits from pydantic_ai AbstractCapability.""" all_capability_classes: list[type[BaseCapability]] = [ BaseCapability, - Capability, - Thinking, - WebSearch, - WebFetch, - MCP, - NativeTool, - PrefixTools, - SetToolMetadata, - UseThreadExecutor, - Instrumentation, - SelectModel, - ResolveModelId, HandleDeferredToolCalls, - IncludeToolReturnSchemas, - RaiseContentFilterError, - ReinjectSystemPrompt, - PrepareTools, - ProcessHistory, - ProcessEventStream, SystemReminders, - PydanticAIDocs, ] for cls in all_capability_classes: @@ -90,30 +70,22 @@ def test_base_capability_native_agent_execution() -> None: assert res.output == "success (no tool calls)" -def test_thinking_capability_native_agent_execution() -> None: - """Verify that Thinking capability passes settings to native pydantic_ai.Agent without error.""" - th = Thinking(effort="medium", budget_tokens=4096, include_thoughts=True) - assert isinstance(th, AbstractCapability) +def test_system_reminders_in_native_agent() -> None: + """Verify SystemReminders capability in native Agent execution.""" + sr = SystemReminders(reminders=["Follow zero-trust security rules."], cadence=1) + assert isinstance(sr, AbstractCapability) - # Check model settings - settings = th.get_model_settings() - assert settings.get("thinking") == "medium" - assert settings.get("budget_tokens") == 4096 + instructions = sr.get_instructions() + assert "Follow zero-trust security rules." in instructions - # Native agent execution - agent = Agent(model=TestModel(), capabilities=[th]) - res = agent.run_sync("think deeply") + agent = Agent(model=TestModel(), capabilities=[sr]) + res = agent.run_sync("verify policy") assert res.output == "success (no tool calls)" def test_capability_tools_and_instructions_in_native_agent() -> None: - """Verify that tools registered on Capability are exposed via get_toolset and executed natively.""" - cap = Capability(instructions="You are a helpful mathematical assistant.") - - @cap.tool - def multiply_numbers(x: int, y: int) -> int: - """Multiply two integers.""" - return x * y + """Verify that tools a capability offers are exposed via get_toolset and executed natively.""" + cap = MathCapability() # Verify native AbstractCapability protocol methods instructions = cap.get_instructions() @@ -131,40 +103,9 @@ def multiply_numbers(x: int, y: int) -> int: assert res.output == '{"multiply_numbers":0}' -def test_system_reminders_in_native_agent() -> None: - """Verify SystemReminders capability in native Agent execution.""" - sr = SystemReminders(reminders=["Follow zero-trust security rules."], cadence=1) - assert isinstance(sr, AbstractCapability) - - instructions = sr.get_instructions() - assert "Follow zero-trust security rules." in instructions - - agent = Agent(model=TestModel(), capabilities=[sr]) - res = agent.run_sync("verify policy") - assert res.output == "success (no tool calls)" - - -def test_pydantic_ai_docs_capability_in_native_agent() -> None: - """Verify PydanticAIDocs capability runs natively in pydantic_ai.Agent.""" - docs_cap = PydanticAIDocs(cache=True) - assert isinstance(docs_cap, AbstractCapability) - - instructions = docs_cap.get_instructions() - assert any("read_pyai_docs" in str(inst) for inst in instructions) - - agent = Agent(model=TestModel(call_tools=[]), capabilities=[docs_cap]) - res = agent.run_sync("read docs") - assert res.output == "success (no tool calls)" - - def test_dual_compatibility_with_devops_cli_pydantic_agent() -> None: """Verify that custom unified PydanticAgent continues to execute flawlessly with capabilities.""" - cap = Capability(instructions="Strict DevOps guidelines.") - - @cap.tool - def calculate_uptime(days: int) -> float: - """Calculate availability.""" - return 99.99 + cap = MathCapability() agent = PydanticAgent[ReviewResult]( name="SecurityReviewer", @@ -177,20 +118,19 @@ def calculate_uptime(days: int) -> float: assert agent.name == "SecurityReviewer" # Ensure tools from capability are registered tool_names = [getattr(t, "name", getattr(t, "__name__", str(t))) for t in agent.tools] - assert "calculate_uptime" in tool_names + assert "multiply_numbers" in tool_names def test_create_pydantic_ai_agent_with_native_capabilities() -> None: """Verify create_pydantic_ai_agent instantiates native Agent that runs with capabilities.""" - th = Thinking(effort="low") - cap = Capability(instructions="Always follow clean code.") + reminders = SystemReminders(reminders=["Always follow clean code."], cadence=1) agent = create_pydantic_ai_agent( model_name="test", system_prompt="Primary system prompt", output_type=ReviewResult, deps_type=DevOpsAgentContext, - capabilities=[th, cap], + capabilities=[reminders, MathCapability()], ) assert isinstance(agent, Agent) @@ -200,10 +140,10 @@ def test_create_pydantic_ai_agent_with_native_capabilities() -> None: def test_get_persona_pydantic_agent_native_execution() -> None: """Verify persona-specialized agent instantiation and execution.""" - th = Thinking(effort="medium") + reminders = SystemReminders(reminders=["Check every dependency."], cadence=1) agent = get_persona_pydantic_agent( persona=Persona.DEVSECOPS, - capabilities=[th], + capabilities=[reminders], model_name="test", ) diff --git a/tests/test_rag_hybrid_search.py b/tests/test_rag_hybrid_search.py index c67b06dd47..b114c625f3 100644 --- a/tests/test_rag_hybrid_search.py +++ b/tests/test_rag_hybrid_search.py @@ -117,38 +117,7 @@ def test_lexical_match_is_immutable() -> None: # ───────────────────────────────────────────────────────────────────────────── -# 2. Shared scorer reuse -# ───────────────────────────────────────────────────────────────────────────── - - -def test_conversation_search_uses_the_shared_scorer() -> None: - """Conversation ranking delegates to the shared BM25 implementation. - - Both consumers share one implementation so a correction to the ranking cannot apply - to only half the codebase. - """ - from devops_cli.ai.harness.conversation import bm25_rank - - documents = [ - {"run_id": "r1", "role": "user", "content": "deploy the kubernetes cluster"}, - {"run_id": "r2", "role": "assistant", "content": "unrelated commentary"}, - ] - matches = bm25_rank("kubernetes", documents) - - assert [m.run_id for m in matches] == ["r1"] - assert matches[0].score > 0.0 - - -def test_conversation_search_respects_max_matches() -> None: - """The conversation wrapper still truncates to the requested match count.""" - from devops_cli.ai.harness.conversation import bm25_rank - - documents = [{"run_id": f"r{i}", "role": "user", "content": "token"} for i in range(5)] - assert len(bm25_rank("token", documents, max_matches=2)) == 2 - - -# ───────────────────────────────────────────────────────────────────────────── -# 3. Hybrid fusion +# 2. Hybrid fusion # ───────────────────────────────────────────────────────────────────────────── @@ -216,7 +185,7 @@ def test_fusion_ranks_documents_found_by_both_rankers_highest() -> None: # ───────────────────────────────────────────────────────────────────────────── -# 4. Retriever integration +# 3. Retriever integration # ───────────────────────────────────────────────────────────────────────────── @@ -273,7 +242,7 @@ def test_search_can_disable_hybrid_fusion() -> None: # ───────────────────────────────────────────────────────────────────────────── -# 5. Vector quantization +# 4. Vector quantization # ───────────────────────────────────────────────────────────────────────────── diff --git a/tests/test_review_defenses_and_verification.py b/tests/test_review_defenses_and_verification.py index 5dca503f54..0bee5f1fbf 100644 --- a/tests/test_review_defenses_and_verification.py +++ b/tests/test_review_defenses_and_verification.py @@ -7,7 +7,6 @@ import pytest from devops_cli.ai.agents.tools import AgentTool -from devops_cli.ai.harness.filesystem import FileSystem from devops_cli.ai.review.exporter import export_invalidated_feedback from devops_cli.commands.vault import _validate_vault_path from devops_cli.core.repo import list_repo_files @@ -80,16 +79,6 @@ def test_mask_secrets_preserves_function_invocations() -> None: assert "settings_mod.get_ai_api_key(st)" in masked -def test_filesystem_search_files_redos_guard(tmp_path: Path) -> None: - fs = FileSystem(root=tmp_path) - (tmp_path / "hello.txt").write_text("hello world\n", encoding="utf-8") - - # Excessively long query string - huge_query = "a" * 500 - res = fs._search_files(query=huge_query) - assert "Error:" in res or "exceeds" in res or "No matches" in res - - def test_mask_secrets_unquoted_token_with_dots() -> None: yaml_snippet = "api_key: abc.def.1234567890abcdef12345\n" masked = mask_secrets(yaml_snippet) diff --git a/tests/test_runtime_security_and_ssrf_hardening.py b/tests/test_runtime_security_and_ssrf_hardening.py index 04f1ad8b68..829dff693a 100644 --- a/tests/test_runtime_security_and_ssrf_hardening.py +++ b/tests/test_runtime_security_and_ssrf_hardening.py @@ -7,9 +7,7 @@ import pytest -from devops_cli.ai.agents.capabilities import WebFetch from devops_cli.ai.agents.media import DiskMediaStore -from devops_cli.ai.agents.tools import Tool from devops_cli.ai.common_tools import web_fetch_tool from devops_cli.ai.diff.difftastic import get_structural_diff from devops_cli.ai.ext_langchain import _validate_langchain_kwargs @@ -91,26 +89,7 @@ def test_web_fetch_tool_reraises_ssrf_blocked_error() -> None: tool.execute(url="http://127.0.0.1:8080/admin") -# ── 5. WebFetch Capability Propagates Blocked Domains ──────────────────────── - - -def test_web_fetch_capability_propagates_blocked_domains() -> None: - """Verify that WebFetch capability passes blocked_domains to web_fetch_tool.""" - cap = WebFetch( - allowed_domains=["example.com"], - blocked_domains=["blocked.com"], - local=True, - ) - tools = cap.get_tools() - assert len(tools) == 1 - fetch_tool = tools[0] - assert isinstance(fetch_tool, Tool) - - with pytest.raises(ValueError, match="blocked_domains"): - fetch_tool.execute(url="https://blocked.com/bad") - - -# ── 6. Secret Sanitizer Regex Identifier Protection ────────────────────────── +# ── 4. Secret Sanitizer Regex Identifier Protection ────────────────────────── def test_secret_sanitizer_does_not_mask_variable_identifiers() -> None: @@ -133,7 +112,7 @@ def test_secret_sanitizer_masks_actual_secret_assignments() -> None: assert "" in sanitized or "" in sanitized -# ── 7. ChaosFaultRunner Argument Injection Guards ──────────────────────────── +# ── 5. ChaosFaultRunner Argument Injection Guards ──────────────────────────── def test_chaos_fault_runner_rejects_argument_injection() -> None: @@ -154,7 +133,7 @@ def test_chaos_fault_runner_rejects_argument_injection() -> None: ) -# ── 8. Structural Diff Ref Injection Guards ────────────────────────────────── +# ── 6. Structural Diff Ref Injection Guards ────────────────────────────────── def test_structural_diff_rejects_flag_injection_refs() -> None: @@ -167,7 +146,7 @@ def test_structural_diff_rejects_flag_injection_refs() -> None: assert "Error:" in res or res == "" -# ── 9. LangChain Tool Kwargs Percent-Encoded Traversal Guards ───────────────── +# ── 7. LangChain Tool Kwargs Percent-Encoded Traversal Guards ───────────────── def test_validate_langchain_kwargs_detects_percent_encoded_traversal() -> None: diff --git a/tests/test_subsystem_containment_and_redaction.py b/tests/test_subsystem_containment_and_redaction.py index c9a6fcfb32..4ed3b4d166 100644 --- a/tests/test_subsystem_containment_and_redaction.py +++ b/tests/test_subsystem_containment_and_redaction.py @@ -2,18 +2,15 @@ Tests cover: -1. FileSystem._resolve_safe_path prefix collision prevention. -2. NativeTool and MCP authorization token redaction. -3. Repomap symlink skipping, directory containment, and file size limits. -4. Reporting stage session_dir containment verification. -5. Static scan target path resolution containment & thread safety. -6. Context path traversal and absolute path rejection. -7. Console print_dry_run_result output secret sanitization. -8. Vault command secret path validation. -9. Telemetry probe latency & endpoint sanitization. -10. Docker sandbox container wait timeout. -11. OpenWebUI bootstrap account credential configuration. -12. Exception tuple parenthesization across modules. +1. Repomap symlink skipping, directory containment, and file size limits. +2. Reporting stage session_dir containment verification. +3. Static scan target path resolution containment & thread safety. +4. Context path traversal and absolute path rejection. +5. Console print_dry_run_result output secret sanitization. +6. Vault command secret path validation. +7. Telemetry probe latency & endpoint sanitization. +8. Docker sandbox container wait timeout. +9. OpenWebUI bootstrap account credential configuration. """ from __future__ import annotations @@ -25,11 +22,7 @@ import pytest -from devops_cli.ai.agents.capabilities import ( - NativeTool, -) from devops_cli.ai.agents.context import _check_path_traversal -from devops_cli.ai.harness.filesystem import FileSystem from devops_cli.ai.repomap import generate_repo_map, parse_file_symbols from devops_cli.ai.review.pipeline import ReviewPipelineOrchestrator from devops_cli.commands.vault import _validate_vault_path @@ -37,47 +30,7 @@ from devops_cli.output.console import print_dry_run_result -# 1. FileSystem._resolve_safe_path prefix collision prevention -def test_filesystem_resolve_safe_path_prefix_collision(tmp_path: Path) -> None: - root_dir = tmp_path / "allowed_root" - root_dir.mkdir() - sibling_dir = tmp_path / "allowed_root_extra" - sibling_dir.mkdir() - secret_file = sibling_dir / "secret.txt" - secret_file.write_text("classified", encoding="utf-8") - - fs = FileSystem(root=root_dir) - - # Legitimate subpath should resolve - valid_sub = root_dir / "file.txt" - valid_sub.write_text("hello", encoding="utf-8") - assert fs._resolve_safe_path("file.txt") == valid_sub.resolve() - - # Prefix collision (../allowed_root_extra/secret.txt) starts with str(root_dir) if not checked with is_relative_to - with pytest.raises(PermissionError, match="outside root"): - fs._resolve_safe_path("../allowed_root_extra/secret.txt") - - -# 2. NativeTool generic tool authorization token redaction -def test_native_tool_token_redaction() -> None: - from pydantic import BaseModel - - class CustomToolModel(BaseModel): - id: str = "custom_tool" - endpoint: str = "https://example.com" - authorization_token: str = "ghp_SUPERSECRET1234567890" - - custom_tool = CustomToolModel() - native_tool = NativeTool(tool=custom_tool) - settings = native_tool.get_model_settings() - - config = settings.get("native_tool", {}) - assert "authorization_token" not in config - assert config.get("id") == "custom_tool" - assert config.get("endpoint") == "https://example.com" - - -# 3. Repomap symlink skipping, containment, and file size limits +# 1. Repomap symlink skipping, containment, and file size limits def test_repomap_skips_symlinks_and_verifies_containment(tmp_path: Path) -> None: src_dir = tmp_path / "src" src_dir.mkdir() @@ -114,7 +67,7 @@ def test_parse_file_symbols_skips_giant_files(tmp_path: Path) -> None: assert node is None or len(node.symbols) == 0 -# 4. Reporting stage session_dir containment verification +# 2. Reporting stage session_dir containment verification def test_review_session_dir_outside_root_is_refused(tmp_path: Path) -> None: """A session directory outside the reviews, working or temporary directory, or through `..`, is refused before anything is written there.""" @@ -133,7 +86,7 @@ def test_review_session_dir_outside_root_is_refused(tmp_path: Path) -> None: ) -# 5. Review file path resolution containment +# 3. Review file path resolution containment def test_review_file_paths_stay_inside_the_target_and_repository(tmp_path: Path) -> None: """Files named outside the review target and its repository, absolute or through `..`, resolve to a missing in-target path rather than being read.""" @@ -161,7 +114,7 @@ def test_review_file_paths_stay_inside_the_target_and_repository(tmp_path: Path) assert not resolved[1].exists() -# 6. Context path traversal sequence rejection +# 4. Context path traversal sequence rejection def test_check_path_traversal_rejects_relative_sequences() -> None: with pytest.raises(SecurityError, match="Path traversal sequence detected"): _check_path_traversal("file_path", "../secrets.txt") @@ -177,7 +130,7 @@ def test_check_path_traversal_rejects_relative_sequences() -> None: _check_path_traversal("dest_path", "./config.yaml") -# 7. Console print_dry_run_result output secret sanitization +# 5. Console print_dry_run_result output secret sanitization def test_print_dry_run_result_masks_secrets() -> None: secret_payload = { "command": "devops auth login", @@ -194,7 +147,7 @@ def test_print_dry_run_result_masks_secrets() -> None: assert "" in printed_str -# 8. Vault command secret path validation +# 6. Vault command secret path validation def test_validate_vault_path() -> None: _validate_vault_path("secret/data/myapp") _validate_vault_path("auth/tokens/ci_bot") @@ -209,7 +162,7 @@ def test_validate_vault_path() -> None: _validate_vault_path("") -# 9. Telemetry probe latency & endpoint sanitization +# 7. Telemetry probe latency & endpoint sanitization def test_telemetry_endpoint_sanitization() -> None: from devops_cli.security.sanitizer import sanitize_telemetry_endpoint @@ -226,7 +179,7 @@ def test_telemetry_endpoint_sanitization() -> None: ) -# 10. Docker sandbox container wait timeout +# 8. Docker sandbox container wait timeout def test_docker_sandbox_wait_timeout(tmp_path: Path, docker_engine: Any) -> None: from devops_cli.docker.sandbox import WorkloadSandboxConfig, WorkloadSandboxRunner @@ -250,7 +203,7 @@ def test_docker_sandbox_wait_timeout(tmp_path: Path, docker_engine: Any) -> None assert kwargs["timeout"] > 0 -# 11. OpenWebUI bootstrap account credential configuration +# 9. OpenWebUI bootstrap account credential configuration def test_bootstrap_openwebui_account_env_overrides(monkeypatch: pytest.MonkeyPatch) -> None: from devops_cli.commands.k8s.stack_lifecycle import _get_openwebui_bootstrap_credentials diff --git a/tests/test_validation.py b/tests/test_validation.py index e739b0738c..c616271665 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -917,42 +917,27 @@ def fail_socket(*args: object, **kwargs: object) -> None: ) == ("example.com", True, False, []) -@pytest.mark.parametrize("bad_domain", ["", ".", "@", ".example.com"]) -def test_capability_domain_lists_refuse_root_and_leading_dot(bad_domain: str) -> None: - """Domain allow/block lists on capabilities and tools refuse root and leading-dot entries (#887).""" - from pydantic import ValidationError as PydanticValidationError - - from devops_cli.ai.agents.capabilities import WebFetch, WebFetchTool, WebSearchTool - from devops_cli.ai.harness.agents import PlaywrightBrowser, Researcher - - with pytest.raises(PydanticValidationError, match="allowed_domains"): - WebFetch(allowed_domains=[bad_domain]) - with pytest.raises(PydanticValidationError, match="allowed_domains"): - WebFetchTool(allowed_domains=[bad_domain]) - with pytest.raises(PydanticValidationError, match="allowed_domains"): - WebSearchTool(allowed_domains=[bad_domain]) - with pytest.raises(PydanticValidationError, match="allowed_domains"): - Researcher(allowed_domains=[bad_domain]) - with pytest.raises(PydanticValidationError, match="allowed_domains"): - PlaywrightBrowser(allowed_domains=[bad_domain]) - +def test_is_at_or_under_matches_whole_labels_and_equal_ip_literals() -> None: + """A host is at or under a domain on whole DNS labels, and an IP literal matches only itself (#887).""" + from devops_cli.core.dns_names import is_at_or_under -def test_capability_blocked_domains_and_settings_domain_validation( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """blocked_domains and k8s.domain / cloudflare.domain refuse invalid names while blank loads as None (#887).""" + assert ( + is_at_or_under("example.com", "example.com"), + is_at_or_under("example.com", "com"), + is_at_or_under("example.com", "ample.com"), + is_at_or_under("192.0.2.1", "192.0.2.1"), + is_at_or_under("192.0.2.1", "192.0.2.2"), + is_at_or_under("192.0.2.1", "example.com"), + is_at_or_under("example.com", "192.0.2.1"), + ) == (True, True, False, True, False, False, False) + + +def test_settings_domain_validation(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """k8s.domain / cloudflare.domain refuse invalid names while blank loads as None (#887).""" from pydantic import ValidationError as PydanticValidationError - from devops_cli.ai.agents.capabilities import WebFetch, WebFetchTool, WebSearchTool from devops_cli.config.settings import load_settings, reset_settings_cache - with pytest.raises(PydanticValidationError, match="blocked_domains"): - WebFetch(blocked_domains=[".example.com"]) - with pytest.raises(PydanticValidationError, match="blocked_domains"): - WebFetchTool(blocked_domains=[".example.com"]) - with pytest.raises(PydanticValidationError, match="blocked_domains"): - WebSearchTool(blocked_domains=[".example.com"]) - cfg_path = tmp_path / "config.yaml" monkeypatch.setenv("DEVOPS_CLI_CONFIG", str(cfg_path)) @@ -979,3 +964,16 @@ def test_capability_blocked_domains_and_settings_domain_validation( loaded_blank.cloudflare.domain, loaded_spaces.k8s.domain, ) == (None, None, None) + + +@pytest.mark.parametrize("root_spelling", ["@", " @ ", "\u3002", "\uff0e", "\uff61"]) +def test_settings_domain_refuses_every_spelling_of_the_root_name(root_spelling: str) -> None: + """dnspython reads `@` and the IDNA full stops as the root name, which no settings domain may be (#887).""" + from pydantic import ValidationError as PydanticValidationError + + from devops_cli.config.settings import CloudflareConfig, KubernetesConfig + + with pytest.raises(PydanticValidationError, match=r"Invalid domain in k8s\.domain"): + KubernetesConfig(domain=root_spelling) + with pytest.raises(PydanticValidationError, match=r"Invalid domain in cloudflare\.domain"): + CloudflareConfig(domain=root_spelling)