Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

docs: add comprehensive deep-dive documentation for AI subsystems

rcourtmanfa1b74792e3b
diff --git a/docs/AI.md b/docs/AI.md
index 2385e2133a..79909c3d59 100644
--- a/docs/AI.md
+++ b/docs/AI.md
@@ -2,58 +2,75 @@
Pulse Patrol is available to everyone with BYOK (your own AI provider). Pulse Pro unlocks auto-fix and advanced analysis. Learn more at <https://pulserelay.pro> or see the technical overview in [PULSE_PRO.md](PULSE_PRO.md).
-## What Patrol Actually Does (Technical)
+---
-Patrol is a scheduled analysis pipeline that builds a rich, system-wide snapshot and produces actionable findings.
+## Overview
-**Inputs (real data, not guesses):**
-- Live state: nodes, VMs/CTs, storages, backups, docker, kubernetes.
-- Recent metrics history (trends + rate of change).
-- Alert state and recent failures.
-- Diagnostics (connectivity, permissions, agent status).
+Pulse includes two AI-powered systems:
-**Enrichment:**
-- Normalizes metrics across resource types.
-- Applies context rules (e.g., ignore idle test nodes, de-noise transient blips).
-- Correlates related issues to avoid duplicate noise.
+1. **Pulse Assistant** — An interactive chat interface for ad-hoc troubleshooting, investigations, and infrastructure control.
+2. **Pulse Patrol** — A scheduled, context-aware analysis service that continuously monitors your infrastructure, learns what's normal, predicts issues, and generates actionable findings.
-**Outputs:**
-- Findings with severity, category, and remediation hints.
-- Summary stats for coverage and risk level.
-- Optional auto-fix and remediation workflows (Pro).
+Both systems are built on the same tool-driven architecture where the LLM acts as a proposer and Go code enforces safety gates.
-## Why Patrol Is Different From Traditional Alerts
+### Not Just Another Chatbot
-Alerts are threshold-based and narrow. Patrol is context-based and cross-system.
+Pulse Assistant is a **protocol-driven, safety-gated agentic system** that:
-- **Alerts**: "Disk > 90%."
-- **Patrol**: "ZFS pool is 86% but trending +4%/day; projected to hit 95% within a week. Largest consumer is datastore X. Recommend prune or expand."
+- **Proactively gathers context** — understands resources before you ask (context prefetcher)
+- **Learns within sessions** — extracts and caches facts to avoid redundant queries (knowledge accumulator)
+- **Enforces workflow invariants** — FSM prevents dangerous state transitions
+- **Supports parallel tool execution** — efficient batch operations with concurrency control
+- **Detects and prevents hallucinations** — phantom execution detection
+- **Auto-recovers from errors** — structured error envelopes enable self-correction
-## Examples of Patrol Findings (Realistic)
+📖 **For a deep technical dive into the Assistant architecture, see [architecture/pulse-assistant-deep-dive.md](architecture/pulse-assistant-deep-dive.md).**
-- Backup jobs succeeded but datastore usage jumped 20% since last run.
-- Node health is OK but cluster clock drift is growing.
-- Multiple VMs in the same storage pool are all retrying snapshots.
-- Docker host is healthy but containers in one stack are flapping.
+### Not Just Another Alerting System
-## Controls and Limits
+Pulse Patrol is a **multi-layered intelligence platform** that:
-- **Schedule**: from 10 minutes to 7 days (default 6 hours).
-- **Scope**: only configured resources and connected agents.
-- **Safety**: command execution remains disabled by default.
-- **Cost control**: BYOK only — use provider limits and budgets to control spend.
+- **Learns** what's normal for your environment (baseline engine)
+- **Predicts** issues before they become critical (pattern detection + forecasting)
+- **Correlates** events across your entire infrastructure (root cause analysis)
+- **Remembers** past incidents and successful remediations (incident memory)
+- **Investigates** issues autonomously when configured (investigation orchestrator)
+- **Verifies** fixes and tracks remediation effectiveness (verification loops)
-## Privacy
+All while running entirely on your infrastructure with BYOK for complete privacy.
-Patrol runs on your server and only sends the minimal context needed for analysis to the configured provider (when AI is enabled). No telemetry is sent to Pulse by default.
+📖 **For a deep technical dive into the intelligence subsystems, see [architecture/pulse-patrol-deep-dive.md](architecture/pulse-patrol-deep-dive.md).**
+
+See [architecture/pulse-assistant.md](architecture/pulse-assistant.md) for the original safety architecture documentation.
+
+---
-Pulse AI adds an optional assistant for troubleshooting and proactive monitoring. It is **off by default** and can be enabled per instance.
+## Pulse Patrol
-## What Makes AI Patrol Different
+Patrol is a scheduled analysis pipeline that builds a rich, system-wide snapshot and produces actionable findings.
+
+### How Patrol Works
-Unlike chatting with a generic AI where you manually describe your infrastructure, Patrol runs automatically and sees **your entire infrastructure at once** - every node, VM, container, storage pool, backup job, and Kubernetes cluster. It's not just a static checklist; it's an LLM analyzing real-time data enriched with historical context.
+```
+Scheduled/Event Trigger
+ │
+ ▼
+buildSeedContext() ── infrastructure snapshot
+ │
+ ▼
+LLM analysis (with tools) ← pulse_storage, pulse_metrics, pulse_alerts, etc.
+ │
+ ▼
+DetectSignals() ── deterministic signal detection from tool outputs
+ │
+ ▼
+createFinding() ── validated, deduplicated findings stored
+ │
+ ▼ (if configured)
+MaybeInvestigateFinding() ── automatic investigation + remediation
+```
-### Context Patrol Receives (That Generic LLMs Can't See)
+### What Patrol Sees
Every patrol run passes the LLM comprehensive context about your environment:
@@ -68,22 +85,36 @@ Every patrol run passes the LLM comprehensive context about your environment:
| **Ceph** | Cluster health, OSD states, PG status |
| **Agent Hosts** | Load averages, memory, disk, RAID status, temperatures |
-### Enriched Context (The Real Differentiator)
+### Enriched Context
-Beyond raw metrics, Patrol enriches the context with intelligence that transforms raw data into actionable insights:
+Beyond raw metrics, Patrol enriches the context with intelligence:
-- **Trend analysis** - 24h and 7d patterns showing `growing`, `stable`, `declining`, or `volatile` behavior
-- **Learned baselines** - Z-score anomaly detection based on what's *normal for your environment*
-- **Capacity predictions** - "Storage pool will be full in 12 days at current growth rate"
-- **Infrastructure changes** - Detected config changes, VM migrations, new deployments
-- **Resource correlations** - Pattern detection across related resources (e.g., containers on same host)
-- **User notes** - Your annotations explaining expected behavior ("runs hot for transcoding")
-- **Dismissed findings** - Respects your feedback and suppressed alerts
-- **Incident memory** - Learns from past investigations and successful remediations
+- **Trend analysis** — 24h and 7d patterns showing `growing`, `stable`, `declining`, or `volatile` behavior
+- **Learned baselines** — Z-score anomaly detection based on what's *normal for your environment*
+- **Capacity predictions** — "Storage pool will be full in 12 days at current growth rate"
+- **Infrastructure changes** — Detected config changes, VM migrations, new deployments
+- **Resource correlations** — Pattern detection across related resources
+- **User notes** — Your annotations explaining expected behavior
+- **Dismissed findings** — Respects your feedback and suppressed alerts
+- **Incident memory** — Learns from past investigations and successful remediations
-### Examples of What Patrol Catches
+### Deterministic Signal Detection
+
+Patrol doesn't rely solely on LLM judgment. It parses tool call outputs and fires deterministic signals for known problems:
-Because it's an LLM with full context, Patrol catches issues that static threshold-based alerting misses:
+| Signal Type | Trigger | Default Threshold |
+|------------|---------|-------------------|
+| `smart_failure` | SMART health status not OK/PASSED | N/A |
+| `high_cpu` | Average CPU usage | 70% |
+| `high_memory` | Average memory usage | 80% |
+| `high_disk` | Storage pool usage | 75% (warning), 95% (critical) |
+| `backup_failed` | Recent backup task with error status | Within 48h |
+| `backup_stale` | No backup completed for VM/CT | 48+ hours |
+| `active_alert` | Critical/warning alert in list | N/A |
+
+Thresholds can be configured via alert settings to match user-defined values.
+
+### Examples of What Patrol Catches
| Issue | Severity | Example |
|-------|----------|---------|
@@ -95,9 +126,7 @@ Because it's an LLM with full context, Patrol catches issues that static thresho
| **Storage issues** | Critical | PBS datastore errors, ZFS pool degraded |
| **Ceph problems** | Warning/Critical | Degraded OSDs, unhealthy PGs |
| **Kubernetes issues** | Warning | Pods stuck in Pending/CrashLoopBackOff |
-| **Restart loops** | Warning | VMs that keep restarting without errors |
-| **Clock drift** | Warning | Node time drift affecting Ceph/HA |
-| **Unusual patterns** | Varies | Any anomaly the LLM identifies as unusual for your setup |
+| **SMART failures** | Critical | Disk health check failed |
### What Patrol Ignores (by design)
@@ -111,55 +140,156 @@ Patrol is **intentionally conservative** to avoid noise:
> **Philosophy**: If a finding wouldn't be worth waking someone up at 3am, Patrol won't create it.
-## Features
+### Finding Severity
+
+- **Critical**: Immediate attention required (service down, data at risk)
+- **Warning**: Should be addressed soon (disk filling, backup stale)
+
+Note: `info` and `watch` level findings are filtered out to reduce noise.
+
+### Managing Findings
+
+Findings can be managed via the UI or API:
+
+- **Get help**: Chat with AI to troubleshoot the issue
+- **Resolve**: Mark as fixed (finding will reappear if the issue resurfaces)
+- **Dismiss**: Mark as expected behavior (creates suppression rule)
+
+Dismissed and resolved findings persist across Pulse restarts.
+
+---
+
+## Autonomy Levels
+
+Patrol supports three autonomy modes that control how much action it can take:
+
+| Mode | Behavior | License |
+|------|----------|---------|
+| **Monitor** | Detect issues only. No investigation or fixes. | Free (BYOK) |
+| **Investigate** | Investigates findings and proposes fixes. All fixes require approval before execution. | Free (BYOK) |
+| **Auto-fix** | Automatically fixes issues and verifies results. Critical findings still require approval by default. | Pro |
+
+### Investigation Flow
+
+When a finding is created in Investigate or Auto-fix mode:
-- **Interactive chat**: Ask questions about current cluster state and get AI-assisted troubleshooting.
-- **Patrol**: Background checks periodically (default: 6 hours) that generate findings. Interval is configurable from 10 minutes to 7 days, or set to 0 to disable.
-- **Alert-triggered analysis (Pro)**: Optional token-efficient analysis when alerts fire.
-- **Kubernetes AI analysis (Pro)**: Deep cluster analysis beyond basic monitoring.
-- **Command execution**: When enabled, AI can run commands via connected agents.
-- **Finding management**: Dismiss, resolve, or suppress findings to prevent recurrence.
-- **Cost tracking**: Tracks token usage and supports monthly budget limits.
+```
+Finding created
+ │
+ ▼
+MaybeInvestigateFinding()
+ │
+ ├─ Has orch + chatService?
+ │ │
+ │ ▼
+ │ InvestigateFinding()
+ │ │
+ │ ▼
+ │ Create chat session
+ │ │
+ │ ▼
+ │ AI analysis (with tools)
+ │ │
+ │ ▼
+ │ [Fix proposed?] ──Yes──► Queue approval (or auto-execute in full mode)
+ │ │
+ │ No
+ │ ▼
+ │ Update finding with outcome
+ │
+ └─ Skip investigation
+```
+
+### Investigation Configuration
+
+| Setting | Default | Description |
+|---------|---------|-------------|
+| `MaxTurns` | 15 | Maximum agentic turns per investigation |
+| `Timeout` | 10 min | Maximum duration per investigation |
+| `MaxConcurrent` | 3 | Maximum concurrent investigations |
+| `MaxAttemptsPerFinding` | 3 | Maximum investigation attempts per finding |
+| `CooldownDuration` | 1 hour | Cooldown before re-investigating |
+| `TimeoutCooldownDuration` | 10 min | Shorter cooldown for timeout failures |
+| `VerificationDelay` | 30 sec | Wait before verifying fix |
-Alert-triggered analysis runs attach a timeline event to the alert, so investigations remain auditable alongside acknowledgements and remediation steps.
+### Investigation Outcomes
-> **License note**: Kubernetes AI analysis is gated by the `kubernetes_ai` Pulse Pro feature.
+| Outcome | Meaning |
+|---------|---------|
+| `resolved` | Issue resolved during investigation |
+| `fix_queued` | Fix proposed, awaiting approval |
+| `fix_executed` | Fix auto-executed successfully |
+| `fix_failed` | Fix attempted but failed |
+| `fix_verified` | Fix worked, issue confirmed resolved |
+| `fix_verification_failed` | Fix ran but issue persists |
+| `needs_attention` | Requires human intervention |
+| `cannot_fix` | Issue cannot be automatically fixed |
+| `timed_out` | Investigation timed out (will retry sooner) |
-## Pulse Assistant (Chat): How It Works
+---
-Pulse Assistant is **tool-driven**. It does not "guess" system state — it calls live tools and reports their outputs.
+## Pulse Assistant (Chat)
+
+Pulse Assistant is a **tool-driven** chat interface. It does not "guess" system state — it calls live tools and reports their outputs.
### The Model's Workflow (Discover → Investigate → Act)
-- **Discover**: Uses `pulse_query` (or `pulse_discovery`) to find real resources and IDs.
-- **Investigate**: Uses `pulse_read` to run bounded, read-only commands and check status/logs.
-- **Act** (optional): Uses `pulse_control` for changes, then verifies with a read.
-
-### Safety Gates That Make It Trustworthy
-- **Strict Resolution (optional)**: When enabled, the assistant must discover a resource before it can act on it. This prevents fabricated IDs.
-- **Read/Write separation**: Read-only commands go through `pulse_read`; write actions go through `pulse_control`. This keeps the workflow state machine honest.
-- **Verification after writes**: After any write, the assistant must perform a read check before it can finish the response.
-- **Non‑interactive guardrails**: Commands that could hang (e.g., `tail -f`) are rewritten into bounded, safe forms.
-- **Approval mode**: In Controlled mode, every write requires explicit user approval. Autonomous mode is available only with Pro.
-
-### What You See As a User
-- **Clear tool usage**: Each step shows which tool ran and what it returned.
-- **Structured recovery**: If a tool is blocked, the assistant adapts (e.g., runs discovery, switches tools, or asks for approval).
-- **Verified outcomes**: Changes are followed by a read check before the assistant claims success.
-
-## Why It's Impressive (and Reliable)
-
-Pulse Assistant behaves like a careful operator:
-- It **grounds answers in live data** instead of assumptions.
-- It **adapts** when guardrails block an action.
-- It **verifies** changes before reporting success.
-- It **keeps you in control** with explicit approval gates.
+
+1. **Discover**: Uses `pulse_query` or `pulse_discovery` to find real resources and IDs
+2. **Investigate**: Uses `pulse_read` to run bounded, read-only commands and check status/logs
+3. **Act** (optional): Uses `pulse_control` for changes, then verifies with a read
+
+### Available Tools
+
+| Tool | Classification | Purpose |
+|------|---------------|---------|
+| `pulse_query`, `pulse_discovery` | Resolve | Resource discovery and query |
+| `pulse_read` | Read | Read-only operations: exec, file, find, tail, logs |
+| `pulse_metrics` | Read | Performance metrics |
+| `pulse_storage` | Read | Storage information |
+| `pulse_kubernetes` | Read | Kubernetes cluster info |
+| `pulse_pmg` | Read | Proxmox Mail Gateway stats |
+| `pulse_alerts` | Read/Write | Alert management (resolve/dismiss are writes) |
+| `pulse_docker` | Read/Write | Docker operations (control/update are writes) |
+| `pulse_knowledge` | Read/Write | Knowledge persistence (remember/note/save are writes) |
+| `pulse_file_edit` | Read/Write | File operations (write/append are writes) |
+| `pulse_control` | Write | Guest control, service management |
+| `pulse_patrol` | Read | Patrol findings and status |
+
+### Safety Gates
+
+The assistant enforces multiple safety gates:
+
+1. **Discovery Before Action** — Action tools cannot operate on resources that weren't first discovered
+2. **Verification After Write** — After any write, the model must perform a read/status check before providing a final answer
+3. **Read/Write Separation** — Read operations route through `pulse_read` (stays in READING state); write operations route through `pulse_control` (enters VERIFYING state)
+4. **Phantom Detection** — Detects when the model claims execution without tool calls
+5. **Approval Mode** — In Controlled mode, every write requires explicit user approval
+6. **Execution Context Binding** — Commands execute within the resolved resource's context, not on parent hosts
+
+### Control Levels
+
+| Level | Behavior | License |
+|-------|----------|---------|
+| **Read-only** | AI can observe and query data only | Free |
+| **Controlled** | AI asks for approval before executing commands | Free |
+| **Autonomous** | AI executes actions without prompting | Pro |
+
+### Using Approvals (Controlled Mode)
+
+When control level is **Controlled**, write actions pause for approval:
+
+1. Tool returns `APPROVAL_REQUIRED: { approval_id, command, ... }`
+2. Agentic loop emits `approval_needed` SSE event
+3. UI shows approval card with the proposed command
+4. **Approve** to execute and verify, or **Deny** to cancel
+5. Only users with admin privileges can approve/deny
+
+---
## Configuration
Configure in the UI: **Settings → System → AI Assistant**
-AI settings are stored encrypted at rest in `ai.enc` under the Pulse config directory. Patrol findings and history are stored in `ai_findings.json`, `ai_patrol_runs.json`, and usage data in `ai_usage_history.json`. These files are located in `/etc/pulse` for systemd installs, or `/data` for Docker/Kubernetes.
-
### Supported Providers
- **Anthropic** (API key or OAuth)
@@ -178,11 +308,74 @@ You can set separate models for:
- Patrol (`patrol_model`)
- Auto-fix remediation (`auto_fix_model`)
+### Storage
+
+AI settings are stored encrypted at rest in `ai.enc` under the Pulse config directory. Related files:
+
+| File | Purpose |
+|------|---------|
+| `ai.enc` | Encrypted AI configuration and credentials |
+| `ai_findings.json` | Patrol findings |
+| `ai_patrol_runs.json` | Patrol run history |
+| `ai_usage_history.json` | Token usage data |
+| `ai_chat_sessions.json` | Legacy chat sessions (UI sync) |
+| `baselines.json` | Learned resource baselines |
+| `ai_correlations.json` | Resource correlation data |
+| `ai_patterns.json` | Detected patterns |
+
+Config directory: `/etc/pulse` (systemd) or `/data` (Docker/Kubernetes)
+
+### Testing
+
+- Test provider connectivity: `POST /api/ai/test` and `POST /api/ai/test/{provider}`
+- List available models: `GET /api/ai/models`
+
+---
+
+## Schedule and Triggers
+
+Patrol runs on a configurable schedule:
+
+| Interval | Description |
+|----------|-------------|
+| Disabled | Patrol runs only when manually triggered |
+| 10 min – 7 days | Configurable interval (default: 6 hours) |
+
+Patrol can also be triggered by:
+- **Manual run**: Click "Run Patrol" in the UI
+- **Alert-triggered analysis (Pro)**: Runs when an alert fires
+- **API call**: `POST /api/ai/patrol/run`
+
+---
+
+## AI Intelligence Layer
+
+Pulse includes a unified intelligence system that aggregates data from all AI subsystems:
+
+### Components
+
+| Component | Purpose |
+|-----------|---------|
+| **Baseline Engine** | Learns normal behavior, detects anomalies via z-score |
+| **Pattern Detector** | Identifies recurring issues and trends |
+| **Correlation Engine** | Links related issues across resources |
+| **Incident Memory** | Tracks past incidents and successful remediations |
+| **Knowledge Store** | Persists user annotations and learned preferences |
+| **Forecast Engine** | Predicts capacity issues and resource exhaustion |
+
+### Health Scoring
+
+Each resource receives a health score (A–F) based on:
+- Current metrics vs baseline
+- Active findings and alerts
+- Recent incidents
+- Trend direction (improving/stable/declining)
+
+---
+
## Model Matrix (Pulse Assistant)
-This table summarizes the most recent **Pulse Assistant** eval runs per model. Patrol is still in development and is not scored yet.
-Time/tokens reflect the combined **Smoke + Read-only** matrix run.
-Transient provider errors (rate limits, unavailable chat endpoints) are skipped when rendering the table.
+This table summarizes the most recent **Pulse Assistant** eval runs per model.
Update the table from eval reports:
```
@@ -206,74 +399,53 @@ scripts/eval/run_model_matrix.sh
| openai:gpt-5.2-chat-latest | ✅ | ✅ | 8s | 12,595 | 2026-01-29 |
<!-- MODEL_MATRIX_END -->
-### Testing
-
-- Test provider connectivity: `POST /api/ai/test` and `POST /api/ai/test/{provider}`
-- List available models: `GET /api/ai/models`
+---
-## Patrol Service (BYOK)
-
-Patrol runs automated health checks on a configurable schedule (default: every 6 hours). It passes comprehensive infrastructure context to the LLM (see "Context Patrol Receives" above) and generates findings when issues are detected.
-
-Patrol runs with your configured provider (BYOK). Auto-fix and assisted/full autonomy require Pulse Pro.
-
-### Finding Severity
-
-- **Critical**: Immediate attention required (service down, data at risk)
-- **Warning**: Should be addressed soon (disk filling, backup stale)
-
-Note: `info` and `watch` level findings are filtered out to reduce noise.
-
-### Managing Findings
+## Safety Controls
-Findings can be managed via the UI or API:
+Pulse includes settings that control how "active" AI features are:
-- **Get help**: Chat with AI to troubleshoot the issue
-- **Resolve**: Mark as fixed (finding will reappear if the issue resurfaces)
-- **Dismiss**: Mark as expected behavior (creates suppression rule)
+- **Autonomous mode (Pro)**: When enabled, AI may execute safe commands without approval
+- **Patrol auto-fix (Pro)**: Allows patrol to attempt automatic remediation
+- **Alert-triggered analysis (Pro)**: Limits AI to analyzing specific events when alerts occur
+- **Full autonomy unlock (Pro)**: Enables auto-fix for critical findings without approval (requires explicit toggle)
-Dismissed and resolved findings persist across Pulse restarts.
+If you enable execution features, ensure agent tokens and scopes are appropriately restricted.
-### AI-Assisted Remediation
+### Advanced Network Restrictions
-When chatting with AI about a patrol finding, the AI can:
-- Run diagnostic commands on connected agents
-- Propose fixes with explanations
-- Automatically resolve findings after successful remediation (Pro auto-fix)
+Pulse blocks AI tool HTTP fetches to loopback and link-local addresses by default. For local development:
-## Safety Controls
+- `PULSE_AI_ALLOW_LOOPBACK=true`
-Pulse includes settings that control how "active" AI features are:
+Use this only in trusted environments.
-- **Autonomous mode (Pro)**: When enabled, AI may execute safe commands without approval.
-- **Patrol auto-fix (Pro)**: Allows patrol to attempt automatic remediation.
-- **Alert-triggered analysis (Pro)**: Limits AI to analyzing specific events when alerts occur.
+---
-If you enable execution features, ensure agent tokens and scopes are appropriately restricted.
+## Privacy
-### Control Levels
+Patrol runs on your server and only sends the minimal context needed for analysis to the configured provider (when AI is enabled). No telemetry is sent to Pulse by default.
-Pulse uses three AI permission levels for infrastructure control:
+---
-- **Read-only**: AI can observe and query data only.
-- **Controlled**: AI asks for approval before executing commands or control actions.
-- **Autonomous (Pro)**: AI executes actions without prompting.
+## Why Patrol Is Different From Traditional Alerts
-### Using Approvals (Controlled Mode)
+Alerts are threshold-based and narrow. Patrol is context-based and cross-system.
-When control level is **Controlled**, write actions pause for approval:
+- **Alerts**: "Disk > 90%"
+- **Patrol**: "ZFS pool is 86% but trending +4%/day; projected to hit 95% within a week. Largest consumer is datastore X. Recommend prune or expand."
-- In chat, you’ll see an approval card with the proposed command.
-- **Approve** to execute and verify the change, or **Deny** to cancel it.
-- Only users with admin privileges can approve/deny.
+---
-### Advanced Network Restrictions
+## Cost Tracking
-Pulse blocks AI tool HTTP fetches to loopback and link-local addresses by default. For local development, you can allow loopback targets:
+Pulse tracks token usage and costs:
-- `PULSE_AI_ALLOW_LOOPBACK=true`
+- View usage summary: `GET /api/ai/cost/summary`
+- Reset counters: `POST /api/ai/cost/reset` (admin)
+- Set monthly budget limits in AI settings
-Use this only in trusted environments.
+---
## Troubleshooting
@@ -282,4 +454,19 @@ Use this only in trusted environments.
| AI not responding | Verify provider credentials in **Settings → System → AI Assistant** |
| No execution capability | Confirm at least one agent is connected |
| Findings not persisting | Check Pulse has write access to `ai_findings.json` in the config directory |
-| Too many findings | This shouldn't happen - please report if it does |
+| Too many findings | This shouldn't happen — please report if it does |
+| Investigation stuck | Check circuit breaker status at `/api/ai/circuit/status`; may auto-reset after cooldown |
+| Model not available | Ensure provider API key is valid and model ID matches provider format |
+
+## Related Documentation
+
+### Deep Dives (Recommended for Technical Audiences)
+
+- **[Pulse Assistant Deep Dive](architecture/pulse-assistant-deep-dive.md)** — Complete technical breakdown of the agentic architecture: context prefetching, knowledge accumulation, FSM enforcement, parallel execution, phantom detection, auto-recovery
+- **[Pulse Patrol Deep Dive](architecture/pulse-patrol-deep-dive.md)** — Full intelligence layer documentation: baseline learning, pattern detection, forecasting, correlation analysis, incident memory, investigation orchestration
+
+### Reference Documentation
+
+- [Architecture: Pulse Assistant (Safety Gates)](architecture/pulse-assistant.md) — Detailed FSM states, tool protocol, and invariants
+- [API Reference](API.md) — Complete API endpoint documentation
+- [Pulse Pro](PULSE_PRO.md) — Pro features and licensing
diff --git a/docs/PULSE_PRO.md b/docs/PULSE_PRO.md
index c57950721d..bfe675d5ff 100644
--- a/docs/PULSE_PRO.md
+++ b/docs/PULSE_PRO.md
@@ -40,22 +40,53 @@ Scheduled background analysis that correlates live state + metrics history to pr
### Pro-Only Automations
- **Alert-triggered analysis**: on-demand deep analysis when alerts fire.
-- **Autonomous mode**: optional diagnostic/fix commands through connected agents.
-- **Auto-fix**: guarded remediations when enabled.
-- **Kubernetes AI analysis**: deep cluster analysis beyond basic monitoring (Pro-only).
+- **Auto-fix mode**: automatic remediation with verification loops (see Autonomy Levels below).
+- **Full autonomy unlock**: auto-fix for critical findings without requiring approval.
+- **Kubernetes AI analysis**: deep cluster analysis beyond basic monitoring.
- **Audit-triggered webhooks**: real-time delivery of security events to external systems.
- **Advanced Reporting**: scheduled or on-demand PDF/CSV infrastructure health reports.
- **Agent Profiles**: centralized configuration profiles for fleets of agents.
+### Autonomy Levels
+
+Patrol and the Assistant support tiered autonomy:
+
+| Mode | Behavior | License |
+|------|----------|--------|
+| **Monitor** | Detect issues only. No investigation or fixes. | Free (BYOK) |
+| **Investigate** | Investigates findings and proposes fixes. All fixes require approval. | Free (BYOK) |
+| **Auto-fix** | Automatically fixes issues and verifies. Critical findings require approval by default. | **Pro** |
+| **Full autonomy** | Auto-fix for all findings including critical, without approval. | **Pro** (explicit toggle) |
+
+### Investigation Orchestration
+
+When Patrol creates a finding, the investigation orchestrator can:
+
+1. **Create a chat session** dedicated to the finding.
+2. **AI analyzes** the issue using available tools (metrics, logs, storage, etc.).
+3. **Propose a fix** with risk assessment (low/medium/high/critical).
+4. **Queue for approval** or **auto-execute** based on autonomy level.
+5. **Verify the fix** with a follow-up read after execution.
+
+Investigation outcomes include:
+- `resolved` — Issue resolved during investigation
+- `fix_queued` — Fix proposed, awaiting approval
+- `fix_executed` — Fix auto-executed successfully
+- `fix_verified` — Fix worked, issue confirmed resolved
+- `needs_attention` — Requires human intervention
+- `cannot_fix` — Issue cannot be automatically fixed
+
### What Free Users Still Get
-- **Pulse Patrol (BYOK)**: background findings with your own provider.
+- **Pulse Patrol (BYOK)**: background findings and investigation proposals with your own provider.
- **AI Chat (BYOK)**: interactive troubleshooting with your own API keys.
- **Update alerts**: container/package update signals remain available in the free tier.
### What You See In The UI
- **Patrol findings**: a prioritized list with severity, evidence, and recommended fixes.
+- **Investigation status**: progress indicators showing investigation state and outcome.
+- **Approval cards**: pending fixes await your review with one-click approve/deny.
- **Alert timelines**: AI analysis events attached to the alert history for auditability.
-- **Remediation controls**: explicit toggles for autonomous mode and auto-fix workflows.
+- **Remediation controls**: explicit toggles for autonomy mode in Patrol settings.
- **Agent profiles**: create, edit, and assign profiles in **Settings → Agents → Agent Profiles**.
## Pro Feature Gates (License-Enforced)
@@ -112,6 +143,10 @@ This returns a feature map like `ai_alerts`, `ai_autofix`, and `kubernetes_ai` s
- **Alert-triggered analysis**: runs per alert event and writes analysis into the alert timeline for auditability.
- **Auto-fix safety**: requires explicit toggles and uses the same agent command scopes you configure for manual runs.
+📖 **For complete technical details on the AI subsystems:**
+- [Pulse Patrol Deep Dive](architecture/pulse-patrol-deep-dive.md) — Baseline learning, pattern detection, forecasting, correlation analysis, incident memory
+- [Pulse Assistant Deep Dive](architecture/pulse-assistant-deep-dive.md) — Context prefetching, FSM enforcement, knowledge accumulation, safety gates
+
## Example Finding Payload (API)
`GET /api/ai/patrol/findings` returns structured findings you can integrate with external tooling:
diff --git a/docs/architecture/pulse-assistant-deep-dive.md b/docs/architecture/pulse-assistant-deep-dive.md
new file mode 100644
index 0000000000..6017701f1a
--- /dev/null
+++ b/docs/architecture/pulse-assistant-deep-dive.md
@@ -0,0 +1,897 @@
+# Pulse Assistant: Technical Deep Dive
+
+This document provides an in-depth look at the engineering behind Pulse Assistant — a safety-gated, tool-driven AI system for infrastructure management that goes far beyond simple chatbots.
+
+---
+
+## Executive Summary
+
+Pulse Assistant isn't a "chat wrapper around an LLM." It's a **protocol-driven, safety-gated agentic system** that:
+
+1. **Treats the LLM as untrusted** — the model proposes, Go code enforces
+2. **Proactively gathers context** — understands resources before you ask
+3. **Learns within sessions** — extracts and caches facts to avoid redundant queries
+4. **Enforces workflow invariants** — FSM prevents dangerous state transitions
+5. **Supports parallel tool execution** — efficient batch operations
+6. **Detects and prevents hallucinations** — phantom execution detection
+7. **Auto-recovers from errors** — structured error envelopes enable self-correction
+
+All while providing streaming responses with real-time tool execution visibility.
+
+---
+
+## Architecture Overview
+
+```
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ USER REQUEST │
+│ (with optional @mentions) │
+└────────────────────────────────┬────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ CONTEXT PREFETCHER │
+│ • Detects resource mentions (@homepage, "jellyfin") │
+│ • Resolves structured mentions from frontend autocomplete │
+│ • Gathers discovery info (ports, config paths, bind mounts) │
+│ • Builds authoritative context summary │
+└────────────────────────────────┬────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ AGENTIC LOOP │
+│ ┌─────────────┐ ┌──────────┐ ┌─────────────────┐ ┌───────────────┐ │
+│ │ LLM │──▶│ FSM │──▶│ Tool Executor │──▶│ Knowledge │ │
+│ │ (Proposer) │ │ (Gating) │ │ (Validation) │ │ Accumulator │ │
+│ └─────────────┘ └──────────┘ └─────────────────┘ └───────────────┘ │
+│ │ │ │ │ │
+│ ▼ ▼ ▼ ▼ │
+│ ┌─────────────┐ ┌──────────┐ ┌─────────────────┐ ┌───────────────┐ │
+│ │ Phantom │ │ Telemetry│ │ ResolvedContext│ │ Context │ │
+│ │ Detection │ │ Counters │ │ (Session Truth)│ │ Compaction │ │
+│ └─────────────┘ └──────────┘ └─────────────────┘ └───────────────┘ │
+└────────────────────────────────┬────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ AGENT EXECUTION LAYER │
+│ (CommandPolicy → AgentServer → Connected Agents) │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## 1. Context Prefetcher
+
+**📁 Location:** `internal/ai/chat/context_prefetch.go`
+
+### What It Does
+
+Before the LLM even sees your message, the Context Prefetcher **proactively gathers relevant context** about any resources you mention.
+
+### How It Works
+
+```go
+type ResourceMention struct {
+ Name string
+ ResourceType string // "vm", "lxc", "docker", "host", "node", "k8s_pod"
+ ResourceID string
+ HostID string
+ MatchedText string
+ BindMounts []MountInfo // Docker bind mount mappings
+ DockerHostName string // Full routing chain for nested Docker
+ DockerHostType string // "lxc", "vm", or "host"
+ DockerHostVMID int
+ ProxmoxNode string
+ TargetHost string // THE correct target for commands
+}
+```
+
+### Two Resolution Modes
+
+1. **Structured Mentions** (preferred): Frontend autocomplete passes fully-resolved resource identities
+2. **Fuzzy Matching** (fallback): Text analysis matches resource names from your message
+
+### Fuzzy Matching Intelligence
+
+```go
+// Matches: "homepage" → "homepage-docker"
+// Matches: "check jellyfin logs" → finds "jellyfin" container
+func matchesResource(messageLower string, messageWords []string, resourceName string) bool {
+ // Direct containment
+ if strings.Contains(messageLower, resourceName) { return true }
+
+ // Prefix matching (homepage → homepage-docker)
+ for _, word := range messageWords {
+ if len(word) >= 4 && strings.HasPrefix(resourceName, word) {
+ return true
+ }
+ }
+ // Hyphenated part matching
+ // ...
+}
+```
+
+### Unresolved Mention Handling
+
+If you @mention something that doesn't exist:
+
+```go
+// Returns explicit feedback rather than wasting tool calls
+sb.WriteString("'myservice' was NOT found in Pulse monitoring.\n")
+sb.WriteString("Do NOT use pulse_discovery to search — they are not in the system.\n")
+sb.WriteString("Instead: use pulse_control directly if you know the host.\n")
+```
+
+### Full Routing Chain for Docker
+
+Docker containers get special treatment — the prefetcher resolves the complete routing chain:
+
+```
+## jellyfin (Docker container)
+Location: Docker on "media-server" (LXC 141) on Proxmox node "delly"
+>>> target_host: "media-server" <<<
+Bind mounts (paths on media-server filesystem, NOT inside container):
+ /opt/jellyfin/config → /config
+ /mnt/media → /media
+```
+
+This prevents the common mistake of running commands on the Proxmox node instead of the LXC.
+
+---
+
+## 2. Knowledge Accumulator
+
+**📁 Location:** `internal/ai/chat/knowledge_accumulator.go`
+
+### What It Does
+
+The Knowledge Accumulator **extracts and caches facts** from every tool result during a session. This prevents redundant queries and helps the model remember what it's already learned.
+
+### Fact Categories
+
+```go
+const (
+ FactCategoryResource = "resource" // VM/LXC/container status
+ FactCategoryStorage = "storage" // Pool usage, backup info
+ FactCategoryAlert = "alert" // Active alerts, findings
+ FactCategoryDiscovery = "discovery" // Ports, paths, services
+ FactCategoryExec = "exec" // Command outputs
+ FactCategoryMetrics = "metrics" // Performance data
+ FactCategoryFinding = "finding" // Patrol findings
+)
+```
+
+### Fact Structure
+
+```go
+type Fact struct {
+ Category FactCategory
+ Key string // Dedup key: "lxc:delly:106:status"
+ Value string // Compact value: "running, Postfix, hostname=patrol-test"
+ ObservedAt time.Time
+ Turn int // Which agentic turn observed this
+}
+```
+
+### Bounded, Session-Scoped
+
+```go
+const (
+ defaultMaxEntries = 60 // Max facts stored
+ defaultMaxChars = 2000 // Max total characters
+ maxValueLen = 200 // Max per-fact value length
+)
+```
+
+### LRU Eviction with Turn Pinning
+
+Facts from the current or previous turn are "soft-pinned" and won't be evicted:
+
+```go
+func (ka *KnowledgeAccumulator) evict() {
+ // ...
+ // Soft-pin: don't evict facts from current or previous turn
+ if fact.Turn >= ka.currentTurn-1 {
+ continue
+ }
+ // Evict oldest facts first
+}
+```
+
+### Knowledge Gate in Agentic Loop
+
+Before executing a tool, the loop checks if we already have the answer:
+
+```go
+// KNOWLEDGE GATE: Return cached facts for redundant tool calls
+if keys := PredictFactKeys(tc.Name, tc.Input); len(keys) > 0 {
+ if cachedValue, found := ka.Lookup(key); found {
+ return "Already known (from earlier investigation): " + cachedValue
+ }
+}
+```
+
+---
+
+## 3. Knowledge Extractor
+
+**📁 Location:** `internal/ai/chat/knowledge_extractor.go`
+
+### What It Does
+
+Deterministically parses tool results and extracts structured facts — **no LLM calls** required.
+
+### Coverage
+
+The extractor handles all major tools:
+
+| Tool | Facts Extracted |
+|------|-----------------|
+| `pulse_query` | Resource status, health, topology, configs |
+| `pulse_storage` | Pool usage, backup tasks, disk health |
+| `pulse_discovery` | Ports, config paths, log paths, services |
+| `pulse_read` | Command outputs (keyed by command) |
+| `pulse_metrics` | CPU, memory, disk averages, baselines |
+| `pulse_alerts` | Active alerts, findings with severity |
+| `pulse_docker` | Container states, update availability |
+| `pulse_kubernetes` | Pod counts, deployment status |
+
+### Example Extraction
+
+For `pulse_query action=get`:
+
+```go
+func extractQueryGetFacts(input, resultText string) []FactEntry {
+ // Parse JSON response
+ // Extract: status, cpu_avg, mem_avg, disk_avg, hostname
+ // Key format: "lxc:delly:106:status"
+ // Value format: "running, cpu:12%, mem:45%, disk:67%"
+}
+```
+
+### Negative Markers
+
+If a query returns an error or empty result, a "negative marker" is stored:
+
+```go
+// Key: "lxc:delly:106:status:queried"
+// Value: "not_found" or "error"
+```
+
+This prevents the model from re-querying resources that don't exist.
+
+---
+
+## 4. Finite State Machine (FSM)
+
+**📁 Location:** `internal/ai/chat/fsm.go`
+
+### What It Does
+
+The FSM enforces **workflow invariants** that prevent dangerous state transitions. The model cannot bypass these — they're enforced in Go code.
+
+### States
+
+```go
+const (
+ StateResolving = "RESOLVING" // No target yet, must discover first
+ StateReading = "READING" // Read tools allowed, can explore
+ StateWriting = "WRITING" // Write in progress (transitional)
+ StateVerifying = "VERIFYING" // Must read/verify before final answer
+)
+```
+
+### Tool Classification
+
+```go
+const (
+ ToolKindResolve // Discovery/query (pulse_query, pulse_discovery)
+ ToolKindRead // Read-only (pulse_read, pulse_metrics, pulse_storage)
+ ToolKindWrite // Mutating (pulse_control, pulse_file_edit write)
+)
+```
+
+### State Transitions
+
+```
+ ┌───────────────────────────────────────────────┐
+ │ │
+ ▼ │
+ ┌──────────┐ resolve/read ┌─────────┐ read │
+ │RESOLVING │ ───────────────▶│ READING │◀──────────┤
+ └──────────┘ └────┬────┘ │
+ │ │
+ write│ │
+ ▼ │
+ ┌───────────┐ verify │
+ │ VERIFYING │──────────┘
+ └───────────┘
+ │
+ write blocked!
+```
+
+### Key Invariants Enforced
+
+1. **Discovery Before Action**: Can't write to undiscovered resources
+2. **Verification After Write**: Must read/check after any mutation
+3. **Read/Write Tool Separation**: `pulse_read` never triggers VERIFYING
+
+### Error Response for FSM Blocks
+
+```json
+{
+ "error": {
+ "code": "FSM_BLOCKED",
+ "message": "Must verify the previous write operation",
+ "blocked": true,
+ "recoverable": true,
+ "recovery_hint": "Use a read tool to check the result first"
+ }
+}
+```
+
+---
+
+## 5. Resolved Context
+
+**📁 Location:** `internal/ai/chat/types.go`
+
+### What It Does
+
+ResolvedContext is the **session-scoped source of truth** for discovered resources. The model cannot fabricate resource IDs — they must come from successful discovery.
+
+### Resource Structure
+
+```go
+type ResolvedResource struct {
+ // Structured Identity
+ Kind string // "lxc", "vm", "docker_container", "node"
+ ProviderUID string // Stable ID from provider
+ Scope ResourceScope // Host, parent, cluster, namespace
+ Aliases []string // All names this resource is known by
+
+ // Routing
+ ReachableVia []ExecutorPath // All ways to reach this resource
+ TargetHost string // Primary command target
+ AllowedActions []string // What can be done
+
+ // Proxmox-specific
+ VMID int
+ Node string
+}
+```
+
+### Canonical Resource ID Format
+
+```
+{kind}:{host}:{provider_uid} # Scoped resources
+lxc:delly:141 # LXC 141 on node delly
+docker_container:media-server:abc123 # Docker on host media-server
+
+{kind}:{provider_uid} # Global resources
+node:delly # Proxmox node
+```
+
+### TTL and LRU Eviction
+
+```go
+const (
+ DefaultResolvedContextTTL = 45 * time.Minute
+ DefaultResolvedContextMaxEntries = 500
+)
+```
+
+### Explicit vs General Access Tracking
+
+**Critical distinction** that prevents false positives:
+
+| Tracking | Set By | Purpose |
+|----------|--------|---------|
+| `lastAccessed` | Every add/get | LRU eviction, TTL expiry |
+| `explicitlyAccessed` | User intent only | Routing validation |
+
+Why this matters:
+- Bulk discovery adds many resources → sets `lastAccessed` for all
+- If routing validation used `lastAccessed`, bulk discovery would block host operations
+- Instead, routing checks `explicitlyAccessed` which is only set for single-resource operations
+
+---
+
+## 6. Parallel Tool Execution
+
+**📁 Location:** `internal/ai/chat/agentic.go`
+
+### What It Does
+
+When the LLM requests multiple tool calls, compatible operations execute **in parallel** for efficiency.
+
+### Three-Phase Pipeline
+
+```
+Phase 1: Pre-check (sequential)
+├── FSM validation
+├── Loop detection
+└── Knowledge gate
+
+Phase 2: Execute (parallel, max 4 concurrent)
+├── Tool 1 ────────────┐
+├── Tool 2 ─────────┐ │
+├── Tool 3 ───────┐ │ │
+└── Tool 4 ─────┐ │ │ │
+ ▼ ▼ ▼ ▼
+ Results
+
+Phase 3: Post-process (sequential)
+├── Stream events to UI
+├── FSM state transitions
+├── Knowledge extraction
+└── Approval flow (if needed)
+```
+
+### Concurrency Control
+
+```go
+var wg sync.WaitGroup
+sem := make(chan struct{}, 4) // Cap at 4 concurrent
+
+for j, pe := range pendingExec {
+ wg.Add(1)
+ go func(idx int, tc providers.ToolCall) {
+ defer wg.Done()
+ sem <- struct{}{} // Acquire
+ defer func() { <-sem }() // Release
+
+ r, e := a.executor.ExecuteTool(ctx, tc.Name, tc.Input)
+ execResults[idx] = parallelToolResult{Result: r, Err: e}
+ }(j, pe.tc)
+}
+wg.Wait()
+```
+
+---
+
+## 7. Loop Detection
+
+**📁 Location:** `internal/ai/chat/agentic.go`
+
+### What It Does
+
+Prevents the model from getting stuck calling the same tool repeatedly.
+
+### Implementation
+
+```go
+const maxIdenticalCalls = 3
+recentCallCounts := make(map[string]int)
+
+func toolCallKey(name string, input map[string]interface{}) string {
+ inputJSON, _ := json.Marshal(input)
+ return name + ":" + string(inputJSON)
+}
+
+// In the loop:
+callKey := toolCallKey(tc.Name, tc.Input)
+recentCallCounts[callKey]++
+if recentCallCounts[callKey] > maxIdenticalCalls {
+ return "LOOP_DETECTED: You have called " + tc.Name +
+ " with the same arguments " + count + " times. Blocked."
+}
+```
+
+---
+
+## 8. Phantom Execution Detection
+
+**📁 Location:** `internal/ai/chat/agentic.go`
+
+### What It Does
+
+Detects when the model **claims to have done something** but never actually called tools. This catches hallucinations.
+
+### Pattern Detection
+
+```go
+func hasPhantomExecution(content string) bool {
+ // Only flag if tools haven't succeeded this episode
+ // Look for phrases like:
+ // - "I have restarted..."
+ // - "Successfully stopped..."
+ // - "The service has been..."
+ // - "Done! I've..."
+}
+```
+
+### Safe Response on Detection
+
+```go
+safeResponse := "I apologize, but I wasn't able to access the infrastructure " +
+ "tools needed to complete that request. This can happen when:\n\n" +
+ "1. The tools aren't available right now\n" +
+ "2. There was a connection issue\n" +
+ "3. The model I'm running on doesn't support function calling\n\n" +
+ "Please try again, or let me know if you have a question I can " +
+ "answer without checking live infrastructure."
+```
+
+---
+
+## 9. Context Compaction
+
+**📁 Location:** `internal/ai/chat/agentic.go`
+
+### What It Does
+
+Compacts old tool results to prevent context window exhaustion in long conversations.
+
+### Strategy
+
+```go
+const compactionKeepTurns = 2 // Keep last 2 turns in full
+const compactionMinChars = 300 // Only compact results > 300 chars
+
+func compactOldToolResults(messages, turnStartIdx, keepTurns, minChars int, ka *KnowledgeAccumulator) {
+ // For results older than keepTurns:
+ // 1. Replace with fact summary from KnowledgeAccumulator
+ // 2. Or truncate to first 200 chars + "[truncated]"
+}
+```
+
+### Wrap-Up Nudges
+
+After many tool calls, the loop hints the model to wrap up:
+
+```go
+const wrapUpNudgeAfterCalls = 12
+const wrapUpEscalateAfterCalls = 18
+
+// After 12 calls: "Consider summarizing your findings"
+// After 18 calls: "Please provide your final answer now"
+```
+
+---
+
+## 10. Execution Intent Classification
+
+**📁 Location:** `internal/ai/tools/tools_query.go`
+
+### What It Does
+
+Classifies commands as read-only or potentially mutating — **deterministically, without LLM judgment**.
+
+### Intent Levels
+
+```go
+const (
+ IntentReadOnlyCertain // Non-mutating by construction (cat, grep, docker logs)
+ IntentReadOnlyConditional // Proven read-only by content (SELECT queries)
+ IntentWriteOrUnknown // Cannot prove safe (unknown, or has mutation patterns)
+)
+```
+
+### Classification Phases (Order Matters!)
+
+```
+Phase 1: Mutation-capability guards
+├── Block: sudo, redirects, pipes to dual-use tools, shell chaining
+
+Phase 2: Known write patterns
+├── Block: rm, shutdown, systemctl restart, DROP DATABASE
+
+Phase 3: Read-only by construction
+├── Allow: cat, grep, ls, docker logs, ffprobe, kubectl get
+
+Phase 4: Content inspection
+├── SQL: SELECT → allow, INSERT/UPDATE/DELETE → block
+├── Redis: GET → allow, SET/DEL → block
+
+Phase 5: Conservative fallback
+└── Unknown → IntentWriteOrUnknown
+```
+
+**Critical**: Phase 1-2 **dominate** — a command matching known write patterns is blocked even if it also matches read-only patterns.
+
+### Content Inspectors
+
+```go
+type ContentInspector interface {
+ Applies(cmdLower string) bool
+ IsReadOnly(cmdLower string) (bool, string)
+}
+
+// Example: SQL inspector
+type sqlContentInspector struct{}
+
+func (s *sqlContentInspector) IsReadOnly(cmd string) (bool, string) {
+ // Parse SQL, check for SELECT only
+ // Block: INSERT, UPDATE, DELETE, DROP, TRUNCATE, ALTER
+}
+```
+
+---
+
+## 11. Strict Resolution
+
+**📁 Location:** `internal/ai/tools/tools_query.go`
+
+### What It Does
+
+Prevents the model from operating on **fabricated or hallucinated resource IDs**.
+
+### Error Response
+
+```go
+type ErrStrictResolution struct {
+ Action string
+ Name string
+ ResourceID string
+ Message string
+ Suggestions []string // Discovered resources with similar names
+}
+
+func (e *ErrStrictResolution) ToToolResponse() ToolResponse {
+ return ToolResponse{
+ OK: false,
+ Error: &ToolError{
+ Code: "STRICT_RESOLUTION",
+ Message: e.Message,
+ Blocked: true,
+ Details: map[string]interface{}{
+ "recovery_hint": "Use pulse_query to discover resources first",
+ "auto_recoverable": true,
+ },
+ },
+ }
+}
+```
+
+---
+
+## 12. Routing Mismatch Detection
+
+**📁 Location:** `internal/ai/tools/tools_query.go`
+
+### What It Does
+
+Prevents accidentally operating on a parent host when you meant to target a child resource.
+
+### Scenario
+
+1. User asks "edit config on @jellyfin" (Docker container on LXC)
+2. Model calls `pulse_file_edit` with `target_host="delly"` (the Proxmox node)
+3. File happens to exist on delly too (shared path)
+4. **Wrong file gets edited!**
+
+### Detection
+
+```go
+type ErrRoutingMismatch struct {
+ TargetHost string
+ MoreSpecificResources []string // ["jellyfin"]
+ MoreSpecificResourceIDs []string // ["docker_container:media-server:abc123"]
+ TargetResourceID string
+ Message string
+}
+```
+
+### Error Response
+
+```json
+{
+ "error": {
+ "code": "ROUTING_MISMATCH",
+ "message": "target_host 'delly' is a Proxmox node, but you recently referenced more specific resources: [jellyfin]",
+ "details": {
+ "target_resource_id": "docker_container:media-server:abc123",
+ "recovery_hint": "Retry with target_host='media-server'",
+ "auto_recoverable": true
+ }
+ }
+}
+```
+
+---
+
+## 13. Approval Flow
+
+**📁 Location:** `internal/ai/chat/agentic.go`, `internal/ai/approval/`
+
+### What It Does
+
+In "Controlled" mode, write operations require explicit user approval before execution.
+
+### Flow
+
+```
+1. Tool returns APPROVAL_REQUIRED
+ ├── approval_id
+ ├── command
+ ├── risk_level
+ └── description
+
+2. Agentic loop emits approval_needed SSE event
+
+3. UI shows approval card to user
+
+4. User approves/denies via API
+ POST /api/ai/approvals/{id}/approve
+ POST /api/ai/approvals/{id}/deny
+
+5. On approve: Tool re-executes with _approval_id
+ On deny: Assistant responds "Command denied: <reason>"
+```
+
+### Autonomous Mode
+
+For investigations, approvals can be bypassed:
+
+```go
+func (a *AgenticLoop) SetAutonomousMode(enabled bool) {
+ a.mu.Lock()
+ a.autonomousMode = enabled
+ a.mu.Unlock()
+}
+```
+
+---
+
+## 14. Token Budget Management
+
+**📁 Location:** `internal/ai/chat/agentic.go`
+
+### Token Tracking
+
+```go
+// Per-turn tracking
+a.totalInputTokens += data.InputTokens
+a.totalOutputTokens += data.OutputTokens
+
+// After each turn:
+if a.budgetChecker != nil {
+ if err := a.budgetChecker(); err != nil {
+ return resultMessages, fmt.Errorf("budget exceeded: %w", err)
+ }
+}
+```
+
+### Dynamic Turn Limits
+
+```go
+// Force text-only on last turn to get a summary
+if turn >= maxTurns-1 {
+ req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceNone}
+}
+
+// After write completion, force summary (prevents stale-data loops)
+if writeCompletedLastTurn {
+ req.ToolChoice = &providers.ToolChoice{Type: providers.ToolChoiceNone}
+}
+```
+
+---
+
+## 15. DeepSeek Artifact Cleanup
+
+**📁 Location:** `internal/ai/chat/agentic.go`
+
+### What It Does
+
+DeepSeek models sometimes leak internal markup in responses. The Assistant cleans this:
+
+```go
+func containsDeepSeekMarker(text string) bool {
+ return strings.Contains(text, "<|DSML|") ||
+ strings.Contains(text, "<|end▁of▁thinking|>")
+}
+
+func cleanDeepSeekArtifacts(content string) string {
+ // Remove:
+ // - <|DSML|function_calls>...</|DSML|>
+ // - <|end▁of▁thinking|>
+ // - Internal reasoning markers
+}
+```
+
+---
+
+## 16. Tool Protocol
+
+**📁 Location:** `internal/ai/tools/protocol.go`
+
+### Consistent Error Envelopes
+
+All tools return the same structure, enabling auto-recovery:
+
+```go
+type ToolResponse struct {
+ OK bool `json:"ok"`
+ Data interface{} `json:"data,omitempty"`
+ Error *ToolError `json:"error,omitempty"`
+ Meta map[string]interface{} `json:"meta,omitempty"`
+}
+
+type ToolError struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Blocked bool `json:"blocked,omitempty"`
+ Failed bool `json:"failed,omitempty"`
+ Retryable bool `json:"retryable,omitempty"`
+ Details map[string]interface{} `json:"details,omitempty"`
+}
+```
+
+### Error Codes
+
+| Code | Meaning | Auto-Recoverable |
+|------|---------|------------------|
+| `STRICT_RESOLUTION` | Resource not discovered | Yes (discover then retry) |
+| `FSM_BLOCKED` | FSM state prevents operation | Yes (perform required action) |
+| `ROUTING_MISMATCH` | Wrong target host | Yes (use correct target) |
+| `APPROVAL_REQUIRED` | User approval needed | Yes (wait for approval) |
+| `NOT_FOUND` | Resource doesn't exist | No |
+| `POLICY_BLOCKED` | Security policy blocked | No |
+| `EXECUTION_FAILED` | Runtime error | Depends |
+
+---
+
+## 17. Telemetry & Metrics
+
+**📁 Location:** `internal/ai/chat/metrics.go`
+
+### Key Metrics Collected
+
+```go
+// Agentic loop iterations
+metrics.RecordAgenticIteration(provider, model)
+
+// FSM blocks
+metrics.RecordFSMToolBlock(state, toolName, toolKind)
+metrics.RecordFSMFinalBlock(state)
+
+// Phantom detection
+metrics.RecordPhantomDetected(provider, model)
+
+// Auto-recovery
+metrics.RecordAutoRecoveryAttempt(errorCode, toolName)
+metrics.RecordAutoRecoverySuccess(errorCode, toolName)
+
+// Routing mismatches
+pulse_ai_routing_mismatch_block_total{tool, target_kind, child_kind}
+```
+
+---
+
+## Files Reference
+
+| File | Purpose |
+|------|---------|
+| `internal/ai/chat/service.go` | Chat service orchestration |
+| `internal/ai/chat/session.go` | Session lifecycle management |
+| `internal/ai/chat/agentic.go` | Core agentic loop (2289 lines) |
+| `internal/ai/chat/fsm.go` | Finite state machine |
+| `internal/ai/chat/types.go` | ResolvedContext, ResolvedResource |
+| `internal/ai/chat/context_prefetch.go` | Proactive context gathering |
+| `internal/ai/chat/knowledge_accumulator.go` | Fact caching |
+| `internal/ai/chat/knowledge_extractor.go` | Deterministic fact extraction |
+| `internal/ai/tools/tools_query.go` | Query/discovery tools, strict resolution |
+| `internal/ai/tools/tools_read.go` | Read-only execution, intent classification |
+| `internal/ai/tools/tools_control.go` | Write operations |
+| `internal/ai/tools/protocol.go` | ToolResponse envelope |
+| `internal/ai/approval/` | Approval flow management |
+
+---
+
+## Summary
+
+Pulse Assistant is engineered with **safety as a first-class concern**:
+
+1. **LLM as proposer, Go as enforcer** — the model suggests, code validates
+2. **Proactive context** — understands resources before you ask
+3. **Session-scoped learning** — remembers what it's discovered
+4. **Workflow enforcement** — FSM prevents dangerous transitions
+5. **Parallel execution** — efficient batch operations
+6. **Hallucination detection** — phantom execution caught and handled
+7. **Auto-recovery** — structured errors enable self-correction
+8. **Routing validation** — prevents wrong-target mistakes
+
+This architecture ensures the Assistant is both **powerful** (can control infrastructure) and **safe** (can't cause unintended damage).
diff --git a/docs/architecture/pulse-patrol-deep-dive.md b/docs/architecture/pulse-patrol-deep-dive.md
new file mode 100644
index 0000000000..ad1a03cdd3
--- /dev/null
+++ b/docs/architecture/pulse-patrol-deep-dive.md
@@ -0,0 +1,763 @@
+# Pulse Patrol: Technical Deep Dive
+
+This document provides an in-depth look at the engineering behind Pulse Patrol — a context-aware, learning AI analysis system that goes far beyond traditional threshold-based monitoring.
+
+---
+
+## Executive Summary
+
+Pulse Patrol is not a simple alerting system. It's a **multi-layered intelligence platform** that:
+
+1. **Learns** what's normal for your environment
+2. **Predicts** issues before they become critical
+3. **Correlates** events across your entire infrastructure
+4. **Remembers** past incidents and successful remediations
+5. **Investigates** issues autonomously when configured
+6. **Verifies** fixes and tracks remediation effectiveness
+
+All while running entirely on your infrastructure with BYOK (Bring Your Own Key) for complete privacy.
+
+---
+
+## Architecture Overview
+
+```
+ ┌─────────────────────────────────────────────────────────────────────┐
+ │ PULSE PATROL SERVICE │
+ │ │
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
+ │ │ Baseline │ │ Pattern │ │ Correlation │ │
+ │ │ Store │ │ Detector │ │ Detector │ │
+ │ │ (Learning) │ │ (Prediction) │ │ (Root Cause) │ │
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
+ │ │ │ │ │
+ │ └─────────────────┼─────────────────┘ │
+ │ │ │
+ │ ┌───────▼───────┐ │
+ │ │ Intelligence │ │
+ │ │ Orchestrator │ │
+ │ └───────┬───────┘ │
+ │ │ │
+ │ ┌──────────────┐ ┌──────▼───────┐ ┌──────────────┐ │
+ │ │ Incident │ │ Forecast │ │ Knowledge │ │
+ │ │ Store │ │ Service │ │ Store │ │
+ │ │ (History) │ │ (Prediction) │ │ (Learning) │ │
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
+ │ │ │
+ │ ┌───────▼───────┐ │
+ │ │ Patrol │ │
+ │ │ Service │ │
+ │ └───────┬───────┘ │
+ │ │ │
+ │ ┌──────────────────┼──────────────────┐ │
+ │ │ │ │ │
+ │ ┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐ │
+ │ │ Signal │ │ Agentic │ │ Evaluation│ │
+ │ │ Detection │ │ Loop │ │ Pass │ │
+ │ │(Determin.)│ │ (LLM) │ │ (LLM) │ │
+ │ └───────────┘ └───────────┘ └───────────┘ │
+ │ │ │
+ │ ┌───────▼───────┐ │
+ │ │ Investigation │ │
+ │ │ Orchestrator │ │
+ │ └───────────────┘ │
+ └─────────────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## 1. Baseline Learning Engine
+
+**📁 Location:** `internal/ai/baseline/store.go`
+
+### What It Does
+
+The baseline engine learns what "normal" looks like for each resource in your environment. Rather than using static thresholds, it builds statistical models from your actual metrics history.
+
+### How It Works
+
+```go
+type MetricBaseline struct {
+ Mean float64 // Average value
+ StdDev float64 // Standard deviation
+ Min float64 // Minimum observed
+ Max float64 // Maximum observed
+ SampleCount int // Number of data points
+ HourlySamples map[int][]float64 // Samples bucketed by hour (0-23)
+}
+```
+
+**Key Features:**
+
+- **Time-of-day awareness**: Tracks hourly buckets to understand that 3pm CPU usage differs from 3am
+- **Z-score anomaly detection**: Flags deviations > 2.0 standard deviations from baseline
+- **Anomaly severity classification**:
+ - `normal`: z-score < 2.0
+ - `mild`: 2.0 ≤ z-score < 2.5
+ - `moderate`: 2.5 ≤ z-score < 3.0
+ - `severe`: 3.0 ≤ z-score < 4.0
+ - `extreme`: z-score ≥ 4.0
+
+```go
+// Anomaly detection with hourly context
+func (s *Store) IsAnomaly(resourceID, metric string, value float64) (bool, float64) {
+ baseline := s.baselines[resourceID]
+ // Use hourly mean if we have enough samples for current hour
+ hourlyMean, usedHourly := baseline.Metrics[metric].GetHourlyMean(time.Now().Hour())
+
+ if usedHourly {
+ zScore = (value - hourlyMean) / baseline.StdDev
+ } else {
+ zScore = (value - baseline.Mean) / baseline.StdDev
+ }
+
+ return math.Abs(zScore) > anomalyThreshold, zScore
+}
+```
+
+**Callback System:**
+```go
+// Event-driven anomaly response
+func (s *Store) SetAnomalyCallback(callback AnomalyCallback) {
+ // Called when anomaly detected — can trigger targeted patrol
+}
+```
+
+---
+
+## 2. Pattern Detection & Prediction
+
+**📁 Location:** `internal/ai/patterns/detector.go`
+
+### What It Does
+
+Tracks historical events and identifies **recurring patterns** to **predict future failures**.
+
+### Event Types Tracked
+
+```go
+const (
+ EventHighMemory = "high_memory" // Memory exceeded threshold
+ EventHighCPU = "high_cpu" // CPU exceeded threshold
+ EventDiskFull = "disk_full" // Disk space critical
+ EventOOMKill = "oom_kill" // Out-of-memory kill
+ EventServiceCrash = "service_crash" // Service crashed
+ EventUnresponsive = "unresponsive" // Resource became unresponsive
+ EventBackupFailed = "backup_failed" // Backup job failed
+)
+```
+
+### Pattern Structure
+
+```go
+type Pattern struct {
+ ResourceID string
+ EventType EventType
+ Occurrences int // How many times this has happened
+ AverageInterval time.Duration // Average time between occurrences
+ LastOccurrence time.Time
+ NextPredicted time.Time // When we expect this to happen again
+ Confidence float64 // 0.0 to 1.0
+ AverageDuration time.Duration // How long events typically last
+}
+```
+
+### Prediction Algorithm
+
+1. **Collect events** by resource and type
+2. **Calculate inter-arrival times** between occurrences
+3. **Apply exponential smoothing** for prediction
+4. **Assign confidence** based on consistency and sample size
+
+```go
+type FailurePrediction struct {
+ ResourceID string
+ EventType EventType
+ PredictedAt time.Time // When we expect the failure
+ DaysUntil float64 // Days until predicted failure
+ Confidence float64 // How confident we are
+ Basis string // "Based on 7 occurrences over 30 days"
+ Pattern *Pattern // The underlying pattern
+}
+```
+
+**Example Output:**
+> "VM `prod-web-1` has experienced `high_memory` events 5 times in the past 14 days with an average interval of 2.8 days. Next occurrence predicted in ~1.5 days (confidence: 0.72)."
+
+---
+
+## 3. Correlation & Root Cause Analysis
+
+**📁 Location:** `internal/ai/correlation/`
+
+### Correlation Detector (`detector.go`)
+
+Tracks when events on one resource are **followed by events on another**, enabling cascade failure prediction.
+
+```go
+type Correlation struct {
+ SourceID string // Resource that has events first
+ SourceName string
+ TargetID string // Resource that has events after
+ TargetName string
+ EventType EventType
+ Occurrences int // How many times this sequence occurred
+ AvgDelay time.Duration // Average time from source to target event
+ Confidence float64
+ Description string // "When storage-1 has disk_full, web-1 crashes within 5 minutes"
+}
+```
+
+**Key Methods:**
+
+```go
+// Get what depends on this resource
+func (d *Detector) GetDependencies(resourceID string) []string
+
+// Get what this resource depends on
+func (d *Detector) GetDependsOn(resourceID string) []string
+
+// Predict cascade effects
+func (d *Detector) PredictCascade(resourceID string, eventType EventType) []CascadePrediction
+```
+
+**Cascade Prediction Example:**
+> "If `storage-1` experiences `disk_full`, expect `web-1` to become `unresponsive` within 3-7 minutes (confidence: 0.85), and `database-1` to experience `service_crash` within 10-15 minutes (confidence: 0.67)."
+
+### Root Cause Engine (`rootcause.go`)
+
+Goes beyond correlation to identify the **underlying cause** of related issues.
+
+```go
+type ResourceRelationship struct {
+ SourceID string
+ TargetID string
+ Relationship RelationshipType // runs_on, uses_storage, uses_network, depends_on, etc.
+}
+
+type RootCauseAnalysis struct {
+ ID string
+ TriggerEvent RelatedEvent // What started the incident
+ RootCause *RelatedEvent // The actual root cause
+ RelatedEvents []RelatedEvent // All related events
+ CausalChain []string // "storage-1 (disk_full) → db-1 (slow) → web-1 (timeout)"
+ Confidence float64
+ Explanation string // Human-readable explanation
+}
+```
+
+**Relationship Types:**
+```go
+const (
+ RelationshipRunsOn = "runs_on" // VM runs on Node
+ RelationshipUsesStorage = "uses_storage" // VM uses Storage pool
+ RelationshipUsesNetwork = "uses_network" // Guest uses Network
+ RelationshipDependsOn = "depends_on" // Generic dependency
+ RelationshipHosted = "hosted" // Container hosted on Docker
+)
+```
+
+---
+
+## 4. Forecast Service
+
+**📁 Location:** `internal/ai/forecast/service.go`
+
+### What It Does
+
+Extrapolates trends to predict when resources will exhaust capacity.
+
+### Trend Analysis
+
+```go
+type Trend struct {
+ Direction TrendDirection // stable, increasing, decreasing, volatile
+ RatePerHour float64 // Change per hour
+ RatePerDay float64 // Change per day
+ Acceleration float64 // Is the rate changing?
+ Seasonality *Seasonality // Daily/weekly patterns
+}
+
+type Seasonality struct {
+ HasDaily bool
+ HasWeekly bool
+ PeakHours []int // e.g., [9, 10, 11, 14, 15, 16]
+ PeakDays []int // e.g., [1, 2, 3, 4, 5] (Mon-Fri)
+}
+```
+
+### Forecasting
+
+```go
+type Forecast struct {
+ ResourceID string
+ Metric string // cpu, memory, disk
+ CurrentValue float64
+ PredictedValue float64 // Value at horizon
+ Trend Trend
+ TimeToThreshold *time.Duration // Time until critical threshold
+ ThresholdValue float64
+ Description string // "Disk will be full in 12 days at current rate"
+}
+```
+
+**Example Output:**
+> "Storage pool `local-zfs` is at 78% and growing +2.3%/day. At this rate, it will reach 95% (critical) in 7.4 days. Weekly pattern detected: higher growth on weekdays. Recommend action by end of week."
+
+---
+
+## 5. Incident Memory System
+
+**📁 Location:** `internal/ai/memory/`
+
+### Incident Store (`incidents.go`)
+
+Maintains full incident timelines with auditability.
+
+```go
+type Incident struct {
+ ID string
+ AlertID string
+ AlertType string
+ ResourceID string
+ ResourceName string
+ Severity string
+ StartedAt time.Time
+ ResolvedAt *time.Time
+ Duration time.Duration
+ Acknowledged bool
+ AckUser string
+ AckTime *time.Time
+ Events []IncidentEvent // Full timeline
+}
+
+type IncidentEvent struct {
+ ID string
+ Type IncidentEventType // alert_fired, acknowledged, analysis, command, resolved
+ Timestamp time.Time
+ Summary string
+ Details map[string]interface{}
+}
+```
+
+**Event Types:**
+- `alert_fired` — Initial alert trigger
+- `alert_acknowledged` — User acknowledged the alert
+- `analysis` — AI analyzed the issue
+- `command` — Command was executed
+- `runbook` — Runbook was triggered
+- `note` — User added a note
+- `resolved` — Alert was resolved
+
+### Remediation Log (`remediation.go`)
+
+Tracks every remediation action for learning and rollback.
+
+```go
+type RemediationRecord struct {
+ ID string
+ Timestamp time.Time
+ ResourceID string
+ ResourceType string
+ ResourceName string
+ FindingID string // Linked to the finding
+ Problem string // What was wrong
+ Action string // What was done
+ Command string // Actual command executed
+ Output string // Command output
+ Outcome Outcome // resolved, partial, failed
+ Duration time.Duration
+ Automatic bool // Was this auto-fix or manual?
+ Rollback *RollbackInfo // Rollback capability
+}
+
+type RollbackInfo struct {
+ Reversible bool
+ RollbackCmd string // Command to undo
+ PreState string // State before action
+ RolledBack bool
+ RolledBackAt *time.Time
+ RolledBackBy string
+ RollbackID string
+}
+```
+
+**Key Capabilities:**
+
+```go
+// Find remediations that worked for similar problems
+func (r *RemediationLog) GetSuccessfulRemediations(problem string, limit int) []RemediationRecord
+
+// Get remediations that can be undone
+func (r *RemediationLog) GetRollbackable(limit int) []RemediationRecord
+
+// Mark a remediation as rolled back
+func (r *RemediationLog) MarkRolledBack(id, rollbackID, username string) error
+```
+
+---
+
+## 6. Knowledge Store
+
+**📁 Location:** `internal/ai/knowledge/store.go`
+
+### What It Does
+
+Stores **persistent, per-resource knowledge** that the AI learns over time, encrypted at rest.
+
+### Note Categories
+
+```go
+const (
+ CategoryService = "service" // What services run here
+ CategoryConfig = "config" // Configuration notes
+ CategoryLearning = "learning" // AI-learned facts
+ CategoryHistory = "history" // Historical context
+ CategoryInfra = "infrastructure" // Auto-discovered facts
+)
+```
+
+### Structure
+
+```go
+type GuestKnowledge struct {
+ GuestID string
+ GuestName string
+ GuestType string
+ Notes []Note
+ UpdatedAt time.Time
+}
+
+type Note struct {
+ ID string
+ Category string
+ Title string
+ Content string
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+```
+
+### Discovery Context Integration
+
+```go
+// Inject discovery context (versions, ports, config paths) into investigations
+func (s *Store) SetDiscoveryContextProvider(provider func() string)
+
+// Scoped context for specific resources
+func (s *Store) GetInfrastructureContextForResources(resourceIDs []string) string
+```
+
+**Example Knowledge:**
+> **Service**: "Runs Jellyfin media server on port 8096, Caddy reverse proxy on 443"
+> **Config**: "Config at /opt/jellyfin/config, database at /var/lib/jellyfin"
+> **Learning**: "High memory usage expected during transcoding — threshold 90% is normal"
+
+---
+
+## 7. Deterministic Signal Detection
+
+**📁 Location:** `internal/ai/patrol_signals.go`
+
+### Philosophy
+
+Patrol combines **LLM judgment** with **deterministic detection** to ensure no issues are missed, even if the LLM overlooks something.
+
+### Signal Types
+
+```go
+const (
+ SignalSMARTFailure = "smart_failure" // SMART health check failed
+ SignalHighCPU = "high_cpu" // CPU exceeded threshold
+ SignalHighMemory = "high_memory" // Memory exceeded threshold
+ SignalHighDisk = "high_disk" // Storage pool filling up
+ SignalBackupFailed = "backup_failed" // Backup task failed
+ SignalBackupStale = "backup_stale" // No backup in 48+ hours
+ SignalActiveAlert = "active_alert" // Critical/warning alert present
+)
+```
+
+### Configurable Thresholds
+
+```go
+type SignalThresholds struct {
+ StorageWarningPercent float64 // Default: 75%
+ StorageCriticalPercent float64 // Default: 95%
+ HighCPUPercent float64 // Default: 70%
+ HighMemoryPercent float64 // Default: 80%
+ BackupStaleThreshold time.Duration // Default: 48 hours
+}
+
+// Thresholds can sync with user-configured alert settings
+func SignalThresholdsFromPatrol(pt PatrolThresholds) SignalThresholds
+```
+
+### Detection Flow
+
+1. **Tool calls complete** during patrol
+2. **DetectSignals()** parses tool outputs for known patterns
+3. **UnmatchedSignals()** compares against findings the LLM reported
+4. **Evaluation pass** — if signals were missed, a focused LLM call reviews them
+5. **Fallback creation** — if still unmatched, deterministic findings are created
+
+---
+
+## 8. Investigation Orchestrator
+
+**📁 Location:** `internal/ai/investigation/`
+
+### Investigation Session
+
+```go
+type InvestigationSession struct {
+ ID string
+ FindingID string
+ SessionID string // Chat session ID
+ Status Status // pending, running, completed, failed, needs_attention
+ StartedAt time.Time
+ CompletedAt *time.Time
+ TurnCount int // Agentic turns used
+ Outcome Outcome
+ ProposedFix *Fix
+ ApprovalID string // If queued for approval
+ ToolsAvailable []string
+ ToolsUsed []string
+ EvidenceIDs []string
+ Summary string
+ Error string
+}
+```
+
+### Configuration
+
+```go
+type InvestigationConfig struct {
+ MaxTurns int // Default: 15
+ Timeout time.Duration // Default: 10 minutes
+ MaxConcurrent int // Default: 3
+ MaxAttemptsPerFinding int // Default: 3
+ CooldownDuration time.Duration // Default: 1 hour
+ TimeoutCooldownDuration time.Duration // Default: 10 minutes (shorter for timeouts)
+ VerificationDelay time.Duration // Default: 30 seconds
+}
+```
+
+### Fix Structure
+
+```go
+type Fix struct {
+ ID string
+ Description string
+ Commands []string
+ RiskLevel string // low, medium, high, critical
+ Destructive bool // Flagged by pattern matching
+ TargetHost string
+ Rationale string
+}
+```
+
+### Destructive Command Detection
+
+Commands are scanned for dangerous patterns:
+- `rm -rf`, `dd if=`, `mkfs.`
+- `shutdown`, `reboot`, `poweroff`
+- `iptables -F`, `ufw disable`
+- Database drops, config wipes
+
+---
+
+## 9. Agentic Patrol Loop
+
+**📁 Location:** `internal/ai/patrol_ai.go`
+
+### Dynamic Turn Budget
+
+```go
+const (
+ patrolMinTurns = 20
+ patrolMaxTurnsLimit = 80
+ patrolTurnsPer50Devices = 5 // +5 turns per 50 devices
+ patrolQuickMinTurns = 10 // Scoped patrols are faster
+ patrolQuickMaxTurns = 30
+)
+
+func computePatrolMaxTurns(resourceCount int, scope *PatrolScope) int {
+ // Scales with environment size
+}
+```
+
+### Patrol Phases
+
+1. **Seed Context Building** — Inventory + thresholds + active findings + notes
+2. **Streaming Analysis** — LLM investigates using MCP tools
+3. **Signal Detection** — Deterministic check on tool outputs
+4. **Evaluation Pass** — Focused review of missed signals
+5. **Stale Finding Reconciliation** — Resolve findings whose issues cleared
+6. **Investigation Triggering** — Queue findings for deep investigation
+
+### Thinking Token Cleanup
+
+Responses from DeepSeek and other models may include internal reasoning markers. Patrol strips these:
+
+```go
+func CleanThinkingTokens(content string) string {
+ // Removes:
+ // - <think>...</think>
+ // - <|end▁of▁thinking|>
+ // - <|DSML|...> (DeepSeek internal format)
+ // - Internal reasoning lines ("Now, ", "Let me ", etc.)
+}
+```
+
+---
+
+## 10. Seed Context (What Patrol Sees)
+
+Every patrol run builds comprehensive context:
+
+| Component | What's Included |
+|-----------|-----------------|
+| **Nodes** | Status, load, uptime, 24h/7d trends, anomaly flags |
+| **VMs/LXCs** | Full metrics, backup status, OCI images, trend direction |
+| **Storage** | Usage %, growth rate, days-to-full prediction |
+| **Docker** | Container counts, health states, update availability |
+| **Kubernetes** | Nodes, pods, deployments, services, namespaces |
+| **PBS** | Datastore status, job outcomes, verification results |
+| **PMG** | Mail queue depths, spam stats, delivery rates |
+| **Agents** | Connection status, permissions, scope restrictions |
+| **Ceph** | Cluster health, OSD states, PG status |
+| **Baselines** | Per-resource learned normal ranges |
+| **Patterns** | Detected recurring issues and predictions |
+| **Correlations** | Known dependencies and cascade risks |
+| **Forecasts** | Capacity predictions for at-risk resources |
+| **Active Findings** | Existing issues being tracked |
+| **User Notes** | Your annotations explaining expected behavior |
+| **Suppression Rules** | What you've dismissed as not-an-issue |
+| **Recent Remediations** | What worked (or failed) recently |
+
+---
+
+## 11. Findings Lifecycle
+
+```
+┌─────────────────────────────────────────────────────────┐
+│ Finding Created │
+│ (by LLM via patrol_report_finding or deterministic) │
+└───────────────────────────┬─────────────────────────────┘
+ │
+ ▼
+ ┌───────────────────────────────┐
+ │ Threshold Validation │
+ │ (Must exceed user thresholds)│
+ └───────────────┬───────────────┘
+ │
+ Pass ◄───────────┼───────────► Reject (filtered out)
+ │
+ ▼
+ ┌───────────────────────────────┐
+ │ Semantic Deduplication │
+ │ (Similar finding already open?)│
+ └───────────────┬───────────────┘
+ │
+ New ◄────────────┼────────────► Merge (bump count)
+ │
+ ▼
+ ┌───────────────────────────────┐
+ │ Finding Stored │
+ │ (ai_findings.json) │
+ └───────────────┬───────────────┘
+ │
+ ┌───────────────┼───────────────┐
+ ▼ ▼ ▼
+ ┌──────┐ ┌──────────┐ ┌────────────┐
+ │Active│ │Investigate│ │ Auto-fix │
+ │(idle)│ │(approval) │ │(autonomous)│
+ └──────┘ └─────┬─────┘ └─────┬──────┘
+ │ │
+ ▼ ▼
+ ┌───────────────────────────┐
+ │ Fix Proposed / Executed │
+ └───────────┬───────────────┘
+ │
+ ▼
+ ┌───────────────────────────┐
+ │ Verification Delay │
+ │ (30 seconds) │
+ └───────────┬───────────────┘
+ │
+ ▼
+ ┌───────────────────────────┐
+ │ Verification Check │
+ │ (Is the issue resolved?) │
+ └───────────┬───────────────┘
+ │
+ ┌──────────────────────┼──────────────────────┐
+ ▼ ▼ ▼
+ ┌─────────┐ ┌────────────┐ ┌──────────────┐
+ │Resolved │ │ Persists │ │Needs Attention│
+ │(closed) │ │(retry later)│ │ (escalate) │
+ └─────────┘ └────────────┘ └──────────────┘
+```
+
+---
+
+## 12. What Makes Patrol Different
+
+| Traditional Alerting | Pulse Patrol |
+|---------------------|--------------|
+| Static thresholds | Learned baselines + context |
+| Single metric | Cross-system correlation |
+| Instant alerts | Trend-aware predictions |
+| No memory | Incident history + pattern learning |
+| Manual investigation | Autonomous investigation |
+| Manual fixes | Verified auto-remediation |
+| Alert fatigue | Noise-controlled findings |
+| Siloed tools | Unified intelligence |
+
+---
+
+## 13. Privacy & Security
+
+- **BYOK**: All AI calls use your API keys to your chosen provider
+- **On-premises**: All processing happens on your Pulse server
+- **Encrypted storage**: Sensitive data (keys, licenses) stored encrypted
+- **Minimal context**: Only necessary data sent to AI providers
+- **No telemetry**: No data sent to Pulse by default
+- **Audit trail**: All actions logged with timestamps and user attribution
+
+---
+
+## Files Reference
+
+| Directory/File | Purpose |
+|----------------|---------|
+| `internal/ai/patrol.go` | Core PatrolService definition, interfaces |
+| `internal/ai/patrol_run.go` | Patrol loop, scoped runs, lifecycle |
+| `internal/ai/patrol_ai.go` | LLM integration, agentic loop, context building |
+| `internal/ai/patrol_signals.go` | Deterministic signal detection |
+| `internal/ai/patrol_findings.go` | Finding CRUD, investigation triggers |
+| `internal/ai/patrol_triggers.go` | Event-driven patrol triggers |
+| `internal/ai/intelligence.go` | Unified intelligence orchestrator |
+| `internal/ai/baseline/` | Baseline learning and anomaly detection |
+| `internal/ai/patterns/` | Pattern detection and failure prediction |
+| `internal/ai/correlation/` | Correlation detection and root cause analysis |
+| `internal/ai/forecast/` | Trend extrapolation and capacity forecasting |
+| `internal/ai/memory/` | Incidents, remediations, context tracking |
+| `internal/ai/knowledge/` | Persistent per-resource knowledge store |
+| `internal/ai/investigation/` | Investigation orchestrator and sessions |
+| `internal/ai/tools/` | MCP tool implementations (50+ tools) |
+
+---
+
+## Summary
+
+Pulse Patrol represents a comprehensive approach to infrastructure intelligence:
+
+1. **It learns** — Baselines, patterns, correlations
+2. **It predicts** — Forecasts, failure predictions, cascade analysis
+3. **It remembers** — Incidents, remediations, knowledge
+4. **It investigates** — Autonomous diagnosis with tool access
+5. **It fixes** — Verified remediation with rollback capability
+6. **It improves** — Tracks what works and learns from outcomes
+
+All running on your infrastructure, with your AI keys, with complete transparency.
diff --git a/internal/ai/chat/agentic_additional_test.go b/internal/ai/chat/agentic_additional_test.go
new file mode 100644
index 0000000000..c468d565b6
--- /dev/null
+++ b/internal/ai/chat/agentic_additional_test.go
@@ -0,0 +1,191 @@
+package chat
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+)
+
+func TestAgenticLoop_Setters(t *testing.T) {
+ loop := &AgenticLoop{}
+ loop.SetMaxTurns(7)
+ if loop.maxTurns != 7 {
+ t.Fatalf("expected maxTurns=7, got %d", loop.maxTurns)
+ }
+
+ loop.SetProviderInfo("provider", "model")
+ if loop.providerName != "provider" || loop.modelName != "model" {
+ t.Fatalf("expected provider/model to be set")
+ }
+
+ called := false
+ loop.SetBudgetChecker(func() error {
+ called = true
+ return nil
+ })
+ if loop.budgetChecker == nil {
+ t.Fatalf("expected budgetChecker to be set")
+ }
+ _ = loop.budgetChecker()
+ if !called {
+ t.Fatalf("expected budgetChecker to be invoked")
+ }
+}
+
+func TestPruneMessagesForModel_Stateless(t *testing.T) {
+ prev := StatelessContext
+ StatelessContext = true
+ defer func() { StatelessContext = prev }()
+
+ messages := []Message{
+ {Role: "user", Content: "first"},
+ {Role: "assistant", Content: "ok"},
+ {Role: "user", Content: "second"},
+ {Role: "assistant", Content: "done"},
+ }
+
+ pruned := pruneMessagesForModel(messages)
+ if len(pruned) != 1 {
+ t.Fatalf("expected 1 message, got %d", len(pruned))
+ }
+ if pruned[0].Content != "second" {
+ t.Fatalf("expected last user message to be kept")
+ }
+}
+
+func TestPruneMessagesForModel_SkipsOrphanedToolResults(t *testing.T) {
+ // Build a message list longer than MaxContextMessagesLimit so pruning occurs.
+ messages := make([]Message, 0, MaxContextMessagesLimit+2)
+ messages = append(messages, Message{Role: "user", Content: "a"})
+ messages = append(messages, Message{Role: "assistant", Content: "b"})
+ // This tool result should be dropped if it becomes the first item after pruning.
+ messages = append(messages, Message{Role: "assistant", ToolResult: &ToolResult{Content: "tool"}})
+ for i := 0; i < MaxContextMessagesLimit; i++ {
+ messages = append(messages, Message{Role: "user", Content: "msg"})
+ }
+
+ pruned := pruneMessagesForModel(messages)
+ if len(pruned) == 0 {
+ t.Fatalf("expected pruned messages")
+ }
+ if pruned[0].ToolResult != nil {
+ t.Fatalf("expected leading tool result to be pruned")
+ }
+}
+
+func TestPruneMessagesForModel_SkipsAssistantWithToolCalls(t *testing.T) {
+ // Ensure assistant tool calls at the start of the pruned window are skipped.
+ messages := make([]Message, 0, MaxContextMessagesLimit+3)
+ messages = append(messages, Message{Role: "user", Content: "seed"})
+ messages = append(messages, Message{Role: "assistant", Content: "seed"})
+ messages = append(messages, Message{Role: "assistant", ToolCalls: []ToolCall{{Name: "pulse_query"}}})
+ messages = append(messages, Message{Role: "assistant", ToolResult: &ToolResult{Content: "result"}})
+ for i := 0; i < MaxContextMessagesLimit; i++ {
+ messages = append(messages, Message{Role: "user", Content: "msg"})
+ }
+
+ pruned := pruneMessagesForModel(messages)
+ if len(pruned) == 0 {
+ t.Fatalf("expected pruned messages")
+ }
+ if pruned[0].Role == "assistant" && len(pruned[0].ToolCalls) > 0 {
+ t.Fatalf("expected assistant tool-call message to be pruned")
+ }
+ if pruned[0].ToolResult != nil {
+ t.Fatalf("expected tool result following pruned tool call to be removed")
+ }
+}
+
+type stubStreamingProvider struct {
+ lastRequest providers.ChatRequest
+ chatStream func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error
+}
+
+func (s *stubStreamingProvider) Chat(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {
+ return &providers.ChatResponse{Content: "ok"}, nil
+}
+
+func (s *stubStreamingProvider) ChatStream(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ s.lastRequest = req
+ if s.chatStream != nil {
+ return s.chatStream(ctx, req, callback)
+ }
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "summary"}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{InputTokens: 1, OutputTokens: 1}})
+ return nil
+}
+
+func (s *stubStreamingProvider) SupportsThinking(model string) bool { return false }
+func (s *stubStreamingProvider) TestConnection(ctx context.Context) error { return nil }
+func (s *stubStreamingProvider) Name() string { return "stub" }
+func (s *stubStreamingProvider) ListModels(ctx context.Context) ([]providers.ModelInfo, error) {
+ return nil, nil
+}
+
+func TestEnsureFinalTextResponse(t *testing.T) {
+ provider := &stubStreamingProvider{}
+ loop := &AgenticLoop{provider: provider, baseSystemPrompt: "prompt"}
+
+ result := loop.ensureFinalTextResponse(
+ context.Background(),
+ "session-1",
+ []Message{{Role: "assistant", Content: ""}},
+ []providers.Message{{Role: "assistant", Content: ""}},
+ func(event StreamEvent) {},
+ )
+ if len(result) != 2 {
+ t.Fatalf("expected summary message to be appended")
+ }
+ if provider.lastRequest.ToolChoice == nil || provider.lastRequest.ToolChoice.Type != providers.ToolChoiceNone {
+ t.Fatalf("expected summary call to enforce text-only tool choice")
+ }
+
+ provider.chatStream = func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ return errors.New("boom")
+ }
+ result2 := loop.ensureFinalTextResponse(
+ context.Background(),
+ "session-2",
+ []Message{{Role: "assistant", Content: ""}},
+ []providers.Message{{Role: "assistant", Content: ""}},
+ func(event StreamEvent) {},
+ )
+ if len(result2) != 1 {
+ t.Fatalf("expected no summary message when provider errors")
+ }
+}
+
+func TestTryAutoRecoveryAndCommandExtraction(t *testing.T) {
+ result := tools.CallToolResult{
+ Content: []tools.Content{{Type: "text", Text: `{"error":{"details":{"auto_recoverable":true,"suggested_rewrite":"pulse_query action=get","category":"strict"}}}`}},
+ IsError: true,
+ }
+ rewrite, attempted := tryAutoRecovery(result, providers.ToolCall{Input: map[string]interface{}{}}, nil, context.Background())
+ if attempted || rewrite == "" {
+ t.Fatalf("expected suggested rewrite and no prior attempt")
+ }
+
+ alt := tools.CallToolResult{
+ Content: []tools.Content{{Type: "text", Text: `{"error":5,"auto_recoverable":true,"suggested_rewrite":"pulse_query action=list"}`}},
+ IsError: true,
+ }
+ rewrite, _ = tryAutoRecovery(alt, providers.ToolCall{Input: map[string]interface{}{}}, nil, context.Background())
+ if rewrite == "" {
+ t.Fatalf("expected suggested rewrite from alternate format")
+ }
+
+ rewrite, attempted = tryAutoRecovery(result, providers.ToolCall{Input: map[string]interface{}{"_auto_recovery_attempt": true}}, nil, context.Background())
+ if !attempted || rewrite != "" {
+ t.Fatalf("expected auto recovery to be skipped when already attempted")
+ }
+
+ if cmd := getCommandFromInput(map[string]interface{}{"command": "ls"}); cmd != "ls" {
+ t.Fatalf("expected command to be extracted")
+ }
+ if cmd := getCommandFromInput(map[string]interface{}{}); cmd != "<unknown>" {
+ t.Fatalf("expected fallback command string")
+ }
+}
diff --git a/internal/ai/chat/context_prefetch_additional_test.go b/internal/ai/chat/context_prefetch_additional_test.go
new file mode 100644
index 0000000000..3b9a4b3b7d
--- /dev/null
+++ b/internal/ai/chat/context_prefetch_additional_test.go
@@ -0,0 +1,323 @@
+package chat
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+type mockPrefetchStateProvider struct {
+ state models.StateSnapshot
+}
+
+func (m mockPrefetchStateProvider) GetState() models.StateSnapshot {
+ return m.state
+}
+
+type mockDiscoveryProvider struct {
+ existing map[string]*tools.ResourceDiscoveryInfo
+ triggeredKey []string
+ triggerErr error
+}
+
+func (m *mockDiscoveryProvider) key(resourceType, hostID, resourceID string) string {
+ return resourceType + ":" + hostID + ":" + resourceID
+}
+
+func (m *mockDiscoveryProvider) GetDiscovery(id string) (*tools.ResourceDiscoveryInfo, error) {
+ return nil, nil
+}
+
+func (m *mockDiscoveryProvider) GetDiscoveryByResource(resourceType, hostID, resourceID string) (*tools.ResourceDiscoveryInfo, error) {
+ if m.existing == nil {
+ return nil, nil
+ }
+ return m.existing[m.key(resourceType, hostID, resourceID)], nil
+}
+
+func (m *mockDiscoveryProvider) ListDiscoveries() ([]*tools.ResourceDiscoveryInfo, error) {
+ return nil, nil
+}
+
+func (m *mockDiscoveryProvider) ListDiscoveriesByType(resourceType string) ([]*tools.ResourceDiscoveryInfo, error) {
+ return nil, nil
+}
+
+func (m *mockDiscoveryProvider) ListDiscoveriesByHost(hostID string) ([]*tools.ResourceDiscoveryInfo, error) {
+ return nil, nil
+}
+
+func (m *mockDiscoveryProvider) FormatForAIContext(discoveries []*tools.ResourceDiscoveryInfo) string {
+ return ""
+}
+
+func (m *mockDiscoveryProvider) TriggerDiscovery(ctx context.Context, resourceType, hostID, resourceID string) (*tools.ResourceDiscoveryInfo, error) {
+ m.triggeredKey = append(m.triggeredKey, m.key(resourceType, hostID, resourceID))
+ if m.triggerErr != nil {
+ return nil, m.triggerErr
+ }
+ return &tools.ResourceDiscoveryInfo{
+ ResourceType: resourceType,
+ HostID: hostID,
+ ResourceID: resourceID,
+ Hostname: hostID,
+ ServiceType: "nginx",
+ ServiceName: "nginx",
+ ConfigPaths: []string{"/etc/nginx/nginx.conf"},
+ LogPaths: []string{"/var/log/nginx/error.log"},
+ }, nil
+}
+
+func TestContextPrefetcher_NoStateProvider(t *testing.T) {
+ prefetcher := NewContextPrefetcher(nil, nil)
+ if ctx := prefetcher.Prefetch(context.Background(), "check @missing", nil); ctx != nil {
+ t.Fatalf("expected nil context when state provider missing")
+ }
+}
+
+func TestContextPrefetcher_UnresolvedMention(t *testing.T) {
+ state := models.StateSnapshot{}
+ prefetcher := NewContextPrefetcher(mockPrefetchStateProvider{state: state}, nil)
+ ctx := prefetcher.Prefetch(context.Background(), "check @missing", nil)
+ if ctx == nil || !strings.Contains(ctx.Summary, "NOT found") {
+ t.Fatalf("expected unresolved mention summary, got %#v", ctx)
+ }
+}
+
+func TestContextPrefetcher_ExtractResourceMentions(t *testing.T) {
+ state := models.StateSnapshot{
+ Nodes: []models.Node{{ID: "node1", Name: "node1"}},
+ VMs: []models.VM{{ID: "vm-1", Name: "alpha", VMID: 101, Node: "node1"}},
+ Containers: []models.Container{{ID: "lxc-1", Name: "beta", VMID: 201, Node: "node1", Type: "lxc"}},
+ DockerHosts: []models.DockerHost{{
+ ID: "dock1",
+ Hostname: "dock1",
+ Containers: []models.DockerContainer{{
+ ID: "cid1",
+ Name: "homepage",
+ State: "running",
+ Mounts: []models.DockerContainerMount{{
+ Source: "/data",
+ Destination: "/config",
+ }},
+ }},
+ }},
+ Hosts: []models.Host{{ID: "host1", Hostname: "host1"}},
+ KubernetesClusters: []models.KubernetesCluster{{
+ ID: "k8s1",
+ Name: "k8s",
+ AgentID: "agent-1",
+ Pods: []models.KubernetesPod{{
+ Name: "pod1",
+ Namespace: "default",
+ }},
+ Deployments: []models.KubernetesDeployment{{
+ Name: "dep1",
+ Namespace: "default",
+ }},
+ }},
+ }
+
+ prefetcher := NewContextPrefetcher(mockPrefetchStateProvider{state: state}, nil)
+ mentions := prefetcher.extractResourceMentions("alpha beta homepage node1 host1 pod1 dep1", state)
+ if len(mentions) == 0 {
+ t.Fatalf("expected mentions to be detected")
+ }
+
+ foundDocker := false
+ for _, m := range mentions {
+ if m.ResourceType == "docker" && m.Name == "homepage" {
+ foundDocker = true
+ if m.TargetHost == "" {
+ t.Fatalf("expected docker mention to have target host")
+ }
+ if len(m.BindMounts) == 0 {
+ t.Fatalf("expected docker bind mounts to be captured")
+ }
+ }
+ }
+ if !foundDocker {
+ t.Fatalf("expected docker mention")
+ }
+}
+
+func TestContextPrefetcher_ResolveStructuredMentions(t *testing.T) {
+ state := models.StateSnapshot{
+ DockerHosts: []models.DockerHost{{
+ ID: "dock1",
+ Hostname: "dock1",
+ Containers: []models.DockerContainer{{
+ ID: "cid:part",
+ Name: "homepage",
+ Mounts: []models.DockerContainerMount{{
+ Source: "/data",
+ Destination: "/config",
+ }},
+ }},
+ }},
+ Hosts: []models.Host{{ID: "host1", Hostname: "host1"}},
+ }
+
+ prefetcher := NewContextPrefetcher(mockPrefetchStateProvider{state: state}, nil)
+ structured := []StructuredMention{
+ {ID: "docker:dock1:cid:part", Name: "homepage", Type: "docker"},
+ {ID: "host:host1", Name: "host1", Type: "host"},
+ {ID: "container:node1:201", Name: "beta", Type: "container", Node: "node1"},
+ }
+
+ mentions := prefetcher.resolveStructuredMentions(structured, state)
+ if len(mentions) != 3 {
+ t.Fatalf("expected 3 mentions, got %d", len(mentions))
+ }
+
+ if mentions[0].ResourceID != "cid:part" {
+ t.Fatalf("expected container ID with colons preserved, got %q", mentions[0].ResourceID)
+ }
+ if len(mentions[0].BindMounts) == 0 {
+ t.Fatalf("expected bind mounts on docker mention")
+ }
+ if mentions[1].ResourceType != "host" {
+ t.Fatalf("expected host mention, got %q", mentions[1].ResourceType)
+ }
+ if mentions[2].ResourceType != "lxc" {
+ t.Fatalf("expected container type normalized to lxc, got %q", mentions[2].ResourceType)
+ }
+
+ unknown := prefetcher.resolveStructuredMentions([]StructuredMention{{ID: "weird:1", Name: "mystery", Type: "weird"}}, state)
+ if len(unknown) != 1 || unknown[0].ResourceType != "weird" {
+ t.Fatalf("expected unknown type to be preserved")
+ }
+}
+
+func TestContextPrefetcher_GetOrTriggerDiscovery(t *testing.T) {
+ provider := &mockDiscoveryProvider{existing: map[string]*tools.ResourceDiscoveryInfo{}}
+ prefetcher := NewContextPrefetcher(mockPrefetchStateProvider{}, provider)
+
+ provider.existing[provider.key("vm", "node1", "101")] = &tools.ResourceDiscoveryInfo{
+ ResourceType: "vm",
+ HostID: "node1",
+ ResourceID: "101",
+ }
+
+ mention := ResourceMention{ResourceType: "vm", HostID: "node1", ResourceID: "101", Name: "alpha"}
+ res, err := prefetcher.getOrTriggerDiscovery(context.Background(), mention)
+ if err != nil || res == nil {
+ t.Fatalf("expected cached discovery, got err=%v res=%v", err, res)
+ }
+ if len(provider.triggeredKey) != 0 {
+ t.Fatalf("expected no trigger when cached discovery exists")
+ }
+
+ mention2 := ResourceMention{ResourceType: "docker", HostID: "dock1", ResourceID: "cid1", Name: "homepage"}
+ res, err = prefetcher.getOrTriggerDiscovery(context.Background(), mention2)
+ if err != nil || res == nil {
+ t.Fatalf("expected discovery trigger to succeed")
+ }
+ if len(provider.triggeredKey) != 1 {
+ t.Fatalf("expected trigger to be called once")
+ }
+
+ mention3 := ResourceMention{ResourceType: "host", HostID: "host1", ResourceID: "host1", Name: "host1"}
+ res, err = prefetcher.getOrTriggerDiscovery(context.Background(), mention3)
+ if err != nil || res != nil {
+ t.Fatalf("expected no discovery for host type")
+ }
+}
+
+func TestContextPrefetcher_FormatContextSummary(t *testing.T) {
+ prefetcher := NewContextPrefetcher(mockPrefetchStateProvider{}, nil)
+
+ mentions := []ResourceMention{
+ {
+ Name: "homepage",
+ ResourceType: "docker",
+ ResourceID: "cid1",
+ HostID: "dock1",
+ DockerHostName: "dock1",
+ DockerHostType: "standalone",
+ TargetHost: "dock1",
+ BindMounts: []MountInfo{{Source: "/data", Destination: "/config"}},
+ },
+ {
+ Name: "beta",
+ ResourceType: "lxc",
+ ResourceID: "201",
+ HostID: "node1",
+ },
+ }
+
+ discoveries := []*tools.ResourceDiscoveryInfo{{
+ ResourceType: "docker",
+ HostID: "dock1",
+ ResourceID: "cid1",
+ Hostname: "dock1",
+ ConfigPaths: []string{"/etc/homepage/config"},
+ LogPaths: []string{"/var/log/homepage.log"},
+ }, {
+ ResourceType: "lxc",
+ HostID: "node1",
+ ResourceID: "201",
+ Hostname: "node1",
+ LogPaths: []string{"journalctl -u service"},
+ DataPaths: []string{"/var/lib/service"},
+ }}
+
+ summary := prefetcher.formatContextSummary(mentions, discoveries)
+ if !strings.Contains(summary, "Docker container") {
+ t.Fatalf("expected docker context in summary")
+ }
+ if !strings.Contains(summary, "target_host") {
+ t.Fatalf("expected target_host in summary")
+ }
+ if !strings.Contains(summary, "VMID") && !strings.Contains(summary, "Type: lxc") {
+ t.Fatalf("expected LXC mention details in summary")
+ }
+ if !strings.Contains(summary, "Log commands") {
+ t.Fatalf("expected log command formatting in summary")
+ }
+}
+
+func TestContextPrefetcher_ExtractHelpers(t *testing.T) {
+ words := extractWords("hello-123 world")
+ if len(words) != 3 {
+ t.Fatalf("expected 3 words, got %d", len(words))
+ }
+
+ mentions := extractExplicitAtMentions("ping @alpha and @beta")
+ if len(mentions) != 2 {
+ t.Fatalf("expected 2 mentions, got %d", len(mentions))
+ }
+
+ if !matchesResource("homepage docker", []string{"homepage"}, "homepage-docker") {
+ t.Fatalf("expected fuzzy match to succeed")
+ }
+}
+
+func TestContextPrefetcher_PrefetchStructuredMentions(t *testing.T) {
+ state := models.StateSnapshot{
+ VMs: []models.VM{{ID: "vm-1", Name: "alpha", VMID: 101, Node: "node1"}},
+ }
+ provider := &mockDiscoveryProvider{existing: map[string]*tools.ResourceDiscoveryInfo{
+ "vm:node1:101": {
+ ResourceType: "vm",
+ HostID: "node1",
+ ResourceID: "101",
+ Hostname: "node1",
+ ServiceType: "nginx",
+ },
+ }}
+
+ prefetcher := NewContextPrefetcher(mockPrefetchStateProvider{state: state}, provider)
+ ctx := prefetcher.Prefetch(context.Background(), "@alpha", []StructuredMention{
+ {ID: "vm:node1:101", Name: "alpha", Type: "vm", Node: "node1"},
+ })
+ if ctx == nil || len(ctx.Mentions) != 1 {
+ t.Fatalf("expected structured mention to be resolved")
+ }
+ if !strings.Contains(ctx.Summary, "alpha") {
+ t.Fatalf("expected summary to include resource name")
+ }
+}
diff --git a/internal/ai/chat/fsm_additional_test.go b/internal/ai/chat/fsm_additional_test.go
new file mode 100644
index 0000000000..9c0d181ec6
--- /dev/null
+++ b/internal/ai/chat/fsm_additional_test.go
@@ -0,0 +1,34 @@
+package chat
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestFSMBlockedErrorFormatting(t *testing.T) {
+ err := &FSMBlockedError{
+ State: StateWriting,
+ ToolName: "pulse_control",
+ ToolKind: ToolKindWrite,
+ Reason: "requires approval",
+ }
+ msg := err.Error()
+ if !strings.Contains(msg, "pulse_control") {
+ t.Fatalf("expected tool name in error message")
+ }
+ if err.Code() != "FSM_BLOCKED" {
+ t.Fatalf("expected FSM_BLOCKED code")
+ }
+
+ err = &FSMBlockedError{State: StateReading, Reason: "test"}
+ if !strings.Contains(err.Error(), string(StateReading)) {
+ t.Fatalf("expected state in error message")
+ }
+}
+
+func TestToolKindStringUnknown(t *testing.T) {
+ var k ToolKind = 99
+ if k.String() != "unknown" {
+ t.Fatalf("expected unknown for invalid tool kind")
+ }
+}
diff --git a/internal/ai/chat/metrics_additional_test.go b/internal/ai/chat/metrics_additional_test.go
new file mode 100644
index 0000000000..22cf3be976
--- /dev/null
+++ b/internal/ai/chat/metrics_additional_test.go
@@ -0,0 +1,28 @@
+package chat
+
+import "testing"
+
+func TestAIMetricsRecording(t *testing.T) {
+ m := GetAIMetrics()
+ if sanitizeLabel("") != "unknown" {
+ t.Fatalf("expected empty label to be sanitized")
+ }
+ if sanitizeLabel("has space") != "has_space" {
+ t.Fatalf("expected spaces to be replaced")
+ }
+
+ m.RecordFSMToolBlock(StateReading, "pulse_query", ToolKindResolve)
+ m.RecordFSMFinalBlock(StateResolving)
+ m.RecordStrictResolutionBlock("validateResolvedResource", "restart")
+ m.RecordRoutingMismatchBlock("pulse_control", "node", "vm")
+ m.RecordPhantomDetected("provider", "model")
+ m.RecordAutoRecoveryAttempt("STRICT_RESOLUTION", "pulse_query")
+ m.RecordAutoRecoverySuccess("STRICT_RESOLUTION", "pulse_query")
+ m.RecordAgenticIteration("provider", "model")
+
+ cb := NewAIMetricsTelemetryCallback()
+ cb.RecordStrictResolutionBlock("validateResolvedResource", "start")
+ cb.RecordAutoRecoveryAttempt("ERR", "tool")
+ cb.RecordAutoRecoverySuccess("ERR", "tool")
+ cb.RecordRoutingMismatchBlock("pulse_control", "node", "vm")
+}
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 5cde3f73d7..c3a438b7b1 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -78,6 +78,7 @@ type Service struct {
sessions *SessionStore
agenticLoop *AgenticLoop
provider providers.StreamingProvider
+ providerFactory func(modelStr string) (providers.StreamingProvider, error)
started bool
autonomousMode bool
contextPrefetcher *ContextPrefetcher
@@ -701,6 +702,9 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca
// createProviderForModel creates a streaming provider for a specific model string (provider:model format).
func (s *Service) createProviderForModel(modelStr string) (providers.StreamingProvider, error) {
+ if s.providerFactory != nil {
+ return s.providerFactory(modelStr)
+ }
if s.cfg == nil {
return nil, fmt.Errorf("no Pulse Assistant config")
}
@@ -1147,51 +1151,7 @@ func (s *Service) createProvider() (providers.StreamingProvider, error) {
return nil, fmt.Errorf("no chat model configured")
}
- // Parse provider:model format
- parts := strings.SplitN(chatModel, ":", 2)
- if len(parts) != 2 {
- return nil, fmt.Errorf("invalid model format: %s (expected provider:model)", chatModel)
- }
- providerName := parts[0]
- modelName := parts[1]
-
- timeout := 5 * time.Minute
-
- switch providerName {
- case "anthropic":
- if s.cfg.AnthropicAPIKey == "" {
- return nil, fmt.Errorf("Anthropic API key not configured")
- }
- return providers.NewAnthropicClient(s.cfg.AnthropicAPIKey, modelName, timeout), nil
-
- case "openai":
- if s.cfg.OpenAIAPIKey == "" {
- return nil, fmt.Errorf("OpenAI API key not configured")
- }
- return providers.NewOpenAIClient(s.cfg.OpenAIAPIKey, modelName, "", timeout), nil
-
- case "deepseek":
- if s.cfg.DeepSeekAPIKey == "" {
- return nil, fmt.Errorf("DeepSeek API key not configured")
- }
- return providers.NewOpenAIClient(s.cfg.DeepSeekAPIKey, modelName, "https://api.deepseek.com", timeout), nil
-
- case "gemini":
- if s.cfg.GeminiAPIKey == "" {
- return nil, fmt.Errorf("Gemini API key not configured")
- }
- return providers.NewGeminiClient(s.cfg.GeminiAPIKey, modelName, "", timeout), nil
-
- case "ollama":
- baseURL := s.cfg.OllamaBaseURL
- if baseURL == "" {
- baseURL = "http://localhost:11434"
- }
- return providers.NewOllamaClient(modelName, baseURL, timeout), nil
-
- default:
- return nil, fmt.Errorf("unsupported provider: %s", providerName)
- }
+ return s.createProviderForModel(chatModel)
}
func (s *Service) applyChatContextSettings() {
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
new file mode 100644
index 0000000000..13cea1638a
--- /dev/null
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -0,0 +1,145 @@
+package chat
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+type stubServiceProvider struct {
+ streamFn func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error
+}
+
+func (s *stubServiceProvider) Chat(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {
+ return &providers.ChatResponse{Content: "ok", Model: req.Model}, nil
+}
+
+func (s *stubServiceProvider) TestConnection(ctx context.Context) error { return nil }
+
+func (s *stubServiceProvider) Name() string { return "stub" }
+
+func (s *stubServiceProvider) ListModels(ctx context.Context) ([]providers.ModelInfo, error) {
+ return nil, nil
+}
+
+func (s *stubServiceProvider) ChatStream(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ if s.streamFn != nil {
+ return s.streamFn(ctx, req, callback)
+ }
+ callback(providers.StreamEvent{
+ Type: "content",
+ Data: providers.ContentEvent{Text: "hello"},
+ })
+ callback(providers.StreamEvent{
+ Type: "done",
+ Data: providers.DoneEvent{InputTokens: 1, OutputTokens: 1},
+ })
+ return nil
+}
+
+func (s *stubServiceProvider) SupportsThinking(model string) bool { return false }
+
+func TestService_ExecuteStream_Success(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ provider := &stubServiceProvider{}
+ loop := NewAgenticLoop(provider, executor, "system")
+
+ svc := &Service{
+ cfg: &config.AIConfig{ChatModel: "openai:test"},
+ sessions: store,
+ executor: executor,
+ agenticLoop: loop,
+ started: true,
+ }
+
+ var doneCount int
+ callback := func(event StreamEvent) {
+ if event.Type == "done" {
+ doneCount++
+ }
+ }
+
+ req := ExecuteRequest{
+ SessionID: "sess-1",
+ Prompt: "hello",
+ }
+ if err := svc.ExecuteStream(context.Background(), req, callback); err != nil {
+ t.Fatalf("ExecuteStream failed: %v", err)
+ }
+ if doneCount != 1 {
+ t.Fatalf("expected done callback once, got %d", doneCount)
+ }
+
+ messages, err := store.GetMessages("sess-1")
+ if err != nil {
+ t.Fatalf("GetMessages failed: %v", err)
+ }
+ if len(messages) < 2 {
+ t.Fatalf("expected at least 2 messages, got %d", len(messages))
+ }
+}
+
+func TestService_ExecuteStream_PrefetchMentionsAndOverrideModel(t *testing.T) {
+ tmpDir := t.TempDir()
+ store, err := NewSessionStore(tmpDir)
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ provider := &stubServiceProvider{}
+ loop := NewAgenticLoop(provider, executor, "system")
+
+ state := models.StateSnapshot{
+ VMs: []models.VM{
+ {ID: "vm:node1:101", VMID: 101, Name: "vm1", Node: "node1", Status: "running"},
+ },
+ }
+
+ var capturedModel string
+ svc := &Service{
+ cfg: &config.AIConfig{ChatModel: "openai:primary"},
+ sessions: store,
+ executor: executor,
+ agenticLoop: loop,
+ contextPrefetcher: NewContextPrefetcher(&mockStateProvider{state: state}, nil),
+ started: true,
+ providerFactory: func(modelStr string) (providers.StreamingProvider, error) {
+ capturedModel = modelStr
+ return provider, nil
+ },
+ }
+
+ autonomous := true
+ req := ExecuteRequest{
+ SessionID: "sess-2",
+ Prompt: "check @vm1",
+ Model: "openai:override",
+ Mentions: []StructuredMention{{ID: "vm:node1:101", Name: "vm1", Type: "vm", Node: "node1"}},
+ MaxTurns: 1,
+ AutonomousMode: &autonomous,
+ }
+
+ if err := svc.ExecuteStream(context.Background(), req, func(StreamEvent) {}); err != nil {
+ t.Fatalf("ExecuteStream failed: %v", err)
+ }
+ if capturedModel != "openai:override" {
+ t.Fatalf("expected override model to be used, got %q", capturedModel)
+ }
+
+ resolved := store.GetResolvedContext("sess-2")
+ if !resolved.WasRecentlyAccessed("vm:node1:101", time.Minute) {
+ t.Fatal("expected explicit access to be recorded for structured mention")
+ }
+}
diff --git a/internal/ai/chat/service_patrol_additional_test.go b/internal/ai/chat/service_patrol_additional_test.go
new file mode 100644
index 0000000000..c4424a65c4
--- /dev/null
+++ b/internal/ai/chat/service_patrol_additional_test.go
@@ -0,0 +1,248 @@
+package chat
+
+import (
+ "context"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+type mockKnowledgeStore struct{}
+
+func (m mockKnowledgeStore) SaveNote(resourceID, note, category string) error { return nil }
+func (m mockKnowledgeStore) GetKnowledge(resourceID, category string) []tools.KnowledgeEntry {
+ return nil
+}
+
+type mockStreamingProvider struct {
+ chatStreamFunc func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error
+ lastRequest providers.ChatRequest
+}
+
+func (m *mockStreamingProvider) Chat(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {
+ return &providers.ChatResponse{Content: "ok"}, nil
+}
+
+func (m *mockStreamingProvider) ChatStream(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ m.lastRequest = req
+ if m.chatStreamFunc != nil {
+ return m.chatStreamFunc(ctx, req, callback)
+ }
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "hello"}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{InputTokens: 1, OutputTokens: 1}})
+ return nil
+}
+
+func (m *mockStreamingProvider) SupportsThinking(model string) bool { return false }
+func (m *mockStreamingProvider) TestConnection(ctx context.Context) error { return nil }
+func (m *mockStreamingProvider) Name() string { return "mock" }
+func (m *mockStreamingProvider) ListModels(ctx context.Context) ([]providers.ModelInfo, error) {
+ return nil, nil
+}
+
+func TestService_CreateProviderForModel(t *testing.T) {
+ svc := &Service{}
+ if _, err := svc.createProviderForModel("bad"); err == nil {
+ t.Fatalf("expected error with nil config")
+ }
+
+ svc.cfg = &config.AIConfig{}
+ if _, err := svc.createProviderForModel("bad"); err == nil {
+ t.Fatalf("expected invalid model format error")
+ }
+
+ if _, err := svc.createProviderForModel("unknown:model"); err == nil {
+ t.Fatalf("expected unsupported provider error")
+ }
+
+ if _, err := svc.createProviderForModel("ollama:llama3"); err != nil {
+ t.Fatalf("expected ollama provider to be created: %v", err)
+ }
+
+ svc.cfg = &config.AIConfig{
+ OpenAIAPIKey: "sk-test",
+ AnthropicAPIKey: "ak-test",
+ GeminiAPIKey: "gk-test",
+ DeepSeekAPIKey: "dk-test",
+ OllamaBaseURL: "http://localhost:11434",
+ PatrolModel: "openai:gpt-4",
+ }
+ if _, err := svc.createProviderForModel("openai:gpt-4"); err != nil {
+ t.Fatalf("expected openai provider: %v", err)
+ }
+ if _, err := svc.createProviderForModel("anthropic:claude-3"); err != nil {
+ t.Fatalf("expected anthropic provider: %v", err)
+ }
+ if _, err := svc.createProviderForModel("gemini:gemini-1.5"); err != nil {
+ t.Fatalf("expected gemini provider: %v", err)
+ }
+ if _, err := svc.createProviderForModel("deepseek:deepseek-chat"); err != nil {
+ t.Fatalf("expected deepseek provider: %v", err)
+ }
+}
+
+func TestService_ExecutePatrolStream_Success(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+
+ service := &Service{
+ started: true,
+ sessions: store,
+ executor: executor,
+ cfg: &config.AIConfig{PatrolModel: "mock:model"},
+ }
+
+ mockProvider := &mockStreamingProvider{
+ chatStreamFunc: func(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ callback(providers.StreamEvent{Type: "content", Data: providers.ContentEvent{Text: "Patrol ok"}})
+ callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{InputTokens: 3, OutputTokens: 2}})
+ return nil
+ },
+ }
+ var modelUsed string
+ service.providerFactory = func(modelStr string) (providers.StreamingProvider, error) {
+ modelUsed = modelStr
+ return mockProvider, nil
+ }
+
+ doneCount := 0
+ resp, err := service.ExecutePatrolStream(context.Background(), PatrolRequest{
+ Prompt: "check status",
+ MaxTurns: 1,
+ SessionID: "",
+ }, func(event StreamEvent) {
+ if event.Type == "done" {
+ doneCount++
+ }
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if resp == nil || resp.Content == "" {
+ t.Fatalf("expected response content")
+ }
+ if modelUsed != "mock:model" {
+ t.Fatalf("expected provider factory to be called with patrol model")
+ }
+ if mockProvider.lastRequest.System == "" {
+ t.Fatalf("expected system prompt to be set")
+ }
+ if doneCount != 1 {
+ t.Fatalf("expected done event to be emitted")
+ }
+
+ msgs, err := store.GetMessages("patrol-main")
+ if err != nil {
+ t.Fatalf("failed to fetch messages: %v", err)
+ }
+ if len(msgs) < 2 {
+ t.Fatalf("expected at least 2 messages saved, got %d", len(msgs))
+ }
+}
+
+func TestService_ExecutePatrolStream_Errors(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+
+ service := &Service{
+ started: false,
+ sessions: store,
+ executor: executor,
+ }
+
+ if _, err := service.ExecutePatrolStream(context.Background(), PatrolRequest{Prompt: "hi"}, func(StreamEvent) {}); err == nil {
+ t.Fatalf("expected service not started error")
+ }
+
+ service.started = true
+ service.cfg = &config.AIConfig{}
+ if _, err := service.ExecutePatrolStream(context.Background(), PatrolRequest{Prompt: "hi"}, func(StreamEvent) {}); err == nil {
+ t.Fatalf("expected no patrol model configured error")
+ }
+
+ service.cfg.PatrolModel = "bad"
+ if _, err := service.ExecutePatrolStream(context.Background(), PatrolRequest{Prompt: "hi"}, func(StreamEvent) {}); err == nil {
+ t.Fatalf("expected provider creation error")
+ }
+}
+
+func TestService_ListAvailableToolsAndSetters(t *testing.T) {
+ stateProvider := &mockStateProvider{state: models.StateSnapshot{}}
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{StateProvider: stateProvider})
+
+ service := &Service{executor: executor, stateProvider: stateProvider}
+ service.SetGuestConfigProvider(nil)
+ service.SetBudgetChecker(func() error { return nil })
+
+ discoveryProvider := &mockDiscoveryProvider{}
+ service.SetDiscoveryProvider(discoveryProvider)
+ if service.contextPrefetcher == nil {
+ t.Fatalf("expected context prefetcher to be set")
+ }
+
+ toolsList := service.ListAvailableTools(context.Background(), "check status")
+ if len(toolsList) == 0 {
+ t.Fatalf("expected available tools to be listed")
+ }
+
+ if service.GetExecutor() == nil {
+ t.Fatalf("expected executor to be returned")
+ }
+}
+
+func TestService_isAutonomousModeEnabled(t *testing.T) {
+ service := &Service{cfg: &config.AIConfig{ControlLevel: config.ControlLevelAutonomous}}
+ if !service.isAutonomousModeEnabled() {
+ t.Fatalf("expected autonomous mode from config")
+ }
+
+ service = &Service{}
+ if service.isAutonomousModeEnabled() {
+ t.Fatalf("expected autonomous mode to be false")
+ }
+}
+
+func TestService_ExecuteMCPTool(t *testing.T) {
+ service := &Service{}
+ if _, err := service.ExecuteMCPTool(context.Background(), "pulse_knowledge", nil); err == nil {
+ t.Fatalf("expected error when executor missing")
+ }
+
+ executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{KnowledgeStoreProvider: mockKnowledgeStore{}})
+ service.executor = executor
+
+ result, err := service.ExecuteMCPTool(context.Background(), "pulse_knowledge", map[string]interface{}{
+ "action": "recall",
+ "resource_id": "vm1",
+ })
+ if err != nil {
+ t.Fatalf("expected tool execution to succeed: %v", err)
+ }
+ if result == "" {
+ t.Fatalf("expected result text")
+ }
+
+ if _, err := service.ExecuteMCPTool(context.Background(), "pulse_knowledge", map[string]interface{}{
+ "action": "recall",
+ }); err == nil {
+ t.Fatalf("expected error for missing resource_id")
+ }
+}
+
+func TestIsSpecialtyTool(t *testing.T) {
+ if !isSpecialtyTool("pulse_storage") {
+ t.Fatalf("expected pulse_storage to be specialty tool")
+ }
+ if isSpecialtyTool("pulse_query") {
+ t.Fatalf("expected pulse_query to be non-specialty tool")
+ }
+}
diff --git a/internal/ai/chat/session_additional_test.go b/internal/ai/chat/session_additional_test.go
new file mode 100644
index 0000000000..8be2cc521c
--- /dev/null
+++ b/internal/ai/chat/session_additional_test.go
@@ -0,0 +1,142 @@
+package chat
+
+import (
+ "testing"
+)
+
+func TestSessionStore_KnowledgeAndToolSets(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ session, err := store.Create()
+ if err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+
+ ka1 := store.GetKnowledgeAccumulator(session.ID)
+ ka2 := store.NewKnowledgeAccumulatorForRun(session.ID)
+ if ka1 == ka2 {
+ t.Fatalf("expected new knowledge accumulator for run")
+ }
+
+ toolSet := map[string]bool{"pulse_query": true}
+ store.SetToolSet(session.ID, toolSet)
+ got := store.GetToolSet(session.ID)
+ if got == nil || !got["pulse_query"] {
+ t.Fatalf("expected tool set entry")
+ }
+ got["pulse_query"] = false
+ if store.GetToolSet(session.ID)["pulse_query"] != true {
+ t.Fatalf("expected tool set to be copied")
+ }
+
+ updated := store.AddToolSet(session.ID, map[string]bool{"pulse_metrics": true})
+ if !updated["pulse_metrics"] {
+ t.Fatalf("expected tool set to include additions")
+ }
+}
+
+func TestSessionStore_ResolvedContextLifecycle(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ session, err := store.Create()
+ if err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+
+ res := &ResolvedResource{
+ ResourceID: "vm:node1:101",
+ ResourceType: "vm",
+ Name: "alpha",
+ TargetHost: "alpha",
+ AllowedActions: []string{"start"},
+ }
+ store.AddResolvedResource(session.ID, res.Name, res)
+
+ if _, err := store.ValidateResourceForAction(session.ID, res.ResourceID, "start"); err != nil {
+ t.Fatalf("expected action to be allowed: %v", err)
+ }
+ if _, err := store.ValidateResourceForAction(session.ID, res.ResourceID, "stop"); err == nil {
+ t.Fatalf("expected action to be blocked")
+ }
+
+ store.ClearResolvedContext(session.ID)
+ if _, err := store.ValidateResourceForAction(session.ID, res.ResourceID, "start"); err == nil {
+ t.Fatalf("expected resource to be unresolved after clear")
+ }
+}
+
+func TestSessionStore_ClearSessionState(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ session, err := store.Create()
+ if err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+
+ // Set up context, FSM, and toolset
+ res := &ResolvedResource{ResourceID: "node:node1", Name: "node1", ResourceType: "node"}
+ store.AddResolvedResource(session.ID, res.Name, res)
+ ctx := store.GetResolvedContext(session.ID)
+ ctx.PinResource(res.ResourceID)
+
+ fsm := store.GetSessionFSM(session.ID)
+ fsm.State = StateVerifying
+ store.SetToolSet(session.ID, map[string]bool{"pulse_query": true})
+ store.GetKnowledgeAccumulator(session.ID)
+
+ store.ClearSessionState(session.ID, true)
+ if !store.GetResolvedContext(session.ID).HasAnyResources() {
+ t.Fatalf("expected pinned resources to remain")
+ }
+ if fsm.State != StateReading {
+ t.Fatalf("expected FSM to keep progress when pinned resources remain")
+ }
+ if store.GetToolSet(session.ID) == nil {
+ t.Fatalf("expected toolset to remain when keepPinned=true")
+ }
+
+ store.ClearSessionState(session.ID, false)
+ if store.GetToolSet(session.ID) != nil {
+ t.Fatalf("expected toolset to be cleared when keepPinned=false")
+ }
+}
+
+func TestSessionStore_ResetFSMAndCleanupContext(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+
+ session, err := store.Create()
+ if err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+
+ fsm := store.GetSessionFSM(session.ID)
+ fsm.State = StateVerifying
+ store.ResetSessionFSM(session.ID, true)
+ if fsm.State != StateReading {
+ t.Fatalf("expected ResetSessionFSM keep progress to move to READING")
+ }
+
+ fsm.State = StateVerifying
+ store.ResetSessionFSM(session.ID, false)
+ if fsm.State != StateResolving {
+ t.Fatalf("expected ResetSessionFSM full reset to move to RESOLVING")
+ }
+
+ store.AddResolvedResource(session.ID, "node1", &ResolvedResource{ResourceID: "node:node1", Name: "node1"})
+ store.cleanupResolvedContext(session.ID)
+ if store.GetResolvedContext(session.ID).HasAnyResources() {
+ t.Fatalf("expected cleanupResolvedContext to remove resources")
+ }
+}
diff --git a/internal/ai/chat/types_additional_test.go b/internal/ai/chat/types_additional_test.go
new file mode 100644
index 0000000000..5853ce3021
--- /dev/null
+++ b/internal/ai/chat/types_additional_test.go
@@ -0,0 +1,122 @@
+package chat
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestResolvedResource_GettersAndAliases(t *testing.T) {
+ res := &ResolvedResource{
+ ResourceID: "vm:node1:101",
+ ResourceType: "vm",
+ TargetHost: "alpha",
+ AgentID: "agent-1",
+ Adapter: "qm",
+ VMID: 101,
+ Node: "node1",
+ AllowedActions: []string{"start"},
+ ProviderUID: "101",
+ Kind: "vm",
+ Aliases: []string{"alpha", "Alpha-VM"},
+ Name: "alpha",
+ }
+
+ if res.GetResourceID() != "vm:node1:101" || res.GetResourceType() != "vm" {
+ t.Fatalf("expected getters to return structured fields")
+ }
+ if res.GetTargetHost() != "alpha" || res.GetAgentID() != "agent-1" || res.GetAdapter() != "qm" {
+ t.Fatalf("expected routing getters to return values")
+ }
+ if res.GetVMID() != 101 || res.GetNode() != "node1" {
+ t.Fatalf("expected VMID/node getters to return values")
+ }
+ if len(res.GetAllowedActions()) != 1 || res.GetAllowedActions()[0] != "start" {
+ t.Fatalf("expected allowed actions getter to return actions")
+ }
+ if len(res.GetAliases()) != 2 {
+ t.Fatalf("expected aliases getter to return values")
+ }
+ if !res.HasAlias("alpha-vm") {
+ t.Fatalf("expected HasAlias to be case-insensitive")
+ }
+}
+
+func TestResolvedResource_GetBestExecutor(t *testing.T) {
+ res := &ResolvedResource{
+ ReachableVia: []ExecutorPath{
+ {ExecutorID: "a", Actions: []string{"restart"}, Priority: 1},
+ {ExecutorID: "b", Actions: []string{"*"}, Priority: 0},
+ },
+ }
+
+ best := res.GetBestExecutor("restart")
+ if best == nil || best.ExecutorID != "a" {
+ t.Fatalf("expected highest priority executor for action")
+ }
+
+ best = res.GetBestExecutor("stop")
+ if best == nil || best.ExecutorID != "b" {
+ t.Fatalf("expected wildcard executor for action")
+ }
+}
+
+func TestResolvedContext_AccessAndValidation(t *testing.T) {
+ ctx := NewResolvedContext("session-1")
+ if ctx.HasAnyResources() {
+ t.Fatalf("expected empty context")
+ }
+
+ res := &ResolvedResource{
+ ResourceID: "vm:node1:101",
+ ResourceType: "vm",
+ Name: "alpha",
+ AllowedActions: []string{"start"},
+ }
+ ctx.AddResource("alpha", res)
+ if !ctx.HasAnyResources() {
+ t.Fatalf("expected resources to exist")
+ }
+
+ if _, ok := ctx.GetResourceByID(res.ResourceID); !ok {
+ t.Fatalf("expected GetResourceByID to find resource")
+ }
+
+ if _, err := ctx.ValidateResourceID("missing"); err == nil {
+ t.Fatalf("expected resource not resolved error")
+ }
+
+ if err := ctx.ValidateAction(res.ResourceID, "start"); err != nil {
+ t.Fatalf("expected action allowed")
+ }
+ if err := ctx.ValidateAction(res.ResourceID, "stop"); err == nil {
+ t.Fatalf("expected action not allowed")
+ }
+
+ if _, err := ctx.ValidateResourceForAction(res.ResourceID, "start"); err != nil {
+ t.Fatalf("expected ValidateResourceForAction to succeed: %v", err)
+ }
+}
+
+func TestResolvedContext_ExplicitAccess(t *testing.T) {
+ ctx := NewResolvedContext("session-1")
+ res := &ResolvedResource{ResourceID: "node:node1", Name: "node1"}
+ ctx.AddResourceWithExplicitAccess(res.Name, res)
+
+ recent := ctx.GetRecentlyAccessedResourcesSorted(5*time.Minute, 10)
+ if len(recent) != 1 || recent[0] != res.ResourceID {
+ t.Fatalf("expected recently accessed resource to be tracked")
+ }
+}
+
+func TestResolvedContextErrors(t *testing.T) {
+ resErr := (&ResourceNotResolvedError{ResourceID: "missing"}).Error()
+ if !strings.Contains(resErr, "missing") {
+ t.Fatalf("expected resource error to include ID")
+ }
+
+ actionErr := (&ActionNotAllowedError{ResourceID: "vm:1", Action: "stop"}).Error()
+ if !strings.Contains(actionErr, "stop") {
+ t.Fatalf("expected action error to include action")
+ }
+}
diff --git a/internal/ai/patrol_ai_additional_test.go b/internal/ai/patrol_ai_additional_test.go
new file mode 100644
index 0000000000..6d6e5ee43f
--- /dev/null
+++ b/internal/ai/patrol_ai_additional_test.go
@@ -0,0 +1,146 @@
+package ai
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/correlation"
+)
+
+func TestSeedFormattingHelpers(t *testing.T) {
+ t.Run("formatBytes", func(t *testing.T) {
+ cases := []struct {
+ value int64
+ want string
+ }{
+ {value: 512, want: "512 B"},
+ {value: 2 * 1024, want: "2 KB"},
+ {value: 5 * 1024 * 1024, want: "5 MB"},
+ {value: 3 * 1024 * 1024 * 1024, want: "3.0 GB"},
+ {value: 2 * 1024 * 1024 * 1024 * 1024, want: "2.0 TB"},
+ }
+ for _, c := range cases {
+ if got := seedFormatBytes(c.value); got != c.want {
+ t.Fatalf("seedFormatBytes(%d) = %q, want %q", c.value, got, c.want)
+ }
+ }
+ })
+
+ t.Run("formatDuration", func(t *testing.T) {
+ cases := []struct {
+ value time.Duration
+ want string
+ }{
+ {value: 30 * time.Second, want: "30s"},
+ {value: 5 * time.Minute, want: "5m"},
+ {value: 3 * time.Hour, want: "3h"},
+ {value: 48 * time.Hour, want: "2d"},
+ }
+ for _, c := range cases {
+ if got := seedFormatDuration(c.value); got != c.want {
+ t.Fatalf("seedFormatDuration(%s) = %q, want %q", c.value, got, c.want)
+ }
+ }
+ })
+
+ t.Run("formatTimeAgo", func(t *testing.T) {
+ now := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC)
+ cases := []struct {
+ value time.Time
+ want string
+ }{
+ {value: now.Add(-30 * time.Second), want: "just now"},
+ {value: now.Add(-10 * time.Minute), want: "10m ago"},
+ {value: now.Add(-2 * time.Hour), want: "2h ago"},
+ {value: now.Add(-24 * time.Hour), want: "1d ago"},
+ {value: now.Add(-72 * time.Hour), want: "3d ago"},
+ }
+ for _, c := range cases {
+ if got := seedFormatTimeAgo(now, c.value); got != c.want {
+ t.Fatalf("seedFormatTimeAgo(%s) = %q, want %q", c.value, got, c.want)
+ }
+ }
+ })
+}
+
+func TestSeedIsInScope(t *testing.T) {
+ if !seedIsInScope(nil, "anything") {
+ t.Fatal("seedIsInScope should return true for nil scope")
+ }
+
+ scoped := map[string]bool{"res-1": true}
+ if seedIsInScope(scoped, "res-2") {
+ t.Fatal("seedIsInScope should return false for missing resource")
+ }
+ if !seedIsInScope(scoped, "res-1") {
+ t.Fatal("seedIsInScope should return true for scoped resource")
+ }
+}
+
+func TestPatrolService_BuildScopedSet_WithCorrelation(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+
+ cfg := correlation.DefaultConfig()
+ cfg.MinOccurrences = 1
+ cfg.CorrelationWindow = 10 * time.Minute
+
+ detector := correlation.NewDetector(cfg)
+ now := time.Now()
+ detector.RecordEvent(correlation.Event{
+ ResourceID: "vm:node1:101",
+ EventType: correlation.EventType("alert"),
+ Timestamp: now.Add(-2 * time.Minute),
+ })
+ detector.RecordEvent(correlation.Event{
+ ResourceID: "vm:node1:102",
+ EventType: correlation.EventType("alert"),
+ Timestamp: now.Add(-1 * time.Minute),
+ })
+
+ ps.correlationDetector = detector
+
+ scope := &PatrolScope{ResourceIDs: []string{"vm:node1:101"}}
+ scopedSet := ps.buildScopedSet(scope)
+ if scopedSet == nil {
+ t.Fatal("expected non-nil scoped set")
+ }
+ if !scopedSet["vm:node1:101"] || !scopedSet["vm:node1:102"] {
+ t.Fatalf("expected correlated resources to be included, got: %+v", scopedSet)
+ }
+}
+
+func TestPatrolService_SeedPreviousRun(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ ps.runHistoryStore = NewPatrolRunHistoryStore(10)
+
+ now := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC)
+ ps.runHistoryStore.Add(PatrolRunRecord{
+ ID: "run-1",
+ StartedAt: now.Add(-2 * time.Hour),
+ Duration: 30 * time.Minute,
+ Status: "issues_found",
+ NewFindings: 1,
+ ExistingFindings: 2,
+ ResolvedFindings: 1,
+ RejectedFindings: 0,
+ FindingsSummary: "CPU warning on node1",
+ })
+
+ summary := ps.seedPreviousRun(now)
+ if summary == "" {
+ t.Fatal("expected previous run summary to be non-empty")
+ }
+ expectedParts := []string{
+ "# Previous Patrol Run",
+ "Status: issues_found",
+ "duration: 30m",
+ "Summary: CPU warning on node1",
+ "Trigger: scheduled",
+ }
+ for _, part := range expectedParts {
+ if !strings.Contains(summary, part) {
+ t.Fatalf("expected summary to contain %q, got:\n%s", part, summary)
+ }
+ }
+}
diff --git a/internal/ai/patrol_ai_eval_additional_test.go b/internal/ai/patrol_ai_eval_additional_test.go
new file mode 100644
index 0000000000..bd021e2cb1
--- /dev/null
+++ b/internal/ai/patrol_ai_eval_additional_test.go
@@ -0,0 +1,148 @@
+package ai
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+func TestIsInvestigationTool(t *testing.T) {
+ if !isInvestigationTool("pulse_query") || !isInvestigationTool("pulse_metrics") || !isInvestigationTool("pulse_storage") || !isInvestigationTool("pulse_read") {
+ t.Fatal("expected investigation tools to be recognized")
+ }
+ if isInvestigationTool("pulse_control") {
+ t.Fatal("expected non-investigation tool to be false")
+ }
+}
+
+func TestFormatToolResult(t *testing.T) {
+ result := tools.CallToolResult{
+ Content: []tools.Content{
+ {Type: "text", Text: "first"},
+ {Type: "resource", URI: "file://ignored"},
+ {Type: "text", Text: "second"},
+ },
+ }
+ if got := formatToolResult(result); got != "first\nsecond" {
+ t.Fatalf("formatToolResult returned %q", got)
+ }
+
+ if got := formatToolResult(tools.CallToolResult{}); got != "" {
+ t.Fatalf("expected empty result for no content, got %q", got)
+ }
+}
+
+func TestEvalPromptBuilders(t *testing.T) {
+ systemPrompt := buildEvalSystemPrompt()
+ if !strings.Contains(systemPrompt, "patrol_report_finding") || !strings.Contains(systemPrompt, "patrol_get_findings") {
+ t.Fatalf("expected eval system prompt to include tool instructions")
+ }
+
+ signals := []DetectedSignal{
+ {
+ SignalType: SignalHighCPU,
+ ResourceID: "node-1",
+ ResourceName: "node-1",
+ ResourceType: "node",
+ SuggestedSeverity: "warning",
+ Category: "performance",
+ Summary: "CPU high",
+ Evidence: "cpu=99%",
+ },
+ }
+ userPrompt := buildEvalUserPrompt(signals)
+ if !strings.Contains(userPrompt, "Signal 1") || !strings.Contains(userPrompt, "CPU high") || !strings.Contains(userPrompt, "cpu=99%") {
+ t.Fatalf("unexpected eval user prompt: %s", userPrompt)
+ }
+}
+
+func TestSignalHelpersAndFindingsFromSignals(t *testing.T) {
+ cases := []struct {
+ signal DetectedSignal
+ wantKey string
+ wantTitle string
+ recSubstring string
+ }{
+ {signal: DetectedSignal{SignalType: SignalSMARTFailure}, wantKey: "smart-failure", wantTitle: "SMART health check failed", recSubstring: "disk"},
+ {signal: DetectedSignal{SignalType: SignalHighCPU}, wantKey: "cpu-high", wantTitle: "High CPU usage detected", recSubstring: "CPU"},
+ {signal: DetectedSignal{SignalType: SignalHighMemory}, wantKey: "memory-high", wantTitle: "High memory usage detected", recSubstring: "memory"},
+ {signal: DetectedSignal{SignalType: SignalHighDisk}, wantKey: "disk-high", wantTitle: "Storage usage is high", recSubstring: "storage"},
+ {signal: DetectedSignal{SignalType: SignalBackupFailed}, wantKey: "backup-failed", wantTitle: "Backup failed", recSubstring: "backup"},
+ {signal: DetectedSignal{SignalType: SignalBackupStale}, wantKey: "backup-stale", wantTitle: "Backup is stale", recSubstring: "backup"},
+ {signal: DetectedSignal{SignalType: SignalActiveAlert}, wantKey: "active-alert", wantTitle: "Active alert detected", recSubstring: "alert"},
+ {signal: DetectedSignal{SignalType: SignalType("unknown")}, wantKey: "deterministic-signal", wantTitle: "Infrastructure signal detected", recSubstring: "Investigate"},
+ }
+
+ for _, c := range cases {
+ if got := signalKey(c.signal); got != c.wantKey {
+ t.Fatalf("signalKey(%s) = %s, want %s", c.signal.SignalType, got, c.wantKey)
+ }
+ if got := signalTitle(c.signal); got != c.wantTitle {
+ t.Fatalf("signalTitle(%s) = %s, want %s", c.signal.SignalType, got, c.wantTitle)
+ }
+ if !strings.Contains(defaultRecommendationForSignal(c.signal), c.recSubstring) {
+ t.Fatalf("unexpected recommendation for %s: %s", c.signal.SignalType, defaultRecommendationForSignal(c.signal))
+ }
+ }
+
+ ps := NewPatrolService(nil, nil)
+ adapter := newPatrolFindingCreatorAdapter(ps, models.StateSnapshot{})
+
+ signals := []DetectedSignal{
+ {
+ SignalType: SignalHighCPU,
+ ResourceID: "node-1",
+ ResourceName: "",
+ ResourceType: "",
+ SuggestedSeverity: "",
+ Category: "",
+ Summary: "CPU high",
+ Evidence: "cpu=99%",
+ },
+ {
+ SignalType: SignalBackupFailed,
+ ResourceID: "vm-101",
+ ResourceName: "vm-101",
+ ResourceType: "vm",
+ SuggestedSeverity: "warning",
+ Category: "backup",
+ Summary: "Backup failed",
+ Evidence: "job failed",
+ },
+ }
+
+ created := ps.createFindingsFromSignals(adapter, signals)
+ if created != len(signals) {
+ t.Fatalf("expected %d findings created, got %d", len(signals), created)
+ }
+}
+
+func TestRunEvaluationPass(t *testing.T) {
+ ps := NewPatrolService(&Service{}, nil)
+ _, err := ps.runEvaluationPass(context.Background(), nil, []DetectedSignal{{SignalType: SignalHighCPU}})
+ if err == nil {
+ t.Fatal("expected error when chat service is unavailable")
+ }
+
+ persistence := config.NewConfigPersistence(t.TempDir())
+ svc := NewService(persistence, nil)
+ mockCS := &patrolMockChatService{
+ executePatrolStreamFunc: func(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {
+ return &PatrolStreamResponse{Content: "ok", InputTokens: 10, OutputTokens: 20}, nil
+ },
+ }
+ svc.SetChatService(mockCS)
+
+ ps.aiService = svc
+ resp, err := ps.runEvaluationPass(context.Background(), nil, []DetectedSignal{{SignalType: SignalHighCPU}})
+ if err != nil {
+ t.Fatalf("expected evaluation pass to succeed, got %v", err)
+ }
+ if resp == nil || resp.InputTokens != 10 || resp.OutputTokens != 20 {
+ t.Fatalf("unexpected evaluation response: %+v", resp)
+ }
+}
diff --git a/internal/ai/patrol_ai_more_test.go b/internal/ai/patrol_ai_more_test.go
new file mode 100644
index 0000000000..a030937f89
--- /dev/null
+++ b/internal/ai/patrol_ai_more_test.go
@@ -0,0 +1,198 @@
+package ai
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+type noExecutorChatService struct{}
+
+func (n *noExecutorChatService) CreateSession(ctx context.Context) (*ChatSession, error) {
+ return &ChatSession{ID: "noop"}, nil
+}
+
+func (n *noExecutorChatService) ExecuteStream(ctx context.Context, req ChatExecuteRequest, callback ChatStreamCallback) error {
+ return nil
+}
+
+func (n *noExecutorChatService) ExecutePatrolStream(ctx context.Context, req PatrolExecuteRequest, callback ChatStreamCallback) (*PatrolStreamResponse, error) {
+ return &PatrolStreamResponse{}, nil
+}
+
+func (n *noExecutorChatService) GetMessages(ctx context.Context, sessionID string) ([]ChatMessage, error) {
+ return nil, nil
+}
+
+func (n *noExecutorChatService) DeleteSession(ctx context.Context, sessionID string) error {
+ return nil
+}
+
+func (n *noExecutorChatService) ReloadConfig(ctx context.Context, cfg *config.AIConfig) error {
+ return nil
+}
+
+func samplePatrolState() models.StateSnapshot {
+ return models.StateSnapshot{
+ Nodes: []models.Node{
+ {
+ ID: "node-1",
+ Name: "node-1",
+ Status: "online",
+ CPU: 0.15,
+ Memory: models.Memory{Usage: 20.0},
+ Disk: models.Disk{Usage: 10.0},
+ },
+ },
+ }
+}
+
+func TestComputePatrolMaxTurns(t *testing.T) {
+ if got := computePatrolMaxTurns(0, nil); got != patrolMinTurns {
+ t.Fatalf("expected min turns %d, got %d", patrolMinTurns, got)
+ }
+
+ if got := computePatrolMaxTurns(1000, nil); got != patrolMaxTurnsLimit {
+ t.Fatalf("expected max turns %d, got %d", patrolMaxTurnsLimit, got)
+ }
+
+ quickScope := &PatrolScope{Depth: PatrolDepthQuick}
+ if got := computePatrolMaxTurns(0, quickScope); got != patrolQuickMinTurns {
+ t.Fatalf("expected quick min turns %d, got %d", patrolQuickMinTurns, got)
+ }
+ if got := computePatrolMaxTurns(200, quickScope); got != patrolQuickMaxTurns {
+ t.Fatalf("expected quick max turns %d, got %d", patrolQuickMaxTurns, got)
+ }
+}
+
+func TestEnsureInvestigationToolCall_NoOp(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ ctx := context.Background()
+
+ var mu sync.Mutex
+ completed := []ToolCallRecord{{ToolName: "pulse_query"}}
+ raw := []string{"existing"}
+
+ ps.ensureInvestigationToolCall(ctx, &tools.PulseToolExecutor{}, &mu, &completed, &raw, true)
+ if len(completed) != 1 || len(raw) != 1 {
+ t.Fatalf("expected no changes when investigation tool already present")
+ }
+
+ ps.ensureInvestigationToolCall(ctx, nil, &mu, &completed, &raw, true)
+ if len(completed) != 1 || len(raw) != 1 {
+ t.Fatalf("expected no changes when executor is nil")
+ }
+}
+
+func TestGetPatrolSystemPrompt_ModeSwitch(t *testing.T) {
+ svc := &Service{cfg: &config.AIConfig{PatrolAutoFix: true}}
+ ps := NewPatrolService(svc, nil)
+ prompt := ps.getPatrolSystemPrompt()
+ if !strings.Contains(prompt, "Auto-Fix Mode") || !strings.Contains(prompt, "pulse_control") {
+ t.Fatalf("expected auto-fix prompt, got: %s", prompt)
+ }
+
+ svc.cfg = &config.AIConfig{PatrolAutoFix: false}
+ prompt = ps.getPatrolSystemPrompt()
+ if !strings.Contains(prompt, "Observe Only Mode") {
+ t.Fatalf("expected observe-only prompt, got: %s", prompt)
+ }
+}
+
+func TestRunAIAnalysis_EarlyErrors(t *testing.T) {
+ t.Run("nil service", func(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ _, err := ps.runAIAnalysis(context.Background(), models.StateSnapshot{}, nil)
+ if err == nil {
+ t.Fatal("expected error when aiService is nil")
+ }
+ })
+
+ t.Run("budget exceeded", func(t *testing.T) {
+ store := cost.NewStore(cost.DefaultMaxDays)
+ store.Record(cost.UsageEvent{
+ Provider: "openai",
+ RequestModel: "gpt-4o-mini",
+ InputTokens: 1_000_000,
+ OutputTokens: 0,
+ })
+ svc := &Service{
+ cfg: &config.AIConfig{CostBudgetUSD30d: 0.01},
+ costStore: store,
+ }
+ ps := NewPatrolService(svc, nil)
+ _, err := ps.runAIAnalysis(context.Background(), models.StateSnapshot{}, nil)
+ if err == nil || !strings.Contains(err.Error(), "patrol skipped") {
+ t.Fatalf("expected budget error, got %v", err)
+ }
+ })
+
+ t.Run("chat service nil", func(t *testing.T) {
+ svc := &Service{}
+ ps := NewPatrolService(svc, nil)
+ scope := &PatrolScope{NoStream: true}
+ _, err := ps.runAIAnalysis(context.Background(), samplePatrolState(), scope)
+ if err == nil || !strings.Contains(err.Error(), "chat service not available") {
+ t.Fatalf("expected chat service error, got %v", err)
+ }
+ })
+
+ t.Run("executor accessor missing", func(t *testing.T) {
+ svc := &Service{}
+ svc.SetChatService(&noExecutorChatService{})
+ ps := NewPatrolService(svc, nil)
+ scope := &PatrolScope{NoStream: true}
+ _, err := ps.runAIAnalysis(context.Background(), samplePatrolState(), scope)
+ if err == nil || !strings.Contains(err.Error(), "executor access") {
+ t.Fatalf("expected executor access error, got %v", err)
+ }
+ })
+
+ t.Run("executor nil", func(t *testing.T) {
+ svc := &Service{}
+ svc.SetChatService(&mockChatService{executor: nil})
+ ps := NewPatrolService(svc, nil)
+ scope := &PatrolScope{NoStream: true}
+ _, err := ps.runAIAnalysis(context.Background(), samplePatrolState(), scope)
+ if err == nil || !strings.Contains(err.Error(), "tool executor not available") {
+ t.Fatalf("expected executor nil error, got %v", err)
+ }
+ })
+}
+
+func TestSeedResourceInventory_QuietSummary(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ cfg := DefaultPatrolConfig()
+ state := models.StateSnapshot{
+ Nodes: []models.Node{
+ {
+ ID: "node-1",
+ Name: "node-1",
+ Status: "online",
+ CPU: 0.10,
+ Memory: models.Memory{Usage: 10.0},
+ Disk: models.Disk{Usage: 15.0},
+ },
+ {
+ ID: "node-2",
+ Name: "node-2",
+ Status: "online",
+ CPU: 0.20,
+ Memory: models.Memory{Usage: 20.0},
+ Disk: models.Disk{Usage: 25.0},
+ },
+ },
+ }
+
+ out := ps.seedResourceInventory(state, nil, cfg, time.Now(), true)
+ if !strings.Contains(out, "# Nodes: All 2") {
+ t.Fatalf("expected quiet node summary, got: %s", out)
+ }
+}
diff --git a/internal/ai/patrol_findings_additional_test.go b/internal/ai/patrol_findings_additional_test.go
index 54c10f0b63..4a9acd48c5 100644
--- a/internal/ai/patrol_findings_additional_test.go
+++ b/internal/ai/patrol_findings_additional_test.go
@@ -6,6 +6,7 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/remediation"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
@@ -483,3 +484,116 @@ func TestIsActionable_EscapeHatchesPreserved(t *testing.T) {
t.Fatal("reliability finding should always pass")
}
}
+
+func TestPatrolService_GenerateRemediationSteps(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+
+ cases := []struct {
+ name string
+ category FindingCategory
+ title string
+ wantLen int
+ }{
+ {name: "performance-cpu", category: FindingCategoryPerformance, title: "High CPU usage", wantLen: 4},
+ {name: "capacity-disk", category: FindingCategoryCapacity, title: "Disk space low", wantLen: 4},
+ {name: "reliability-offline", category: FindingCategoryReliability, title: "Service offline", wantLen: 4},
+ {name: "backup-failed", category: FindingCategoryBackup, title: "Backup failed", wantLen: 4},
+ {name: "security", category: FindingCategorySecurity, title: "Vulnerability detected", wantLen: 4},
+ {name: "general", category: FindingCategoryGeneral, title: "Config drift detected", wantLen: 4},
+ }
+
+ for _, c := range cases {
+ finding := &Finding{
+ ID: "f-" + c.name,
+ ResourceID: "res-1",
+ Category: c.category,
+ Title: c.title,
+ }
+ steps := ps.generateRemediationSteps(finding)
+ if len(steps) != c.wantLen {
+ t.Fatalf("%s: expected %d steps, got %d", c.name, c.wantLen, len(steps))
+ }
+ }
+
+ unknown := &Finding{
+ ID: "f-unknown",
+ ResourceID: "res-1",
+ Category: FindingCategory("mystery"),
+ Title: "Unknown issue",
+ }
+ steps := ps.generateRemediationSteps(unknown)
+ if len(steps) != 3 {
+ t.Fatalf("unknown category: expected 3 generic steps, got %d", len(steps))
+ }
+}
+
+func TestPatrolService_GenerateRemediationPlan(t *testing.T) {
+ engine := remediation.NewEngine(remediation.DefaultEngineConfig())
+ ps := NewPatrolService(nil, nil)
+ ps.SetRemediationEngine(engine)
+
+ finding := &Finding{
+ ID: "finding-1",
+ Key: "service-restart",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryReliability,
+ ResourceID: "vm-101",
+ ResourceName: "web",
+ ResourceType: "vm",
+ Title: "Unexpected restart detected",
+ Description: "Service restarted unexpectedly",
+ Recommendation: "Investigate restart cause",
+ }
+
+ ps.generateRemediationPlan(finding)
+
+ plan := engine.GetPlanForFinding(finding.ID)
+ if plan == nil {
+ t.Fatal("expected remediation plan to be created")
+ }
+ if plan.RiskLevel == "" {
+ t.Fatal("expected risk level to be set on plan")
+ }
+ if len(plan.Warnings) == 0 {
+ t.Fatal("expected warnings to be added to plan")
+ }
+}
+
+func TestPatrolFindingCreatorAdapter_ResolveFindingAndChecks(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ finding := &Finding{
+ ID: "resolve-1",
+ Key: "cpu-high",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryPerformance,
+ ResourceID: "node-1",
+ ResourceName: "node-1",
+ ResourceType: "node",
+ Title: "High CPU",
+ }
+ ps.findings.Add(finding)
+
+ var resolvedID string
+ ps.unifiedFindingResolver = func(id string) {
+ resolvedID = id
+ }
+
+ adapter := newPatrolFindingCreatorAdapter(ps, models.StateSnapshot{})
+ if err := adapter.ResolveFinding(finding.ID, "resolved in test"); err != nil {
+ t.Fatalf("ResolveFinding failed: %v", err)
+ }
+ if resolvedID != finding.ID {
+ t.Fatalf("expected unified resolver to be called with %s, got %s", finding.ID, resolvedID)
+ }
+ if len(adapter.getResolvedIDs()) != 1 {
+ t.Fatalf("expected resolved IDs to be tracked")
+ }
+
+ if adapter.HasCheckedFindings() {
+ t.Fatal("expected HasCheckedFindings to be false before GetActiveFindings")
+ }
+ _ = adapter.GetActiveFindings("", "warning")
+ if !adapter.HasCheckedFindings() {
+ t.Fatal("expected HasCheckedFindings to be true after GetActiveFindings")
+ }
+}
diff --git a/internal/ai/patrol_history_persistence_test.go b/internal/ai/patrol_history_persistence_test.go
index 8e653e09e5..09915f801b 100644
--- a/internal/ai/patrol_history_persistence_test.go
+++ b/internal/ai/patrol_history_persistence_test.go
@@ -22,6 +22,18 @@ type mockPatrolHistoryPersistence struct {
loadCalls atomic.Int32
}
+type errorPatrolHistoryPersistence struct {
+ err error
+}
+
+func (e *errorPatrolHistoryPersistence) SavePatrolRunHistory(runs []PatrolRunRecord) error {
+ return e.err
+}
+
+func (e *errorPatrolHistoryPersistence) LoadPatrolRunHistory() ([]PatrolRunRecord, error) {
+ return nil, nil
+}
+
func (m *mockPatrolHistoryPersistence) SavePatrolRunHistory(runs []PatrolRunRecord) error {
m.saveCalls.Add(1)
m.mu.Lock()
@@ -204,6 +216,76 @@ func TestPatrolRunHistoryStore_SetPersistence(t *testing.T) {
}
}
+func TestPatrolRunHistoryStore_PersistenceStatusAndErrors(t *testing.T) {
+ store := NewPatrolRunHistoryStore(5)
+ store.saveDebounce = 0
+
+ saveErr := errors.New("save failed")
+ errPersistence := &errorPatrolHistoryPersistence{err: saveErr}
+
+ if err := store.SetPersistence(errPersistence); err != nil {
+ t.Fatalf("SetPersistence failed: %v", err)
+ }
+
+ errCh := make(chan error, 1)
+ store.SetOnSaveError(func(err error) {
+ errCh <- err
+ })
+
+ store.Add(PatrolRunRecord{ID: "run-1"})
+
+ select {
+ case err := <-errCh:
+ if err == nil || err.Error() != "save failed" {
+ t.Fatalf("unexpected error callback: %v", err)
+ }
+ case <-time.After(1 * time.Second):
+ t.Fatal("timed out waiting for save error callback")
+ }
+
+ lastErr, lastSaveTime, hasPersistence := store.GetPersistenceStatus()
+ if lastErr == nil {
+ t.Fatal("expected last save error to be recorded")
+ }
+ if !lastSaveTime.IsZero() {
+ t.Fatalf("expected last save time to be zero on failure, got %v", lastSaveTime)
+ }
+ if !hasPersistence {
+ t.Fatal("expected persistence to be configured")
+ }
+}
+
+func TestConvertPatrolToolCalls(t *testing.T) {
+ aiCalls := []ToolCallRecord{
+ {
+ ID: "call-1",
+ ToolName: "pulse_query",
+ Input: `{"action":"get"}`,
+ Output: `{"status":"ok"}`,
+ Success: true,
+ StartTime: 123,
+ EndTime: 456,
+ Duration: 333,
+ },
+ }
+
+ cfgCalls := convertAIToolCallsToConfig(aiCalls)
+ if len(cfgCalls) != 1 {
+ t.Fatalf("expected 1 config tool call, got %d", len(cfgCalls))
+ }
+ if cfgCalls[0].ToolName != "pulse_query" || cfgCalls[0].Duration != 333 {
+ t.Fatalf("unexpected config tool call: %+v", cfgCalls[0])
+ }
+
+ roundTrip := convertConfigToolCallsToAI(cfgCalls)
+ if len(roundTrip) != 1 {
+ t.Fatalf("expected 1 AI tool call, got %d", len(roundTrip))
+ }
+ if roundTrip[0].ID != "call-1" || roundTrip[0].Output != `{"status":"ok"}` {
+ t.Fatalf("unexpected AI tool call: %+v", roundTrip[0])
+ }
+}
+
func TestPatrolRunHistoryStore_SetPersistence_Nil(t *testing.T) {
store := NewPatrolRunHistoryStore(10)
diff --git a/internal/ai/patrol_init_additional_test.go b/internal/ai/patrol_init_additional_test.go
new file mode 100644
index 0000000000..07d2fc5750
--- /dev/null
+++ b/internal/ai/patrol_init_additional_test.go
@@ -0,0 +1,168 @@
+package ai
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/circuit"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/knowledge"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/remediation"
+ "github.com/rcourtman/pulse-go-rewrite/internal/servicediscovery"
+)
+
+type mockLearningProvider struct{}
+
+func (m mockLearningProvider) FormatForContext() string { return "prefs" }
+
+type mockProxmoxEventProvider struct{}
+
+func (m mockProxmoxEventProvider) FormatForPatrol(duration time.Duration) string { return "events" }
+
+type mockForecastProvider struct{}
+
+func (m mockForecastProvider) FormatKeyForecasts() string { return "forecast" }
+
+type stubInvestigationOrchestrator struct{}
+
+func (s *stubInvestigationOrchestrator) InvestigateFinding(ctx context.Context, finding *InvestigationFinding, autonomyLevel string) error {
+ return nil
+}
+
+func (s *stubInvestigationOrchestrator) GetInvestigationByFinding(findingID string) *InvestigationSession {
+ return nil
+}
+
+func (s *stubInvestigationOrchestrator) GetRunningCount() int { return 0 }
+
+func (s *stubInvestigationOrchestrator) GetFixedCount() int { return 0 }
+
+func (s *stubInvestigationOrchestrator) CanStartInvestigation() bool { return true }
+
+func (s *stubInvestigationOrchestrator) ReinvestigateFinding(ctx context.Context, findingID, autonomyLevel string) error {
+ return nil
+}
+
+func (s *stubInvestigationOrchestrator) Shutdown(ctx context.Context) error { return nil }
+
+func TestPatrolService_SettersAndScopeHints(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+
+ ks := &knowledge.Store{}
+ ps.SetKnowledgeStore(ks)
+ if ps.GetKnowledgeStore() != ks {
+ t.Fatalf("expected knowledge store to be set")
+ }
+
+ discoveryStore, err := servicediscovery.NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create discovery store: %v", err)
+ }
+ ps.SetDiscoveryStore(discoveryStore)
+ if ps.GetDiscoveryStore() == nil {
+ t.Fatalf("expected discovery store to be set")
+ }
+
+ lp := mockLearningProvider{}
+ ps.SetLearningProvider(lp)
+ if ps.learningProvider == nil {
+ t.Fatalf("expected learning provider to be set")
+ }
+
+ pep := mockProxmoxEventProvider{}
+ ps.SetProxmoxEventProvider(pep)
+ if ps.proxmoxEventProvider == nil {
+ t.Fatalf("expected proxmox event provider to be set")
+ }
+
+ fp := mockForecastProvider{}
+ ps.SetForecastProvider(fp)
+ if ps.forecastProvider == nil {
+ t.Fatalf("expected forecast provider to be set")
+ }
+
+ tm := NewTriggerManager(TriggerManagerConfig{MaxPendingTriggers: 1})
+ ps.SetTriggerManager(tm)
+ if ps.GetTriggerManager() == nil {
+ t.Fatalf("expected trigger manager to be set")
+ }
+
+ discovery := &servicediscovery.ResourceDiscovery{
+ ID: "vm:node1:101",
+ ResourceType: servicediscovery.ResourceTypeVM,
+ ResourceID: "101",
+ HostID: "node1",
+ Hostname: "node1",
+ ServiceName: "nginx",
+ ServiceType: "nginx",
+ }
+ if err := discoveryStore.Save(discovery); err != nil {
+ t.Fatalf("failed to save discovery: %v", err)
+ }
+
+ scope := PatrolScope{ResourceIDs: []string{"101"}}
+ updated := ps.addDiscoveryScopeHint(scope)
+ if updated.Context == "" || !strings.Contains(updated.Context, "Discovery:") {
+ t.Fatalf("expected discovery hint in scope context")
+ }
+}
+
+func TestTruncateScopeContext(t *testing.T) {
+ if truncateScopeContext("short", 10) != "short" {
+ t.Fatalf("expected short string to remain unchanged")
+ }
+ if truncateScopeContext("long-value", 3) != "lon" {
+ t.Fatalf("expected hard truncation for small max")
+ }
+ if !strings.HasSuffix(truncateScopeContext("long-value", 6), "...") {
+ t.Fatalf("expected ellipsis for truncated context")
+ }
+}
+
+func TestPatrolService_AdditionalSetters(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+
+ breaker := circuit.NewBreaker("test", circuit.Config{})
+ ps.SetCircuitBreaker(breaker)
+ if ps.circuitBreaker != breaker {
+ t.Fatalf("expected circuit breaker to be set")
+ }
+
+ engine := remediation.NewEngine(remediation.DefaultEngineConfig())
+ ps.SetRemediationEngine(engine)
+ if ps.GetRemediationEngine() != engine {
+ t.Fatalf("expected remediation engine to be set")
+ }
+
+ orchestrator := &stubInvestigationOrchestrator{}
+ ps.SetInvestigationOrchestrator(orchestrator)
+ if ps.GetInvestigationOrchestrator() != orchestrator {
+ t.Fatalf("expected investigation orchestrator to be set")
+ }
+
+ callbackCalled := false
+ ps.SetUnifiedFindingCallback(func(f *Finding) bool {
+ callbackCalled = true
+ return true
+ })
+ if ps.unifiedFindingCallback == nil {
+ t.Fatalf("expected unified finding callback to be set")
+ }
+ ps.unifiedFindingCallback(&Finding{})
+ if !callbackCalled {
+ t.Fatalf("expected unified finding callback to be invoked")
+ }
+
+ var resolvedID string
+ ps.SetUnifiedFindingResolver(func(id string) {
+ resolvedID = id
+ })
+ if ps.unifiedFindingResolver == nil {
+ t.Fatalf("expected unified finding resolver to be set")
+ }
+ ps.unifiedFindingResolver("finding-1")
+ if resolvedID != "finding-1" {
+ t.Fatalf("expected unified finding resolver to capture id, got %q", resolvedID)
+ }
+}
diff --git a/internal/ai/patrol_metrics_additional_test.go b/internal/ai/patrol_metrics_additional_test.go
new file mode 100644
index 0000000000..41dfe78f3d
--- /dev/null
+++ b/internal/ai/patrol_metrics_additional_test.go
@@ -0,0 +1,12 @@
+package ai
+
+import "testing"
+
+func TestPatrolMetrics_Recorders(t *testing.T) {
+ m := GetPatrolMetrics()
+ m.RecordCircuitBlock()
+ m.RecordInvestigationOutcome("resolved")
+ m.RecordFixVerification("success")
+ m.RecordScopedDroppedFinal()
+ m.RecordRun("manual", "scoped")
+}
diff --git a/internal/ai/patrol_run_additional_test.go b/internal/ai/patrol_run_additional_test.go
new file mode 100644
index 0000000000..5ca103339f
--- /dev/null
+++ b/internal/ai/patrol_run_additional_test.go
@@ -0,0 +1,154 @@
+package ai
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+type mockPatrolProvider struct {
+ response string
+ err error
+}
+
+func (m mockPatrolProvider) Chat(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {
+ if m.err != nil {
+ return nil, m.err
+ }
+ return &providers.ChatResponse{Content: m.response}, nil
+}
+
+func (m mockPatrolProvider) ChatStream(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {
+ return nil
+}
+
+func (m mockPatrolProvider) SupportsThinking(model string) bool { return false }
+func (m mockPatrolProvider) TestConnection(ctx context.Context) error { return nil }
+func (m mockPatrolProvider) Name() string { return "mock" }
+func (m mockPatrolProvider) ListModels(ctx context.Context) ([]providers.ModelInfo, error) {
+ return nil, nil
+}
+
+type mockPatrolStateProvider struct {
+ state models.StateSnapshot
+}
+
+func (m mockPatrolStateProvider) GetState() models.StateSnapshot { return m.state }
+
+func TestPatrolService_AskAIAboutAlert(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ aiSvc := &Service{
+ provider: mockPatrolProvider{response: "RESOLVE: looks good"},
+ cfg: &config.AIConfig{PatrolModel: "mock:model"},
+ }
+
+ alert := AlertInfo{
+ ID: "a1",
+ Type: "cpu",
+ ResourceName: "node1",
+ ResourceType: "node",
+ Message: "high cpu",
+ Value: 90,
+ Threshold: 80,
+ Duration: "5m",
+ }
+ state := models.StateSnapshot{Nodes: []models.Node{{ID: "node1", Name: "node1", CPU: 10}}}
+
+ resolved, reason := ps.askAIAboutAlert(context.Background(), alert, state, aiSvc)
+ if !resolved {
+ t.Fatalf("expected alert to resolve")
+ }
+ if reason == "" {
+ t.Fatalf("expected resolution reason")
+ }
+}
+
+func TestPatrolService_GetResourceCurrentState(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ state := models.StateSnapshot{
+ Storage: []models.Storage{{ID: "s1", Name: "store1", Usage: 75.5, Status: "ok"}},
+ }
+ alert := AlertInfo{ResourceType: "Storage", ResourceID: "s1", ResourceName: "store1"}
+ if got := ps.getResourceCurrentState(alert, state); got == "" {
+ t.Fatalf("expected storage state")
+ }
+
+ alert = AlertInfo{ResourceType: "unknown"}
+ if got := ps.getResourceCurrentState(alert, state); got == "" {
+ t.Fatalf("expected fallback for unknown resource")
+ }
+}
+
+func TestPatrolService_TriggerPatrolForAlert(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ ps.adHocTrigger = make(chan *alerts.Alert, 1)
+
+ ps.TriggerPatrolForAlert(nil) // should no-op
+
+ alert := &alerts.Alert{ID: "a1", Type: "cpu", ResourceID: "node1"}
+ ps.TriggerPatrolForAlert(alert)
+ select {
+ case got := <-ps.adHocTrigger:
+ if got.ID != alert.ID {
+ t.Fatalf("expected alert to be queued")
+ }
+ default:
+ t.Fatalf("expected alert to be queued")
+ }
+
+ // Trigger manager path
+ tm := NewTriggerManager(TriggerManagerConfig{MaxPendingTriggers: 1})
+ ps.SetTriggerManager(tm)
+ ps.TriggerPatrolForAlert(alert)
+ if tm.GetPendingCount() != 1 {
+ t.Fatalf("expected trigger manager to queue alert")
+ }
+}
+
+func TestPatrolService_RunTargetedPatrol_Disabled(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ ps.config.Enabled = false
+
+ alert := &alerts.Alert{ID: "a2", Type: "cpu", ResourceID: "node1"}
+ ps.runTargetedPatrol(context.Background(), alert)
+}
+
+func TestPatrolService_RunScopedPatrol_EarlyPaths(t *testing.T) {
+ ps := NewPatrolService(nil, mockPatrolStateProvider{state: models.StateSnapshot{}})
+ ps.config.Enabled = false
+ ps.runScopedPatrol(context.Background(), PatrolScope{ResourceIDs: []string{"node1"}})
+
+ // Re-queue when run already in progress
+ ps.config.Enabled = true
+ ps.runInProgress = true
+ ps.runStartedAt = time.Now()
+ ps.SetTriggerManager(NewTriggerManager(TriggerManagerConfig{MaxPendingTriggers: 2}))
+ ps.runScopedPatrol(context.Background(), PatrolScope{ResourceIDs: []string{"node1"}})
+ if ps.triggerManager.GetPendingCount() != 1 {
+ t.Fatalf("expected scoped patrol to be re-queued")
+ }
+
+ // Drop permanently when retries exhausted
+ ps.runInProgress = true
+ ps.runStartedAt = time.Now()
+ ps.runScopedPatrol(context.Background(), PatrolScope{ResourceIDs: []string{"node1"}, RetryCount: scopedPatrolMaxRetries})
+
+ // No resources matched
+ ps.runInProgress = false
+ ps.stateProvider = mockPatrolStateProvider{state: models.StateSnapshot{}}
+ ps.runScopedPatrol(context.Background(), PatrolScope{ResourceIDs: []string{"node1"}})
+
+ // AI unavailable path
+ ps.runInProgress = false
+ ps.stateProvider = mockPatrolStateProvider{state: models.StateSnapshot{Nodes: []models.Node{{ID: "node1", Name: "node1"}}}}
+ ps.runScopedPatrol(context.Background(), PatrolScope{ResourceIDs: []string{"node1"}, ResourceTypes: []string{"node"}})
+ status := ps.GetStatus()
+ if status.BlockedReason == "" {
+ t.Fatalf("expected blocked reason when AI unavailable")
+ }
+}
diff --git a/scripts/build-release.sh b/scripts/build-release.sh
index b5296f325c..52fcf5b954 100755
--- a/scripts/build-release.sh
+++ b/scripts/build-release.sh
@@ -397,10 +397,32 @@ cp scripts/pulse-auto-update.sh "$RELEASE_DIR/"
# Generate checksums (include tarballs, zip files, helm chart, and install.sh)
cd "$RELEASE_DIR"
shopt -s nullglob extglob
+checksum_files=()
# Match all tarballs, zip files, exe files, and install scripts
+if compgen -G "pulse-*.tar.gz" > /dev/null; then
+ checksum_files+=( pulse-*.tar.gz )
+fi
if compgen -G "pulse-*.tgz" > /dev/null; then
checksum_files+=( pulse-*.tgz )
fi
+if compgen -G "pulse-*.zip" > /dev/null; then
+ checksum_files+=( pulse-*.zip )
+fi
+if compgen -G "pulse-*.exe" > /dev/null; then
+ checksum_files+=( pulse-*.exe )
+fi
+if [ -f "install.sh" ]; then
+ checksum_files+=( install.sh )
+fi
+if [ -f "install-docker.sh" ]; then
+ checksum_files+=( install-docker.sh )
+fi
+if [ -f "pulse-auto-update.sh" ]; then
+ checksum_files+=( pulse-auto-update.sh )
+fi
+if compgen -G "install*.ps1" > /dev/null; then
+ checksum_files+=( install*.ps1 )
+fi
if [ ${#checksum_files[@]} -eq 0 ]; then
echo "Warning: no release artifacts found to checksum."
else