Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/SELF_IMPROVEMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,42 @@ Five systemic updates harden the loop against recurrence:
4. **Prompt Instruction Hardening**: Updated `src/devops_cli/ai/tasks/verify_finding_system.md`, `src/devops_cli/ai/tasks/review.md`, and `src/devops_cli/ai/personas/devsecops/prompt.md` with explicit invalidation rules against tautological criteria, offline URL parsing, and internal cluster networking.
5. **Defensive API & Git Execution Hardening**: Added CRLF header sanitization in gateway, URL scheme validation in gateway bench, run_id regex validation in run store, and git argument separators in analyze.

#### Calibration Record: Session `20260928-201857`

This session evaluated repository review telemetry `/workspaces/devops-cli/.data/reviews/20260928-201857`, identifying transient Cloudflare HTTP 524 gateway timeouts on provider endpoints, Python 3.12+ invalid regex escape sequence warnings, and 18 subsystem code quality and security findings:

| Claim / Observation | Why it was false / Remediated |
| --- | --- |
| Transient HTTP 524 gateway timeouts caused skipped file reviews | Review agent retried only 2 times with static backoff. Elevated `DEFAULT_REVIEW_RETRY_ATTEMPTS = 6`, exponential backoff `2.0s` to `60.0s`, broadened retry status codes (408, 429, 500, 502-504, 520-524), and sanitized Cloudflare HTML error bodies in `ai/client/base.py`. |
| `<unknown>:1: SyntaxWarning: "\w" is an invalid escape sequence` emitted during review | LLM-generated criteria and naked `ast.parse` in symbol/outline scanners emitted unescaped regex warnings under Python 3.12+. Added `PYTHONWARNINGS="ignore::SyntaxWarning"` to sandbox environment, wrapped internal `ast.parse` in `warnings.catch_warnings()`, and instructed review models to use raw strings (`r'...'`) or double backslashes. |
| Python 3.14 PEP 758 multi-exception syntax falsely flagged as syntax error | LLM claimed `except TypeError, ValueError:` syntax is invalid. Broadened `HALLUCINATION-PEP758-EXCEPT` signatures to match `catches X, Y but this syntax is invalid`. |
| Tautological criteria commands auto-verifying false findings | Criteria running `python -c "import foo; print('ok')"` exited 0 without assertions, triggering false auto-promotions. Hardened `_is_tautological_verification_command` in `review_environment.py` to require active assertions (`assert`, `sys.exit`, `pytest`). |
| Insecure dynamic reflection via `_LAZY_OBJECT_MAPPING` in `commands/mcp.py` & `commands/repos.py` | **Remediated**: removed `_LAZY_OBJECT_MAPPING`, `__getattr__`, and `_get` wrappers; replaced with direct static imports. |
| Potential path traversal in `devops repos clone-org` | **Remediated**: added `validate_no_path_traversal` and `is_relative_to` checks on `repo.name`. |
| Predictable static temporary file in `KubernetesService.switch_context` | **Remediated**: replaced static `.tmp` file with `NamedTemporaryFile(delete=False, dir=parent)` with `0o600` permissions and atomic replacement. |
| Inverted return value in `LibraryVectorStore.ensure_collection_exists` | **Remediated**: returned `True` when collection exists (`if info: return True`). |
| Unbounded refresh calculation in `LiveResourceWatcher` | **Remediated**: bounded refresh rate calculation with `min(30, max(1, int(1.0 / max(0.01, self.interval_seconds))))`. |
| Dangling client reference on close in `HttpClientBroker` | **Remediated**: guaranteed `_sync_client = None` and `_async_client = None` are always cleared on `close()` and `aclose()`. |
| Missing async client cleanup helper in `http/pool.py` | **Remediated**: added `aclose_shared_clients()` helper. |
| Incomplete error metrics in `cli_command_handler` | **Remediated**: passed `error_type=type(exc).__name__` in `DevOpsCLIError` handler. |
| Missing dictionary support in `ResourceInformer._normalize_event` | **Remediated**: extracted metadata cleanly via `_extract_event_metadata` supporting both objects and raw event dictionaries. |
| Broad exception handling in `_fetch_metric_value` in `argo/rollouts.py` | **Remediated**: narrowed `except Exception:` to `(httpx2.HTTPError, ValueError, KeyError, IndexError, TypeError)`. |
| Broad exception handling in `instruction_generator.py` | **Remediated**: narrowed `except Exception:` to `(tomllib.TOMLDecodeError, OSError)`. |
| Unvalidated output path in `grafana dashboards export` | **Remediated**: added `validate_no_path_traversal` before path resolution. |
| Root equality bypass in review feedback exporter | **Remediated**: enforced `resolved_out != root` in `ai/review/exporter.py`. |
| Missing path traversal validation in `inspect_git_manifest_drift` | **Remediated**: decomposed into pure helper functions with `validate_no_path_traversal`. |
| Unbounded callable import and resource leak in `memory_profiler.py` | **Remediated**: added `try/finally` around broker in `_exercise_http_pool`, and validated module/function names against identifier regex. |
| Unsanitized error messages in `k8s/security_stream.py` | **Remediated**: applied `mask_secrets` to `proc.stderr`. |
| Unvalidated `currentStepIndex` in `ArgoRolloutState.from_manifest` | **Remediated**: safely parsed `current_step` to integer or `None`. |
| Swallowed `ModuleNotFoundError` in `ai/__init__.py` dynamic loader | **Remediated**: verified `exc.name == f"devops_cli.ai.{name}"` before suppressing. |

Systemic hardening updates resulting from this session:
1. **Resilient HTTP Backoff & Error Stripping**: Elevated review retry attempts to 6 with exponential backoff and HTML tag stripping on provider errors.
2. **Dual-Layer Escape Sequence Suppression**: Configured sandbox environment variable `PYTHONWARNINGS` and wrapped internal AST parsers to eliminate false `SyntaxWarning: "\w"`.
3. **Strict Criteria Assertion Enforcement**: Hardened criteria evaluation to disallow unasserted `print(...)` commands from auto-verifying defects.
4. **Anti-Hallucination Expansions**: Registered `HALLUCINATION-GRAPHQL-JSON-DUMPS`, `HALLUCINATION-EXAMPLE-COM-WEBHOOK`, `HALLUCINATION-PROMETHEUS-TELEMETRY-METRIC`, and broadened `HALLUCINATION-PEP758-EXCEPT`.
5. **Systemic Code Hardening Across 18 Subsystems**: Closed path traversal, resource lifecycle, exception scoping, and type safety vulnerabilities project-wide.

### Phase 4: Root Cause & Severity Classification
- Isolate exact failure mechanisms and categorize severity:
- **CRITICAL**: Exploitable vulnerability, auth bypass, credential leak, SSRF, arbitrary file write outside root, or fatal crash.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Task 718: Remediate Review Findings 20260928-201857 and Enhance Feedback Loop

**Issue**: [#718](https://github.com/dan-petty/devops-cli/issues/718)
**Status**: Done
**Milestone**: `v0.2.24`
**Priority**: `priority/p1-high`
**Scope**: `type/security`, `type/refactor`, `scope/review`, `priority/p1-high`

---

## 1. Description & Objectives

Remediate valid findings and systemic defects identified during review session `/workspaces/devops-cli/.data/reviews/20260928-201857`, increase review retries and incremental backoff for transient 4xx and 5xx HTTP gateway errors (such as Cloudflare 524 timeouts), eliminate Python 3.12+ invalid escape sequence `SyntaxWarning: "\w"` warnings across all AST parsing call sites and sandbox criteria execution, disarm tautological criteria commands from falsely auto-promoting findings, broaden anti-hallucination catalogs, harden subsystems against path traversal and socket leaks, update review and persona prompts, export review feedback dataset, and document calibration in self-improvement records.

### Key Deliverables Completed:
- [x] **HTTP 4xx/5xx Treatment & Review Retry Backoff**:
- Increased `DEFAULT_REVIEW_RETRY_ATTEMPTS` to 6 (from 3) in `src/devops_cli/config/defaults.py`.
- Tuned `DEFAULT_REVIEW_RETRY_MIN_BACKOFF` to 2.0s and `DEFAULT_REVIEW_RETRY_MAX_BACKOFF` to 60.0s.
- Replaced hardcoded `retries=3` in `ReviewPipelineOrchestrator` agent creation with `DEFAULT_REVIEW_RETRY_ATTEMPTS`.
- Refined `_clean_http_error_body` in `src/devops_cli/ai/client/base.py` to strip multi-line HTML error bodies into concise HTTP error summaries.
- [x] **Invalid Regex Escape Warnings Prevention (`SyntaxWarning: "\w"`)**:
- Added `("PYTHONWARNINGS", "ignore::SyntaxWarning")` to `CONST_HOST_SANDBOX_DEFAULT_ENV` in `src/devops_cli/config/constants.py`.
- Wrapped `ast.parse` in `warnings.catch_warnings()` suppressing `SyntaxWarning` across `src/devops_cli/ai/analyze/outlines.py`, `src/devops_cli/ai/analyze/symbols.py`, `src/devops_cli/ai/context_packer.py`, `src/devops_cli/ai/rag/chunker.py`, `src/devops_cli/ai/rag/metadata.py`, `src/devops_cli/ai/ast_stream.py`, `src/devops_cli/ai/ast/fallback.py`, `src/devops_cli/security/aibom.py`, and `src/devops_cli/security/reference_extractor.py`.
- Updated review prompts (`code_review_prompt.md`, `review.md`, `review_output_instruction.md`, `verify_finding_system.md`) and persona prompt templates to explicitly instruct models to use raw strings (`r'...'`) and double backslashes (`\\\\`) in verification criteria and code blocks.
- [x] **Tautological Criteria Auto-Promotion Prevention**:
- Hardened `_is_tautological_verification_command` in `src/devops_cli/ai/review/review_environment.py` to identify criteria commands that execute no assertions or failure conditions (e.g. pure module imports with prints), preventing auto-promotion of findings to verified status.
- [x] **Subsystem Hardening & Finding Remediation**:
- `src/devops_cli/commands/mcp.py`: Removed lazy `__getattr__` and `_LAZY_OBJECT_MAPPING` in favor of direct symbol imports.
- `src/devops_cli/commands/repos.py`: Replaced lazy `__getattr__` and `_LAZY_OBJECT_MAPPING` with direct symbol imports; added `validate_no_path_traversal` and `is_relative_to` checks on `repo.name` in `clone-org`.
- `src/devops_cli/k8s/service.py`: Replaced static `.tmp` file in `switch_context` with secure `tempfile.NamedTemporaryFile(delete=False, dir=parent)` with `0o600` permissions and atomic replacement in `try...finally`.
- `src/devops_cli/ai/rag/library_store.py`: Fixed `ensure_collection_exists` to return `True` when collection already exists.
- `src/devops_cli/watchers/live_resource.py`: Guarded against division-by-zero and CPU pegging in refresh rate calculation with `min(30, max(1, int(1.0 / max(0.01, self.interval_seconds))))`.
- `src/devops_cli/http/broker.py`: Ensured `close()` and `aclose()` always reset `_sync_client = None` and `_async_client = None`.
- `src/devops_cli/http/pool.py`: Added explicit `aclose_shared_clients()` helper and safe socket cleanup.
- `src/devops_cli/core/command_decorator.py`: Standardized `DevOpsCLIError` handler to consistently record `error_type`.
- `src/devops_cli/k8s/informer.py`: Handled both dictionary objects and K8s API model objects in `_normalize_event`.
- `src/devops_cli/argo/rollouts.py`: Narrowed exception handling in `_fetch_metric_value` to `(httpx2.HTTPError, ValueError, TypeError, KeyError)`.
- `src/devops_cli/ai/instruction_generator.py`: Narrowed exception handling in `parse_project_metadata` to `(tomllib.TOMLDecodeError, OSError)`.
- `src/devops_cli/commands/grafana.py`: Added `validate_no_path_traversal` to `dashboards_export`.
- `src/devops_cli/ai/review/exporter.py`: Ensured root equality and relative validation consistency in output path checks.
- `src/devops_cli/argo/gitops.py`: Added path traversal validation in `inspect_git_manifest_drift`.
- `src/devops_cli/telemetry/memory_profiler.py`: Wrapped `_exercise_http_pool` cleanup in `try...finally`; validated custom module and function identifiers with strict regex before import.
- `src/devops_cli/k8s/security_stream.py`: Masked secrets in `stderr_msg`.
- `src/devops_cli/models/argo.py`: Safely parsed integer `current_step` in `from_manifest()`.
- `src/devops_cli/ai/__init__.py`: Narrowed `ModuleNotFoundError` handling in `__getattr__` to the requested module name.
- [x] **Anti-Hallucination Catalog & Pre-Verification Expansion**:
- `src/devops_cli/ai/review/common_hallucinations.py`: Updated `_verify_secret_scanning_ground_truth` so identifier lookups (`getattr(..., "password", ...)` or `.get("password")`) are not mistaken for secret string literals.
- `src/devops_cli/ai/review/common_hallucinations.json`:
- Updated `HALLUCINATION-PEP758-EXCEPT` signature patterns to match `catches <A>, <B> but this syntax is invalid`.
- Added `HALLUCINATION-GRAPHQL-JSON-DUMPS` (GraphQL query interpolation using `json.dumps()` is safe escaping, not injection).
- Added `HALLUCINATION-EXAMPLE-COM-WEBHOOK` (RFC 2606 `example.com` webhook placeholder is compliant dummy URL).
- Added `HALLUCINATION-PROMETHEUS-TELEMETRY-METRIC` (standard telemetry enablement boolean gauge in `/metrics` is not an info leak).
- [x] **Calibration Records & Knowledge Documentation**:
- Added Calibration Record for Session `20260928-201857` to `docs/SELF_IMPROVEMENT.md`.
- [x] **Feedback Dataset Export**:
- Exported review session feedback dataset via `uv run devops review export-feedback`.
- [x] **Unit & Regression Testing with Structural Tuple Equality**:
- Added tests for retry configuration, regex warning suppression, tautological criteria detection, and security defenses.
- Consolidated linear test assertions into structural tuple equality checks (`assert (a, b) == (x, y)`).
- 100% pass across all 10 quality gates in `uv run devops ci`.
5 changes: 3 additions & 2 deletions src/devops_cli/ai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ def __getattr__(name: str) -> Any:
import importlib

return importlib.import_module(f"devops_cli.ai.{name}")
except ModuleNotFoundError:
pass
except ModuleNotFoundError as exc:
if exc.name != f"devops_cli.ai.{name}":
raise

if name in {
"AIClientError",
Expand Down
5 changes: 4 additions & 1 deletion src/devops_cli/ai/analyze/outlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import json
import logging
import re
import warnings
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Literal
Expand Down Expand Up @@ -249,7 +250,9 @@ def _extract_python_pseudocode_outline(content: str) -> list[str]:
"""Extract AST signatures and key statements directly from Python source code."""
lines: list[str] = []
try:
tree = ast.parse(content)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
tree = ast.parse(content)
for node in tree.body:
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
lines.extend(_extract_function_pseudocode(node))
Expand Down
5 changes: 4 additions & 1 deletion src/devops_cli/ai/analyze/symbols.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@
from __future__ import annotations

import ast
import warnings


def extract_python_source_symbols(content: str | None) -> set[str]:
"""Extract top-level and class member symbols from Python source code."""
if not content:
return set()
try:
tree = ast.parse(content)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
tree = ast.parse(content)
except SyntaxError, ValueError, RecursionError:
return set()

Expand Down
5 changes: 4 additions & 1 deletion src/devops_cli/ai/ast/fallback.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import ast
import re
import warnings
from typing import Any

from devops_cli.ai.ast.models import CodeSpan, PolyglotFileMap, PolyglotSymbol, SymbolKind
Expand Down Expand Up @@ -59,7 +60,9 @@ def _parse_py_class_members(cls_node: ast.ClassDef) -> list[PolyglotSymbol]:

def _parse_python_symbols(code: str) -> list[PolyglotSymbol]:
try:
tree = ast.parse(code)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
tree = ast.parse(code)
except Exception:
return []

Expand Down
5 changes: 4 additions & 1 deletion src/devops_cli/ai/ast_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import ast
import io
import tokenize
import warnings
from collections.abc import Iterator
from enum import StrEnum
from pathlib import Path
Expand Down Expand Up @@ -143,7 +144,9 @@ def stream_ast_symbols(source: str | Path) -> Iterator[ASTSymbol]:
else:
source_code = source
try:
tree = ast.parse(source_code)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
tree = ast.parse(source_code)
except SyntaxError:
return

Expand Down
2 changes: 1 addition & 1 deletion src/devops_cli/ai/client/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def _clean_http_error_body(raw_body: str) -> str:
if not raw_body:
return ""
clean = raw_body.strip()
if "<html" in clean.lower() or "<!doctype" in clean.lower():
if any(tag in clean.lower() for tag in ("<html", "<!doctype", "<head", "<body", "<div")):
title_match = re.search(r"<title[^>]*>(.*?)</title>", clean, re.IGNORECASE)
if title_match:
title_text = title_match.group(1).strip()
Expand Down
5 changes: 4 additions & 1 deletion src/devops_cli/ai/context_packer.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import ast
import bisect
import logging
import warnings
from collections.abc import Collection, Sequence
from pathlib import Path

Expand Down Expand Up @@ -409,7 +410,9 @@ def pack_code(
cfg = config or self.config
orig_tokens = count_tokens(code)
try:
tree = ast.parse(code)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
tree = ast.parse(code)
except SyntaxError:
return _handle_syntax_fallback(code, orig_tokens, cfg)

Expand Down
2 changes: 1 addition & 1 deletion src/devops_cli/ai/instruction_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def parse_project_metadata(repo_path: Path) -> ProjectMetadata:
project, name, description
)
dependencies, dev_dependencies = _extract_pyproject_deps(data)
except Exception as exc:
except (tomllib.TOMLDecodeError, OSError) as exc:
logger.debug("Failed parsing pyproject.toml at %s: %s", pyproject_file, exc)

has_devcontainer = (resolved_path / ".devcontainer" / "devcontainer.json").is_file() or (
Expand Down
5 changes: 4 additions & 1 deletion src/devops_cli/ai/rag/chunker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import logging
import mimetypes
import re
import warnings
from pathlib import Path

from devops_cli.ai.analyze.scanner import detect_language
Expand Down Expand Up @@ -309,7 +310,9 @@ def _chunk_python(
return []

try:
tree = ast.parse(content)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
tree = ast.parse(content)
except SyntaxError:
return self._chunk_line_window(
content, file_path, language="python", project_name=project_name
Expand Down
2 changes: 1 addition & 1 deletion src/devops_cli/ai/rag/library_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def ensure_collection_exists(self) -> bool:
return False
info = self.qdrant_client.get_collection_info(self.collection_name)
if info:
return False
return True

dim = self._resolve_dimension()
if hasattr(self.qdrant_client, "ensure_collection"):
Expand Down
9 changes: 7 additions & 2 deletions src/devops_cli/ai/rag/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import ast
import logging
import re
import warnings
from typing import Any

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -72,7 +73,9 @@ def extract_security_tags(content: str) -> list[str]:
def _extract_python_imports(content: str) -> list[str]:
"""Parse AST to extract imported module names from Python source."""
try:
tree = ast.parse(content)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
tree = ast.parse(content)
imports: list[str] = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
Expand Down Expand Up @@ -112,7 +115,9 @@ def extract_declarations(content: str, language: str) -> list[str]:

if lang_key.startswith("python") or lang_key == "py":
try:
tree = ast.parse(content)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
tree = ast.parse(content)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
declarations.append(node.name)
Expand Down
Loading
Loading