manatrix/pentest/decision_audit.py

pentest / decision_audit.py

pentest/decision_audit.py · 29.0 KB

"""
Structured Audit Logging for All AI Decisions

Provides an append-only, timestamped audit trail for every decision,
expert selection, action selection, and tool execution in the
penetration testing pipeline. Supports JSON/Markdown/HTML export
and human-review workflows.

Key components:
- AuditEntry: Immutable record for a single decision event
- DecisionAuditLog: Manager class for storing, querying, and exporting audits
"""

import gzip
import hashlib
import json
import logging
import os
import shutil
import time
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Dataclasses
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class AuditEntry:
    """Immutable audit record for a single decision or action event.

    All fields are set at construction and cannot be modified afterwards.
    ``entry_id`` is a UUID; ``timestamp`` is UTC. ``human_reviewed``
    indicates whether a human has reviewed and approved/rejected the entry.

    Attributes:
        entry_id: Unique identifier (UUID4) for this entry.
        timestamp: Unix timestamp (UTC) when the entry was created.
        decision_type: Category of decision (e.g. "expert_selection",
                        "action_selection", "tool_execution").
        context: Snapshot of relevant environment/state at decision time.
        reasoning: Textual explanation of why this decision was made.
        confidence: Confidence score associated with the decision [0,1].
        outcome: Outcome of the decision when known (None if pending).
        human_reviewed: Whether a human has reviewed this entry.
        metadata: Additional structured data (e.g. tool name, model used).
    """
    entry_id: str
    timestamp: float
    decision_type: str
    context: Dict[str, Any] = field(hash=False, compare=False)
    reasoning: str = ""
    confidence: float = 0.0
    outcome: Optional[Any] = field(default=None, hash=False, compare=False)
    human_reviewed: bool = False
    metadata: Dict[str, Any] = field(default_factory=dict, hash=False, compare=False)

    def to_dict(self) -> dict:
        """Serialize the entry to a plain dict (JSON-compatible)."""
        return {
            "entry_id": self.entry_id,
            "timestamp": self.timestamp,
            "timestamp_iso": datetime.fromtimestamp(
                self.timestamp, tz=timezone.utc
            ).isoformat(),
            "decision_type": self.decision_type,
            "context": self.context,
            "reasoning": self.reasoning,
            "confidence": self.confidence,
            "outcome": self.outcome,
            "human_reviewed": self.human_reviewed,
            "metadata": self.metadata,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "AuditEntry":
        """Reconstruct an AuditEntry from a dict (e.g. loaded from JSON)."""
        return cls(
            entry_id=data["entry_id"],
            timestamp=float(data["timestamp"]),
            decision_type=data["decision_type"],
            context=data.get("context", {}),
            reasoning=data.get("reasoning", ""),
            confidence=float(data.get("confidence", 0.0)),
            outcome=data.get("outcome"),
            human_reviewed=bool(data.get("human_reviewed", False)),
            metadata=data.get("metadata", {}),
        )


# ---------------------------------------------------------------------------
# DecisionAuditLog
# ---------------------------------------------------------------------------

class DecisionAuditLog:
    """Append-only audit log for all AI-driven decisions.

    Stores entries as newline-delimited JSON (NDJSON) in a dedicated
    directory, one file per day, with optional gzip compression for
    older files. Supports querying, human-review workflows, and
    structured export to JSON, Markdown, or HTML.

    Usage::

        audit = DecisionAuditLog(log_dir="logs/audit")
        entry_id = audit.log_expert_selection(query, selected, reasoning, 0.85)
        audit.mark_reviewed(entry_id, "Approved - valid target scope")
        unreviewed = audit.get_unreviewed(limit=50)
        audit.export_audit("report.json", format="json")
    """

    # File naming convention.
    _FILENAME_FORMAT = "audit_%Y%m%d.ndjson"
    # Files older than this (in seconds) are eligible for gzip compression.
    _COMPRESS_AGE_SECONDS = 86400  # 1 day
    # Size (bytes) at which a single NDJSON file is rotated early.
    _MAX_FILE_BYTES = 10 * 1024 * 1024  # 10 MB

    def __init__(
        self,
        log_dir: str,
        compress: bool = True,
        max_file_bytes: Optional[int] = None,
    ) -> None:
        """Initialize the audit log.

        Args:
            log_dir: Directory where NDJSON audit files will be stored.
                     Created if it does not exist.
            compress: Whether to gzip-compress NDJSON files older than 1 day.
            max_file_bytes: Maximum size of a single NDJSON file before
                            rotation. Defaults to 10 MB.
        """
        self._log_dir = Path(log_dir)
        self._compress = compress
        self._max_file_bytes = max_file_bytes or self._MAX_FILE_BYTES
        self._log_dir.mkdir(parents=True, exist_ok=True)

        # In-memory index of unreviewed entries for fast lookups.
        self._unreviewed_ids: set = set()

        # Load existing unreviewed IDs to avoid losing state across restarts.
        self._refresh_unreviewed_index()

        logger.info("DecisionAuditLog initialized at '%s'", self._log_dir)

    # ------------------------------------------------------------------
    # Core logging methods
    # ------------------------------------------------------------------

    def log_decision(self, entry: AuditEntry) -> str:
        """Write an arbitrary AuditEntry to the log.

        This is the foundational append operation; all other logging
        methods ultimately call this.

        Args:
            entry: The AuditEntry to log.

        Returns:
            The entry's ``entry_id``.
        """
        path = self._current_path()

        # Serialize without trailing newline (we add it in the loop).
        line = json.dumps(entry.to_dict(), ensure_ascii=False) + "\n"

        with path.open("a", encoding="utf-8") as fh:
            fh.write(line)

        if not entry.human_reviewed:
            self._unreviewed_ids.add(entry.entry_id)

        logger.debug(
            "Audit entry logged: [%s] %s",
            entry.entry_id,
            entry.decision_type,
        )
        return entry.entry_id

    def log_expert_selection(
        self,
        query: Any,
        selected_expert: Any,
        reasoning: str,
        confidence: float,
        metadata: Optional[dict] = None,
    ) -> str:
        """Log a decision to select a specific expert system.

        Args:
            query: The query or task that triggered expert selection.
            selected_expert: The expert object/name that was selected.
            reasoning: Why this expert was chosen.
            confidence: Confidence score for the selection [0,1].
            metadata: Additional context (e.g. expert type, alternatives).

        Returns:
            The entry ID of the logged audit entry.
        """
        if metadata is None:
            metadata = {}

        # Serialize query/expert to JSON-safe types.
        context: Dict[str, Any] = {
            "query_type": type(query).__name__,
            "query_summary": _truncate(_safe_serialize(query), 500),
            "selected_expert": _safe_serialize(selected_expert),
            "alternatives": metadata.get("alternatives", []),
        }
        metadata.setdefault("expert_selection", True)

        entry = AuditEntry(
            entry_id=str(uuid.uuid4()),
            timestamp=time.time(),
            decision_type="expert_selection",
            context=context,
            reasoning=reasoning,
            confidence=confidence,
            metadata=metadata,
        )
        return self.log_decision(entry)

    def log_action_selection(
        self,
        state: Any,
        action: Any,
        reasoning: str,
        confidence: float,
        metadata: Optional[dict] = None,
    ) -> str:
        """Log a decision to select a specific attack action.

        Args:
            state: Current environment state (or a summary thereof).
            action: The selected action dict/object.
            reasoning: Why this action was chosen over alternatives.
            confidence: Confidence score for the action selection [0,1].
            metadata: Additional context (e.g. action alternatives, risk level).

        Returns:
            The entry ID of the logged audit entry.
        """
        if metadata is None:
            metadata = {}

        context: Dict[str, Any] = {
            "state_summary": _truncate(_safe_serialize(state), 500),
            "selected_action": _safe_serialize(action),
            "alternatives": metadata.get("alternatives", []),
            "action_risk": metadata.get("risk_level", "unknown"),
        }
        metadata.setdefault("action_selection", True)

        entry = AuditEntry(
            entry_id=str(uuid.uuid4()),
            timestamp=time.time(),
            decision_type="action_selection",
            context=context,
            reasoning=reasoning,
            confidence=confidence,
            metadata=metadata,
        )
        return self.log_decision(entry)

    def log_tool_execution(
        self,
        tool: Any,
        params: Any,
        reasoning: str,
        result: Any,
        metadata: Optional[dict] = None,
    ) -> str:
        """Log a decision to execute a specific tool.

        Args:
            tool: The tool being executed (name, object, or module path).
            params: Parameters passed to the tool.
            reasoning: Why this tool was selected.
            result: Tool execution result (can be an exception for failures).
            metadata: Additional context (e.g. execution time, target host).

        Returns:
            The entry ID of the logged audit entry.
        """
        if metadata is None:
            metadata = {}

        success = metadata.get("success", _is_success_result(result))
        context: Dict[str, Any] = {
            "tool_name": _safe_serialize(tool),
            "params_summary": _truncate(_safe_serialize(params), 500),
            "result_summary": _truncate(_safe_serialize(result), 500),
            "success": success,
            "execution_time_sec": metadata.get("execution_time_sec"),
        }
        metadata.setdefault("tool_execution", True)

        entry = AuditEntry(
            entry_id=str(uuid.uuid4()),
            timestamp=time.time(),
            decision_type="tool_execution",
            context=context,
            reasoning=reasoning,
            confidence=metadata.get("confidence", 0.0),
            outcome=("success" if success else "failure"),
            metadata=metadata,
        )
        return self.log_decision(entry)

    # ------------------------------------------------------------------
    # Query and review
    # ------------------------------------------------------------------

    def query_audit(
        self,
        filters: Optional[dict] = None,
    ) -> List[AuditEntry]:
        """Query the audit log with optional filters.

        Supported filter keys:
            - ``decision_type``: Exact match on decision_type.
            - ``from_timestamp``: Include entries with timestamp >= this.
            - ``to_timestamp``: Include entries with timestamp <= this.
            - ``min_confidence``: Include entries with confidence >= this.
            - ``max_confidence``: Include entries with confidence <= this.
            - ``human_reviewed``: Boolean filter.
            - ``outcome``: Exact match on outcome.
            - ``entry_ids``: List of entry IDs to include.
            - ``metadata_key``: Include entries whose metadata contains
                                ``metadata_key`` (value ignored).
            - ``reasoning_contains``: Substring match on reasoning field.

        Args:
            filters: Dictionary of filter criteria.

        Returns:
            List of matching AuditEntry objects, ordered by timestamp.
        """
        if filters is None:
            filters = {}

        results: List[AuditEntry] = []
        decision_type = filters.get("decision_type")
        from_ts = filters.get("from_timestamp", 0.0)
        to_ts = filters.get("to_timestamp", float("inf"))
        min_conf = filters.get("min_confidence", 0.0)
        max_conf = filters.get("max_confidence", 1.0)
        human_reviewed_filter = filters.get("human_reviewed")
        outcome_filter = filters.get("outcome")
        entry_ids_filter = filters.get("entry_ids")
        reasoning_substr = filters.get("reasoning_contains", "").lower()
        check_metadata_key = "metadata_key" in filters

        for path in self._iter_audit_files(from_ts, to_ts):
            for raw in _iter_ndjson(path):
                entry = _safe_deserialize_entry(raw)
                if entry is None:
                    continue

                # Apply filters.
                if decision_type and entry.decision_type != decision_type:
                    continue
                if not (from_ts <= entry.timestamp <= to_ts):
                    continue
                if not (min_conf <= entry.confidence <= max_conf):
                    continue
                if human_reviewed_filter is not None:
                    if entry.human_reviewed != human_reviewed_filter:
                        continue
                if outcome_filter and entry.outcome != outcome_filter:
                    continue
                if entry_ids_filter and entry.entry_id not in entry_ids_filter:
                    continue
                if reasoning_substr and reasoning_substr not in entry.reasoning.lower():
                    continue
                if check_metadata_key:
                    if filters["metadata_key"] not in entry.metadata:
                        continue

                results.append(entry)

        results.sort(key=lambda e: e.timestamp)
        logger.debug("Query returned %d entries (filters=%s)", len(results), filters)
        return results

    def get_unreviewed(
        self,
        limit: int = 100,
        decision_type: Optional[str] = None,
    ) -> List[AuditEntry]:
        """Return entries pending human review.

        Args:
            limit: Maximum number of entries to return.
            decision_type: Optional filter to only unreviewed entries
                           of this decision type.

        Returns:
            List of unreviewed AuditEntry objects, ordered by timestamp.
        """
        filters: Dict[str, Any] = {
            "human_reviewed": False,
            "entry_ids": list(self._unreviewed_ids),
        }
        if decision_type:
            filters["decision_type"] = decision_type

        return self.query_audit(filters)[:limit]

    def mark_reviewed(
        self,
        entry_id: str,
        human_feedback: str,
    ) -> None:
        """Mark an entry as human-reviewed and append feedback.

        The original entry is preserved (append-only); the review
        record is stored in a separate review log. If the entry is
        already reviewed, the existing review entry is overwritten.

        Args:
            entry_id: ID of the entry to mark as reviewed.
            human_feedback: Human reviewer's feedback/decision.

        Raises:
            ValueError: If no entry with the given ID exists.
        """
        # Locate and load the entry.
        entries = self.query_audit({"entry_ids": [entry_id]})
        if not entries:
            raise ValueError(f"No audit entry found with ID '{entry_id}'")

        entry = entries[0]

        # Write review record to a separate append-only review log.
        review_path = self._log_dir / f"reviews_{entry_id[:8]}.jsonl"
        review_record = {
            "entry_id": entry_id,
            "reviewed_at": time.time(),
            "reviewed_at_iso": datetime.now(timezone.utc).isoformat(),
            "feedback": human_feedback,
            "previous_outcome": entry.outcome,
        }
        with review_path.open("a", encoding="utf-8") as fh:
            fh.write(json.dumps(review_record, ensure_ascii=False) + "\n")

        # Update the unreviewed index.
        self._unreviewed_ids.discard(entry_id)

        logger.info(
            "Entry %s marked as reviewed: '%s'",
            entry_id,
            _truncate(human_feedback, 80),
        )

    # ------------------------------------------------------------------
    # Export
    # ------------------------------------------------------------------

    def export_audit(
        self,
        output_path: str,
        format: str = "json",
        filters: Optional[dict] = None,
        include_context: bool = True,
    ) -> str:
        """Export audit entries to a file.

        Args:
            output_path: Path for the output file.
            format: Output format: "json", "markdown", or "html".
            filters: Optional query filters (same as query_audit).
            include_context: Whether to include full context in the output.

        Returns:
            Absolute path to the generated file.

        Raises:
            ValueError: If format is not supported.
            IOError: If the file cannot be written.
        """
        entries = self.query_audit(filters or {})

        if not entries:
            logger.warning("No entries match the given filters; export will be empty.")

        output_path = str(Path(output_path).resolve())

        if format == "json":
            self._export_json(output_path, entries, include_context)
        elif format == "markdown":
            self._export_markdown(output_path, entries, include_context)
        elif format == "html":
            self._export_html(output_path, entries, include_context)
        else:
            raise ValueError(
                f"Unsupported export format '{format}'. "
                "Supported: json, markdown, html"
            )

        logger.info(
            "Exported %d audit entries to '%s' (format=%s)",
            len(entries),
            output_path,
            format,
        )
        return output_path

    # ------------------------------------------------------------------
    # Statistics
    # ------------------------------------------------------------------

    def get_audit_stats(self) -> dict:
        """Compute aggregate statistics over all audit entries.

        Returns:
            A dict containing counts, averages, and breakdowns.
        """
        all_entries = self.query_audit({})
        total = len(all_entries)

        if total == 0:
            return {
                "total_entries": 0,
                "entries_by_type": {},
                "reviewed_count": 0,
                "unreviewed_count": 0,
                "avg_confidence": 0.0,
                "entries_by_outcome": {},
                "date_range": None,
            }

        by_type: Dict[str, int] = {}
        by_outcome: Dict[str, int] = {}
        confidence_sum = 0.0
        reviewed_count = 0
        timestamps = []

        for entry in all_entries:
            by_type[entry.decision_type] = by_type.get(entry.decision_type, 0) + 1
            confidence_sum += entry.confidence
            timestamps.append(entry.timestamp)
            if entry.human_reviewed:
                reviewed_count += 1
            if entry.outcome is not None:
                by_outcome[str(entry.outcome)] = by_outcome.get(str(entry.outcome), 0) + 1

        return {
            "total_entries": total,
            "entries_by_type": by_type,
            "reviewed_count": reviewed_count,
            "unreviewed_count": total - reviewed_count,
            "review_coverage_pct": round(reviewed_count / total * 100, 2),
            "avg_confidence": round(confidence_sum / total, 4),
            "entries_by_outcome": by_outcome,
            "date_range": {
                "earliest": datetime.fromtimestamp(min(timestamps), tz=timezone.utc).isoformat(),
                "latest": datetime.fromtimestamp(max(timestamps), tz=timezone.utc).isoformat(),
            },
        }

    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------

    def _current_path(self) -> Path:
        """Return the NDJSON file path for today (rotated if over size limit)."""
        today_path = self._log_dir / datetime.now().strftime(self._FILENAME_FORMAT)

        if today_path.exists() and today_path.stat().st_size >= self._max_file_bytes:
            # Rotate to a timestamped file.
            rotated = (
                self._log_dir
                / f"audit_{datetime.now():%Y%m%d_%H%M%S}.ndjson"
            )
            shutil.move(str(today_path), str(rotated))
            logger.info("Audit file rotated to '%s'", rotated.name)

        return today_path

    def _iter_audit_files(
        self,
        from_timestamp: float,
        to_timestamp: float,
    ) -> List[Path]:
        """Yield NDJSON file paths whose date range may contain the query range."""
        files: List[Path] = []

        # Scan all .ndjson and .ndjson.gz files in the log directory.
        for ext in ("*.ndjson", "*.ndjson.gz"):
            files.extend(self._log_dir.glob(ext))

        # Filter to files whose name suggests a relevant date range.
        # Simple heuristic: accept all files (full scan).
        return sorted(files)

    def _refresh_unreviewed_index(self) -> None:
        """Rebuild the in-memory unreviewed entry ID set from all audit files."""
        self._unreviewed_ids.clear()

        for path in self._iter_audit_files(0.0, float("inf")):
            for raw in _iter_ndjson(path):
                entry = _safe_deserialize_entry(raw)
                if entry is not None and not entry.human_reviewed:
                    self._unreviewed_ids.add(entry.entry_id)

        logger.debug(
            "Unreviewed index rebuilt: %d unreviewed entries",
            len(self._unreviewed_ids),
        )

    def _export_json(
        self,
        path: str,
        entries: List[AuditEntry],
        include_context: bool,
    ) -> None:
        """Write entries as a JSON array."""
        records = []
        for e in entries:
            d = e.to_dict()
            if not include_context:
                d.pop("context", None)
            records.append(d)

        with open(path, "w", encoding="utf-8") as fh:
            json.dump(
                {"exported_at": datetime.now(timezone.utc).isoformat(),
                 "total_entries": len(entries),
                 "entries": records},
                fh,
                indent=2,
                ensure_ascii=False,
            )

    def _export_markdown(
        self,
        path: str,
        entries: List[AuditEntry],
        include_context: bool,
    ) -> None:
        """Write entries as a Markdown table."""
        lines: List[str] = [
            "# Decision Audit Log",
            "",
            f"**Exported:** {datetime.now(timezone.utc).isoformat()}",
            f"**Total entries:** {len(entries)}",
            "",
            "## Entries",
            "",
            "| Timestamp | Type | Confidence | Outcome | Human Reviewed |",
            "|---|---|---|---|---|",
        ]

        for e in entries:
            ts = datetime.fromtimestamp(e.timestamp, tz=timezone.utc).strftime(
                "%Y-%m-%d %H:%M:%S UTC"
            )
            reasoning_preview = _truncate(e.reasoning.replace("\n", " "), 60)
            outcome_str = str(e.outcome) if e.outcome is not None else "-"
            lines.append(
                f"| {ts} | {e.decision_type} | {e.confidence:.2f} "
                f"| {outcome_str} | {'Yes' if e.human_reviewed else 'No'} |"
            )
            if include_context and e.context:
                lines.append(f"  **Context:** {json.dumps(e.context)[:200]}")
            if reasoning_preview:
                lines.append(f"  **Reasoning:** {reasoning_preview}")
            lines.append("")

        with open(path, "w", encoding="utf-8") as fh:
            fh.write("\n".join(lines))

    def _export_html(
        self,
        path: str,
        entries: List[AuditEntry],
        include_context: bool,
    ) -> None:
        """Write entries as a self-contained HTML report."""
        rows: List[str] = []
        for e in entries:
            ts = datetime.fromtimestamp(e.timestamp, tz=timezone.utc).strftime(
                "%Y-%m-%d %H:%M:%S UTC"
            )
            ctx_json = json.dumps(e.context, ensure_ascii=False) if include_context else ""
            confidence_bar = _confidence_bar(e.confidence)

            rows.append(
                f'<tr class="{"unreviewed" if not e.human_reviewed else ""}">'
                f'<td>{ts}</td>'
                f'<td><span class="badge">{e.decision_type}</span></td>'
                f'<td>{confidence_bar} {e.confidence:.2f}</td>'
                f'<td>{e.outcome or "-"}</td>'
                f'<td>{"Yes" if e.human_reviewed else "No"}</td>'
                f'<td>{_escape_html(e.reasoning[:120])}</td>'
                f'</tr>'
            )

        rows_str = "\n".join(rows)

        html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Decision Audit Log</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 2rem; background:#f9f9f9; }}
h1 {{ color: #333; }}
table {{ border-collapse: collapse; width: 100%; background: #fff; }}
th {{ background: #2c3e50; color:#fff; padding:8px; text-align:left; }}
td {{ padding:6px 8px; border-bottom:1px solid #eee; }}
tr.unreviewed td {{ background:#fff3cd; }}
.badge {{ background:#3498db; color:#fff; padding:2px 6px; border-radius:3px; font-size:0.85em; }}
.conf-bar {{ display:inline-block; width:60px; height:8px; background:#ddd; border-radius:4px; }}
.conf-fill {{ display:inline-block; height:8px; border-radius:4px; background:#27ae60; }}
</style>
</head>
<body>
<h1>Decision Audit Log</h1>
<p><strong>Exported:</strong> {datetime.now(timezone.utc).isoformat()} &nbsp;
<strong>Total entries:</strong> {len(entries)}</p>
<table>
<thead>
<tr>
<th>Timestamp</th><th>Type</th><th>Confidence</th><th>Outcome</th>
<th>Reviewed</th><th>Reasoning</th>
</tr>
</thead>
<tbody>
{rows_str}
</tbody>
</table>
</body>
</html>"""

        with open(path, "w", encoding="utf-8") as fh:
            fh.write(html_content)


# ---------------------------------------------------------------------------
# Module-level utilities
# ---------------------------------------------------------------------------

def _iter_ndjson(path: Path):
    """Yield parsed JSON objects from an NDJSON or gzipped NDJSON file."""
    opener = gzip.open if path.suffix == ".gz" else open
    try:
        with opener(path, "rt", encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if not line:
                    continue
                try:
                    yield json.loads(line)
                except json.JSONDecodeError:
                    logger.warning("Malformed JSON line in '%s', skipping", path)
                    continue
    except Exception as exc:
        logger.error("Failed to read audit file '%s': %s", path, exc)


def _safe_deserialize_entry(raw: dict) -> Optional[AuditEntry]:
    """Safely construct an AuditEntry from a raw dict, or None on error."""
    try:
        return AuditEntry.from_dict(raw)
    except (KeyError, TypeError, ValueError) as exc:
        logger.warning("Malformed audit entry, skipping: %s (exc=%s)", raw, exc)
        return None


def _safe_serialize(obj: Any) -> str:
    """Attempt to serialize an arbitrary object to JSON, fallback to repr."""
    try:
        return json.dumps(obj, ensure_ascii=False, default=str)
    except (TypeError, ValueError):
        return repr(obj)


def _truncate(text: str, max_len: int) -> str:
    """Truncate a string to max_len characters, appending '...' if cut."""
    if len(text) <= max_len:
        return text
    return text[: max_len - 3] + "..."


def _is_success_result(result: Any) -> bool:
    """Heuristic to determine if a tool result is a success."""
    if result is None:
        return False
    if isinstance(result, bool):
        return result
    if isinstance(result, dict):
        if result.get("success") is True or result.get("error") is None:
            return True
    if isinstance(result, Exception):
        return False
    return True


def _escape_html(text: str) -> str:
    """Basic HTML escaping."""
    return (
        text.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )


def _confidence_bar(confidence: float) -> str:
    """Return an inline HTML confidence bar snippet."""
    pct = int(confidence * 100)
    color = "#27ae60" if confidence >= 0.7 else "#f39c12" if confidence >= 0.4 else "#e74c3c"
    return (
        f'<div class="conf-bar"><div class="conf-fill" '
        f'style="width:{pct}%;background:{color}"></div></div>'
    )

← 返回文件树 · 在 GitHub 上查看