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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
package tools
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
// PatrolReportFindingRequiredArguments returns the schema-owned argument list
// used by both provider projection and Patrol's model-facing authoring
// guidance. Each caller receives its own slice so prompt construction cannot
// mutate the registered provider contract.
func PatrolReportFindingRequiredArguments() []string {
return []string{
"key",
"severity",
"category",
"resource_id",
"resource_name",
"resource_type",
"title",
"description",
"recommendation",
"evidence",
}
}
// registerPatrolTools registers the patrol-specific finding lifecycle tools.
// These tools are only functional during a patrol run when patrolFindingCreator is set.
func (e *PulseToolExecutor) registerPatrolTools() {
// patrol_report_finding — LLM calls this to create a finding
e.registry.registerBuiltin(RegisteredTool{
Definition: Tool{
Name: agentcapabilities.PatrolReportFindingToolName,
Description: fmt.Sprintf(`Report an infrastructure finding discovered during patrol investigation.
Call this tool to create a structured finding after you have gathered sufficient evidence. A provider-reported failed health check, failed backup, or broken replication state is sufficient evidence for the confirmed symptom even when optional logs or command execution are unavailable. Use warning/reliability for a failed health check unless the evidence establishes a critical consequence. Report the symptom and state that its root cause is unknown; do not fabricate a cause or suppress the finding while searching for one.
Every call must independently include all required arguments: %s. Report one causal incident at a time and wait for its result before reporting another; never split fields across parallel calls or attempt reporting several findings in parallel.
Group symptoms that share one causal chain into one operator-facing finding on the user-facing degraded resource. Include related dependency evidence and honest uncertainty in that finding. Create separate findings only for causally independent incidents.
Do not report a stopped, exited, offline, or otherwise down resource merely to restate its current state; real-time alerts own that condition. Report a distinct downstream degradation or deeper reliability issue only when the evidence establishes one.
Every finding must include concrete evidence and a safe, actionable recommendation grounded in that evidence. The recommendation may be a bounded investigation or verification step when remediation is not yet justified; never claim that an action was taken or verified when it was not.
The finding will be validated against current metrics and deduplicated automatically.
Returns: {"ok": true, "finding_id": "...", "is_new": true/false} on success.`, strings.Join(PatrolReportFindingRequiredArguments(), ", ")),
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
"key": {
Type: "string",
Description: "Stable issue key for deduplication. Use the canonical key when one fits — cpu-high, memory-high, disk-high, backup-stale, backup-failed, smart-failure, guest-unreachable (these have deterministic verifiers that ground resolution) — otherwise a stable kebab-case key like backup-never, storage-high-usage, node-offline, restart-loop, pbs-job-failed.",
},
"severity": {
Type: "string",
Description: "Finding severity level. Only report actionable issues — observations and minor notes belong in your analysis text, not as findings.",
Enum: []string{"critical", "warning"},
},
"category": {
Type: "string",
Description: "Finding category",
Enum: []string{"performance", "capacity", "reliability", "backup", "security", "general"},
},
"resource_id": {
Type: "string",
Description: "Resource ID (e.g. node/pve1, vm/100, ct/101)",
},
"resource_name": {
Type: "string",
Description: "Human-readable resource name",
},
"resource_type": {
Type: "string",
Description: "Canonical v6 resource type",
Enum: []string{"node", "vm", "system-container", "app-container", "storage", "physical_disk", "agent", "k8s-cluster", "pbs"},
},
"title": {
Type: "string",
Description: "Brief finding title (1 sentence)",
},
"description": {
Type: "string",
Description: "Detailed description of the issue found",
},
"impact": {
Type: "string",
Description: "Operator-facing consequence if ignored: what happens to which workloads, jobs, or data if the operator does nothing. " +
"Base this on the data you gathered, not on the severity level. Most infrastructure issues have knowable consequences — " +
"provide this whenever the data supports it. Omit only if the consequence is truly unknowable from available information.",
},
"recommendation": {
Type: "string",
Description: "Specific, actionable next step the operator should take. Include verification steps where possible.",
},
"evidence": {
Type: "string",
Description: "Specific data points, metric values, command outputs, or tool results that led to this finding. " +
"This is the trust anchor: the operator uses it to verify your conclusion independently. " +
"Always include the key evidence — if you gathered enough data to create this finding, you have evidence to report.",
},
},
Required: PatrolReportFindingRequiredArguments(),
},
},
Handler: handlePatrolReportFinding,
Governance: ToolGovernance{
ActionMode: ToolActionWrite,
ApprovalPolicy: ToolApprovalScopeOnly,
ApprovalSummary: "patrol-only; records a governed finding after evidence collection",
Summary: "Creates a structured patrol finding during autonomous investigation.",
},
})
// patrol_assess_finding — LLM records an explicit verdict for a finding
// already present in the current Patrol context. This closes the lifecycle
// gap where models correctly avoided duplicate reports but Patrol then lost
// the fact that the issue was still present.
e.registry.registerBuiltin(RegisteredTool{
Definition: Tool{
Name: agentcapabilities.PatrolAssessFindingToolName,
Description: `Record the current verdict for an existing active Patrol finding after checking current evidence.
Use present when the issue is independently reconfirmed, resolved only when current evidence supports closure, and uncertain when the available evidence cannot justify either conclusion. Every active finding presented in the Patrol context must receive one assessment. Do not use this tool for a new issue; use patrol_report_finding instead.
Returns: {"ok": true, "finding_id": "...", "verdict": "present|resolved|uncertain"} on success.`,
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
agentcapabilities.FindingIDArgumentName: {
Type: "string",
Description: "The active finding ID returned by patrol_get_findings",
},
"verdict": {
Type: "string",
Description: "Current evidence-based verdict for this existing finding",
Enum: []string{"present", "resolved", "uncertain"},
},
"evidence": {
Type: "string",
Description: "Current data points, metrics, logs, or tool output supporting this verdict",
},
agentcapabilities.ReasonArgumentName: {
Type: "string",
Description: "Concise explanation connecting the current evidence to the verdict",
},
},
Required: []string{agentcapabilities.FindingIDArgumentName, "verdict", "evidence", agentcapabilities.ReasonArgumentName},
},
},
Handler: handlePatrolAssessFinding,
Governance: ToolGovernance{
ActionMode: ToolActionWrite,
ApprovalPolicy: ToolApprovalScopeOnly,
ApprovalSummary: "patrol-only; records an evidence-grounded verdict for an existing finding",
Summary: "Reconfirms, resolves, or holds an existing Patrol finding as uncertain.",
},
})
// patrol_resolve_finding — LLM calls this to resolve an active finding
e.registry.registerBuiltin(RegisteredTool{
Definition: Tool{
Name: agentcapabilities.PatrolResolveFindingToolName,
Description: `Resolve an active patrol finding after verifying the issue is no longer present.
Call this after investigating an existing finding and confirming the issue has been resolved.
Returns: {"ok": true, "resolved": true} on success.`,
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
agentcapabilities.FindingIDArgumentName: {
Type: "string",
Description: "The ID of the finding to resolve",
},
agentcapabilities.ReasonArgumentName: {
Type: "string",
Description: "Brief explanation of why this finding is being resolved (e.g. 'CPU has returned to 35%, well below threshold')",
},
},
Required: []string{agentcapabilities.FindingIDArgumentName, agentcapabilities.ReasonArgumentName},
},
},
Handler: handlePatrolResolveFinding,
Governance: ToolGovernance{
ActionMode: ToolActionWrite,
ApprovalPolicy: ToolApprovalScopeOnly,
ApprovalSummary: "patrol-only; resolves a finding after verification",
Summary: "Marks a patrol finding resolved after current evidence supports closure.",
},
})
// patrol_get_findings — LLM calls this to check existing active findings
e.registry.registerBuiltin(RegisteredTool{
Definition: Tool{
Name: agentcapabilities.PatrolGetFindingsToolName,
Description: `Get currently active patrol findings. Call this exactly once near the beginning of a Patrol run, then reuse the result to check what findings already exist before reporting new ones (avoids duplicates) and to identify findings that may need resolution. Do not call it again before the final summary.
Returns a list of active findings with their IDs, severity, resource, and title.`,
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
"resource_id": {
Type: "string",
Description: "Filter by resource ID (optional)",
},
"severity": {
Type: "string",
Description: "Minimum severity to include (optional, default: info)",
Enum: []string{"info", "watch", "warning", "critical"},
},
},
},
},
Handler: handlePatrolGetFindings,
Governance: ToolGovernance{
ActionMode: ToolActionRead,
ApprovalPolicy: ToolApprovalScopeOnly,
ApprovalSummary: "no approval required",
Summary: "Reads active patrol findings for deduplication and investigation context.",
},
})
// patrol_propose_observer — the model authors a bounded artifact, while
// core retains all lifecycle authority. A successful call is intentionally
// still uncovered until a separate validator and installer accept it.
e.registry.registerBuiltin(RegisteredTool{
Definition: Tool{
Name: agentcapabilities.PatrolProposeObserverToolName,
Description: `Propose a durable read-only observer for an active operator objective that is currently missing coverage.
Use this only when the objective context says observer_missing, or when current evidence clearly requires a new observer version. Translate the operator's outcome into the smallest useful local observer without hard-coding an application into Pulse. The probe_json and requirements_json fields must each be one bounded JSON object. Do not include mutation commands, credentials, or secret values.
Classify evidence_fit as direct only when the predicate itself measures the full retained outcome. Use proxy when the signal is useful for waking Patrol but merely correlates with the outcome or indicates it may be impaired. Reachability, process health, and resource-online state are proxies for richer user outcomes such as smooth playback, successful recording, correctness, or latency unless the retained objective is explicitly availability or online state. When uncertain, choose proxy. A healthy proxy is installed and evaluated locally, but core truthfully keeps the objective uncovered until a direct observer exists.
Core can install three generic local ABIs. All require trigger_kind interval, requirements_json {}, a 10-300 second interval, and a 1-10 sample failure window. Use pulse-resource-state/v1 when canonical resource status is truthful: {"runtime":"pulse-resource-state/v1","path":"status","operator":"equals","value":"online","sample_interval_seconds":30,"wake_after_consecutive_failures":2}; operator may be equals or not_equals and value may be online, offline, warning, or unknown. Use pulse-resource-metric/v1 for canonical resource telemetry: {"runtime":"pulse-resource-metric/v1","metric":"disk_percent","operator":"less_than","threshold":85,"sample_interval_seconds":30,"wake_after_consecutive_failures":2,"max_evidence_age_seconds":180}; metric may be cpu_percent, memory_percent, disk_percent, or temperature_celsius, and operator may be less_than, less_than_or_equals, greater_than, or greater_than_or_equals. Percent thresholds are 0-100, temperatures are -100 to 300 Celsius, and evidence age is bounded from the sample interval through 3600 seconds. Use pulse-availability-state/v1 only for an enabled canonical target ID shown in the objective's local availability signals: {"runtime":"pulse-availability-state/v1","target_id":"the-exact-target-id","path":"probe_outcome","operator":"equals","value":"reachable","sample_interval_seconds":30,"wake_after_consecutive_failures":2}; value may be reachable, unreachable, or indeterminate. Never invent a target ID. If the outcome needs an event, log, file, socket, mutation, unsupported protocol, or richer signal, describe that honest proposal instead; core will retain it with an explicit unsupported validation reason rather than pretending it is active.
This tool records only a versioned proposed artifact. It does not validate, install, execute, or claim coverage. Core owns the observer ID, version, SHA-256 digest, read-only posture, sandboxing, installation, health lease, and any later transition.
Returns the proposed observer identity and the truthful uncovered coverage reason.`,
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
"objective_id": {
Type: "string",
Description: "Objective ID exactly as shown in Operator Objectives",
},
"expected_revision": {
Type: "number",
Description: "Current objective revision exactly as shown in Operator Objectives",
},
"interpretation": {
Type: "string",
Description: "Concise measurable interpretation of the operator's desired outcome",
},
"evidence_fit": {
Type: "string",
Description: "direct only when this predicate itself measures the full objective; proxy when it is a useful correlated wake signal",
Enum: []string{"direct", "proxy"},
},
"trigger_kind": {
Type: "string",
Description: "Cheapest appropriate local wake source; interval means a bounded local probe, never repeated model polling",
Enum: []string{"event", "webhook", "log", "file", "socket", "api", "interval"},
},
"probe_json": {
Type: "string",
Description: "One JSON object describing the read-only probe. Use one documented generic ABI exactly when canonical status, metrics, or an existing availability target can measure the outcome; otherwise provide an honest bounded proposal for future capability validation.",
},
"wake_evidence": {
Type: "string",
Description: "Concrete evidence transition that should wake Patrol for model reasoning",
},
"requirements_json": {
Type: "string",
Description: "One JSON object declaring external requirements. Use {} for every currently installable generic ABI. Never include secret values.",
},
},
Required: []string{"objective_id", "expected_revision", "evidence_fit", "interpretation", "trigger_kind", "probe_json", "wake_evidence", "requirements_json"},
},
},
Handler: handlePatrolProposeObserver,
Governance: ToolGovernance{
ActionMode: ToolActionWrite,
ApprovalPolicy: ToolApprovalScopeOnly,
ApprovalSummary: "patrol-only; records a non-executable observer proposal",
Summary: "Records a bounded model-authored observer proposal without installing or executing it.",
},
})
}
func handlePatrolProposeObserver(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
proposer := e.GetPatrolObserverProposer()
if proposer == nil {
return NewTextResult("patrol_propose_observer is only available during a Patrol detection run with an objective store."), nil
}
objectiveID, _ := args["objective_id"].(string)
evidenceFit, _ := args["evidence_fit"].(string)
interpretation, _ := args["interpretation"].(string)
triggerKind, _ := args["trigger_kind"].(string)
probeJSON, _ := args["probe_json"].(string)
wakeEvidence, _ := args["wake_evidence"].(string)
requirementsJSON, _ := args["requirements_json"].(string)
objectiveID = strings.TrimSpace(objectiveID)
evidenceFit = strings.ToLower(strings.TrimSpace(evidenceFit))
interpretation = strings.TrimSpace(interpretation)
triggerKind = strings.ToLower(strings.TrimSpace(triggerKind))
probeJSON = strings.TrimSpace(probeJSON)
wakeEvidence = strings.TrimSpace(wakeEvidence)
requirementsJSON = strings.TrimSpace(requirementsJSON)
expectedRevision, revisionOK := patrolObserverExpectedRevision(args["expected_revision"])
missing := make([]string, 0, 8)
for name, value := range map[string]string{
"objective_id": objectiveID, "evidence_fit": evidenceFit, "interpretation": interpretation,
"trigger_kind": triggerKind, "probe_json": probeJSON,
"wake_evidence": wakeEvidence, "requirements_json": requirementsJSON,
} {
if value == "" {
missing = append(missing, name)
}
}
if !revisionOK {
missing = append(missing, "expected_revision")
}
if len(missing) > 0 {
sort.Strings(missing)
return NewErrorResult(fmt.Errorf("missing or invalid required fields: %s", strings.Join(missing, ", "))), nil
}
validTrigger := map[string]bool{"event": true, "webhook": true, "log": true, "file": true, "socket": true, "api": true, "interval": true}
if !validTrigger[triggerKind] {
return NewErrorResult(fmt.Errorf("invalid trigger_kind %q", triggerKind)), nil
}
if evidenceFit != "direct" && evidenceFit != "proxy" {
return NewErrorResult(fmt.Errorf("invalid evidence_fit %q", evidenceFit)), nil
}
result, err := proposer.ProposeObserver(PatrolObserverProposalInput{
ObjectiveID: objectiveID, ExpectedRevision: expectedRevision,
EvidenceFit: evidenceFit, Interpretation: interpretation, TriggerKind: triggerKind,
ProbeJSON: probeJSON, WakeEvidence: wakeEvidence,
RequirementsJSON: requirementsJSON,
})
if err != nil {
return NewErrorResult(fmt.Errorf("failed to propose observer: %w", err)), nil
}
return NewJSONResult(map[string]interface{}{
"ok": true, "objective_id": result.ObjectiveID, "revision": result.Revision,
"observer_id": result.ObserverID, "observer_version": result.Version,
"state": result.State, "artifact_digest": result.ArtifactDigest,
"coverage_state": result.CoverageState, "coverage_reason": result.CoverageReason,
}), nil
}
func patrolObserverExpectedRevision(value interface{}) (uint64, bool) {
switch typed := value.(type) {
case float64:
if typed <= 0 || typed != math.Trunc(typed) || typed > float64(^uint64(0)) {
return 0, false
}
return uint64(typed), true
case int:
if typed <= 0 {
return 0, false
}
return uint64(typed), true
case uint64:
return typed, typed > 0
case json.Number:
parsed, err := strconv.ParseUint(string(typed), 10, 64)
return parsed, err == nil && parsed > 0
default:
return 0, false
}
}
func handlePatrolAssessFinding(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
creator := e.GetPatrolFindingCreator()
if creator == nil {
return NewTextResult("patrol_assess_finding is only available during a patrol run."), nil
}
if checker, ok := creator.(PatrolFindingsChecker); ok && !checker.HasCheckedFindings() {
return NewErrorResult(fmt.Errorf("call patrol_get_findings before assessing a finding")), nil
}
findingID, _ := args[agentcapabilities.FindingIDArgumentName].(string)
verdict, _ := args["verdict"].(string)
evidence, _ := args["evidence"].(string)
reason, _ := args[agentcapabilities.ReasonArgumentName].(string)
findingID = strings.TrimSpace(findingID)
verdict = strings.ToLower(strings.TrimSpace(verdict))
evidence = strings.TrimSpace(evidence)
reason = strings.TrimSpace(reason)
var missing []string
if findingID == "" {
missing = append(missing, agentcapabilities.FindingIDArgumentName)
}
if verdict == "" {
missing = append(missing, "verdict")
}
if evidence == "" {
missing = append(missing, "evidence")
}
if reason == "" {
missing = append(missing, agentcapabilities.ReasonArgumentName)
}
if len(missing) > 0 {
return NewErrorResult(fmt.Errorf("missing required fields: %s", strings.Join(missing, ", "))), nil
}
if verdict != "present" && verdict != "resolved" && verdict != "uncertain" {
return NewErrorResult(fmt.Errorf("invalid verdict %q: must be present, resolved, or uncertain", verdict)), nil
}
input := PatrolFindingAssessmentInput{
FindingID: findingID,
Verdict: verdict,
Evidence: evidence,
Reason: reason,
}
assessor, ok := creator.(PatrolFindingAssessor)
if !ok {
return NewErrorResult(fmt.Errorf("patrol finding adapter does not support explicit assessments")), nil
}
if err := assessor.AssessFinding(input); err != nil {
var alreadyDecided *PatrolFindingAlreadyDecidedError
if errors.As(err, &alreadyDecided) {
return NewJSONResult(map[string]interface{}{
"ok": true,
agentcapabilities.FindingIDArgumentName: alreadyDecided.FindingID,
"verdict": verdict,
"applied": false,
"reason": "new_finding_reported_this_run",
}), nil
}
return NewErrorResult(fmt.Errorf("failed to assess finding: %w", err)), nil
}
return NewJSONResult(map[string]interface{}{
"ok": true,
agentcapabilities.FindingIDArgumentName: findingID,
"verdict": verdict,
"applied": true,
}), nil
}
func handlePatrolReportFinding(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
creator := e.GetPatrolFindingCreator()
if creator == nil {
return NewTextResult("patrol_report_finding is only available during a patrol run."), nil
}
if checker, ok := creator.(PatrolFindingsChecker); ok && !checker.HasCheckedFindings() {
return NewErrorResult(fmt.Errorf("call patrol_get_findings before reporting a finding")), nil
}
// Extract and normalize required fields. The provider schema is the first
// line of defence; this handler remains authoritative for providers that do
// not enforce JSON-schema required fields themselves.
key, _ := args["key"].(string)
severity, _ := args["severity"].(string)
category, _ := args["category"].(string)
resourceID, _ := args["resource_id"].(string)
resourceName, _ := args["resource_name"].(string)
resourceType, _ := args["resource_type"].(string)
resourceType = canonicalPatrolResourceType(resourceType)
title, _ := args["title"].(string)
description, _ := args["description"].(string)
recommendation, _ := args["recommendation"].(string)
evidence, _ := args["evidence"].(string)
key = strings.TrimSpace(key)
severity = strings.TrimSpace(severity)
category = strings.TrimSpace(category)
resourceID = strings.TrimSpace(resourceID)
resourceName = strings.TrimSpace(resourceName)
title = strings.TrimSpace(title)
description = strings.TrimSpace(description)
recommendation = strings.TrimSpace(recommendation)
evidence = strings.TrimSpace(evidence)
// Validate required fields
var missing []string
if key == "" {
missing = append(missing, "key")
}
if severity == "" {
missing = append(missing, "severity")
}
if category == "" {
missing = append(missing, "category")
}
if resourceID == "" {
missing = append(missing, "resource_id")
}
if resourceName == "" {
missing = append(missing, "resource_name")
}
if resourceType == "" {
missing = append(missing, "resource_type")
}
if title == "" {
missing = append(missing, "title")
}
if description == "" {
missing = append(missing, "description")
}
if recommendation == "" {
missing = append(missing, "recommendation")
}
if evidence == "" {
missing = append(missing, "evidence")
}
if len(missing) > 0 {
return NewErrorResult(fmt.Errorf("missing required fields: %s", strings.Join(missing, ", "))), nil
}
if isUnsupportedLegacyResourceTypeToken(resourceType) {
return NewErrorResult(fmt.Errorf("unsupported resource_type %q", resourceType)), nil
}
validResourceTypes := map[string]bool{
"node": true,
"vm": true,
"system-container": true,
"app-container": true,
"storage": true,
"physical_disk": true,
"agent": true,
"k8s-cluster": true,
"pbs": true,
}
if !validResourceTypes[resourceType] {
return NewErrorResult(fmt.Errorf("unsupported resource_type %q: use node, vm, system-container, app-container, storage, physical_disk, agent, k8s-cluster, or pbs", resourceType)), nil
}
// Validate enums
validSeverities := map[string]bool{"critical": true, "warning": true}
if !validSeverities[severity] {
return NewErrorResult(fmt.Errorf("invalid severity %q: must be critical or warning. For minor observations, include them in your analysis text instead of creating a finding", severity)), nil
}
validCategories := map[string]bool{"performance": true, "capacity": true, "reliability": true, "backup": true, "security": true, "general": true}
if !validCategories[category] {
return NewErrorResult(fmt.Errorf("invalid category %q: must be performance, capacity, reliability, backup, security, or general", category)), nil
}
// Impact remains optional: requiring a consequence when the available
// evidence cannot establish one would reward fabrication.
impact, _ := args["impact"].(string)
impact = strings.TrimSpace(impact)
input := PatrolFindingInput{
Key: key,
Severity: severity,
Category: category,
ResourceID: resourceID,
ResourceName: resourceName,
ResourceType: resourceType,
Title: title,
Description: description,
Impact: impact,
Recommendation: recommendation,
Evidence: evidence,
}
findingID, isNew, err := creator.CreateFinding(input)
if err != nil {
var alreadyReported *PatrolFindingAlreadyReportedError
if errors.As(err, &alreadyReported) {
return NewJSONResult(map[string]interface{}{
"ok": true,
agentcapabilities.FindingIDArgumentName: alreadyReported.FindingID,
"is_new": true,
"applied": false,
"reason": "finding_reported_this_run",
}), nil
}
var ownedByAlerts *PatrolFindingOwnedByAlertsError
if errors.As(err, &ownedByAlerts) {
return NewJSONResult(map[string]interface{}{
"ok": true,
agentcapabilities.FindingIDArgumentName: ownedByAlerts.FindingID,
"is_new": false,
"applied": false,
"reason": "alert_owned_resource_state",
}), nil
}
return NewErrorResult(fmt.Errorf("failed to create finding: %w", err)), nil
}
result := map[string]interface{}{
"ok": true,
agentcapabilities.FindingIDArgumentName: findingID,
"is_new": isNew,
}
return NewJSONResult(result), nil
}
func handlePatrolResolveFinding(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
creator := e.GetPatrolFindingCreator()
if creator == nil {
return NewTextResult("patrol_resolve_finding is only available during a patrol run."), nil
}
if checker, ok := creator.(PatrolFindingsChecker); ok && !checker.HasCheckedFindings() {
return NewErrorResult(fmt.Errorf("call patrol_get_findings before resolving a finding")), nil
}
findingID, _ := args[agentcapabilities.FindingIDArgumentName].(string)
reason, _ := args[agentcapabilities.ReasonArgumentName].(string)
if findingID == "" {
return NewErrorResult(fmt.Errorf("missing required field: %s", agentcapabilities.FindingIDArgumentName)), nil
}
if reason == "" {
return NewErrorResult(fmt.Errorf("missing required field: %s", agentcapabilities.ReasonArgumentName)), nil
}
var resolveErr error
if assessor, ok := creator.(PatrolFindingAssessor); ok {
// Preserve this legacy tool as an alias onto the explicit assessment
// lifecycle so every runtime resolution is persisted with a terminal
// verdict. Narrow extension adapters without assessment support retain
// the original fail-closed resolution call.
resolveErr = assessor.AssessFinding(PatrolFindingAssessmentInput{
FindingID: findingID,
Verdict: "resolved",
Evidence: reason,
Reason: reason,
})
} else {
resolveErr = creator.ResolveFinding(findingID, reason)
}
if resolveErr != nil {
return NewErrorResult(fmt.Errorf("failed to resolve finding: %w", resolveErr)), nil
}
result := map[string]interface{}{
"ok": true,
"resolved": true,
}
return NewJSONResult(result), nil
}
func handlePatrolGetFindings(_ context.Context, e *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {
creator := e.GetPatrolFindingCreator()
if creator == nil {
return NewTextResult("patrol_get_findings is only available during a patrol run."), nil
}
resourceID, _ := args["resource_id"].(string)
minSeverity, _ := args["severity"].(string)
findings := creator.GetActiveFindings(resourceID, minSeverity)
result := map[string]interface{}{
"ok": true,
"count": len(findings),
"findings": findings,
}
return NewJSONResult(result), nil
}
func canonicalPatrolResourceType(resourceType string) string {
return strings.ToLower(strings.TrimSpace(resourceType))
}
func isUnsupportedLegacyResourceTypeToken(value string) bool {
return unifiedresources.IsUnsupportedLegacyResourceTypeAlias(value)
}