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.

Own quickstart state and bill Patrol per run

rcourtman12c30da168ca
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 685a438ba0..90ba548cf3 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -149,9 +149,21 @@ credentials still outrank Patrol quickstart whenever both are present.
That same Patrol quickstart contract is execution-scoped rather than
provider-turn-scoped: the runtime must stamp one stable execution identifier
per higher-level Patrol run and propagate it through every hosted quickstart
-provider call, including retries and the evaluation pass, so one Patrol run
-consumes at most one quickstart credit even when the underlying agentic loop
-makes multiple model turns.
+provider call, including retries, the evaluation pass, alert auto-resolution
+quick-analysis calls, and any other ancillary Patrol-side AI work that still
+belongs to the same run, so one Patrol run consumes at most one quickstart
+credit even when the underlying agentic loop makes multiple model turns or
+post-analysis Patrol helpers need additional model calls.
+That same server-authoritative quickstart contract also governs partial and
+released error paths. `internal/ai/providers/quickstart.go` and
+`internal/ai/quickstart.go` must treat server-reported credits and expiry as
+optional fields on non-success responses, sync cached inventory only when the
+server actually returns authoritative inventory, and preserve the last known
+server state otherwise. The license-server quickstart boundary must release
+failed reservations with the post-release workspace snapshot attached whenever
+that inventory is known, rather than forcing the runtime to infer exhaustion
+from absent fields or resetting credits to zero after transient upstream
+errors.
Public-facing copy that reflects those runtime fields must therefore speak in
Patrol quickstart runs on activated or trial-backed installs and Patrol-only
no-key activation, not in generic AI credits, anonymous Community bootstrap,
diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.go
index 88b7b9a88a..4810eab50d 100644
--- a/internal/ai/patrol_ai.go
+++ b/internal/ai/patrol_ai.go
@@ -215,7 +215,7 @@ func CleanThinkingTokens(content string) string {
// runAIAnalysis uses the agentic tool-driven approach to analyze infrastructure.
// The LLM investigates using MCP tools and reports findings via patrol_report_finding.
// An optional scope focuses the patrol on specific resources.
-func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRuntimeState, scope *PatrolScope) (*AIAnalysisResult, error) {
+func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRuntimeState, scope *PatrolScope, executionID string) (*AIAnalysisResult, error) {
if p.aiService == nil {
return nil, fmt.Errorf("Pulse Patrol service not available")
}
@@ -269,7 +269,9 @@ func (p *PatrolService) runAIAnalysisState(ctx context.Context, snap patrolRunti
log.Debug().Msg("AI Patrol: Starting agentic patrol analysis")
maxTurns := computeTriageMaxTurns(len(triageResult.Flags), scope)
- executionID := uuid.NewString()
+ if strings.TrimSpace(executionID) == "" {
+ executionID = uuid.NewString()
+ }
log.Debug().
Int("triage_flags", len(triageResult.Flags)).
Int("max_turns", maxTurns).
diff --git a/internal/ai/patrol_ai_more_test.go b/internal/ai/patrol_ai_more_test.go
index 773b20471b..2ef26d8ad7 100644
--- a/internal/ai/patrol_ai_more_test.go
+++ b/internal/ai/patrol_ai_more_test.go
@@ -207,7 +207,7 @@ func TestGetPatrolSystemPrompt_ModeSwitch(t *testing.T) {
func TestRunAIAnalysis_EarlyErrors(t *testing.T) {
t.Run("nil service", func(t *testing.T) {
ps := NewPatrolService(nil, nil)
- _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, models.StateSnapshot{}), nil)
+ _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, models.StateSnapshot{}), nil, "")
if err == nil {
t.Fatal("expected error when aiService is nil")
}
@@ -226,7 +226,7 @@ func TestRunAIAnalysis_EarlyErrors(t *testing.T) {
costStore: store,
}
ps := NewPatrolService(svc, nil)
- _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, models.StateSnapshot{}), nil)
+ _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, models.StateSnapshot{}), nil, "")
if err == nil || !strings.Contains(err.Error(), "patrol skipped") {
t.Fatalf("expected budget error, got %v", err)
}
@@ -236,7 +236,7 @@ func TestRunAIAnalysis_EarlyErrors(t *testing.T) {
svc := &Service{}
ps := NewPatrolService(svc, nil)
scope := &PatrolScope{NoStream: true}
- _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, samplePatrolState()), scope)
+ _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, samplePatrolState()), scope, "")
if err == nil || !strings.Contains(err.Error(), "chat service not available") {
t.Fatalf("expected chat service error, got %v", err)
}
@@ -247,7 +247,7 @@ func TestRunAIAnalysis_EarlyErrors(t *testing.T) {
svc.SetChatService(&noExecutorChatService{})
ps := NewPatrolService(svc, nil)
scope := &PatrolScope{NoStream: true}
- _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, samplePatrolState()), scope)
+ _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, samplePatrolState()), scope, "")
if err == nil || !strings.Contains(err.Error(), "executor access") {
t.Fatalf("expected executor access error, got %v", err)
}
@@ -258,7 +258,7 @@ func TestRunAIAnalysis_EarlyErrors(t *testing.T) {
svc.SetChatService(&mockChatService{executor: nil})
ps := NewPatrolService(svc, nil)
scope := &PatrolScope{NoStream: true}
- _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, samplePatrolState()), scope)
+ _, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, samplePatrolState()), scope, "")
if err == nil || !strings.Contains(err.Error(), "tool executor not available") {
t.Fatalf("expected executor nil error, got %v", err)
}
@@ -332,7 +332,7 @@ func TestRunAIAnalysis_RetriesWithProviderDerivedSeedBudget(t *testing.T) {
t.Fatalf("expected initial triage seed to exceed retry budget, got %d tokens", got)
}
- result, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, state), &PatrolScope{NoStream: true})
+ result, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, state), &PatrolScope{NoStream: true}, "")
if err != nil {
t.Fatalf("runAIAnalysisState returned error: %v", err)
}
@@ -400,7 +400,7 @@ func TestRunAIAnalysis_StreamEvents(t *testing.T) {
ps := NewPatrolService(svc, nil)
scope := &PatrolScope{NoStream: true}
- res, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, samplePatrolState()), scope)
+ res, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, samplePatrolState()), scope, "")
if err != nil {
t.Fatalf("runAIAnalysis failed: %v", err)
}
diff --git a/internal/ai/patrol_alerts_review_test.go b/internal/ai/patrol_alerts_review_test.go
index 9b202e0cda..4e6ba8de54 100644
--- a/internal/ai/patrol_alerts_review_test.go
+++ b/internal/ai/patrol_alerts_review_test.go
@@ -25,7 +25,7 @@ func TestShouldResolveAlert_UsageAndMissing(t *testing.T) {
state := models.StateSnapshot{
Storage: []models.Storage{{ID: "storage-1", Usage: 80}},
}
- resolved, reason := ps.shouldResolveAlertState(context.Background(), usageAlert, patrolRuntimeStateForTest(ps, state), nil)
+ resolved, reason := ps.shouldResolveAlertState(context.Background(), usageAlert, patrolRuntimeStateForTest(ps, state), nil, "")
if !resolved || !strings.Contains(reason, "usage dropped") {
t.Fatalf("expected usage alert to resolve, got resolved=%v reason=%q", resolved, reason)
}
@@ -38,7 +38,7 @@ func TestShouldResolveAlert_UsageAndMissing(t *testing.T) {
Threshold: 90,
StartTime: now.Add(-25 * time.Hour),
}
- resolved, reason = ps.shouldResolveAlertState(context.Background(), missingAlert, patrolRuntimeStateForTest(ps, state), nil)
+ resolved, reason = ps.shouldResolveAlertState(context.Background(), missingAlert, patrolRuntimeStateForTest(ps, state), nil, "")
if !resolved || !strings.Contains(reason, "resource no longer present") {
t.Fatalf("expected missing storage alert to resolve, got resolved=%v reason=%q", resolved, reason)
}
@@ -61,7 +61,7 @@ func TestShouldResolveAlert_UsageUsesReadState(t *testing.T) {
Storage: []models.Storage{{ID: "storage-1", Usage: 80}},
})
- resolved, reason := ps.shouldResolveAlertState(context.Background(), alert, patrolRuntimeState{readState: registry}, nil)
+ resolved, reason := ps.shouldResolveAlertState(context.Background(), alert, patrolRuntimeState{readState: registry}, nil, "")
if !resolved || !strings.Contains(reason, "usage dropped") {
t.Fatalf("expected usage alert to resolve from readState, got resolved=%v reason=%q", resolved, reason)
}
@@ -84,7 +84,7 @@ func TestShouldResolveAlert_CPUAndOffline(t *testing.T) {
state := models.StateSnapshot{
Nodes: []models.Node{{ID: "node-1", Name: "node-1", CPU: 0.10, Status: "online"}},
}
- resolved, reason := ps.shouldResolveAlertState(context.Background(), cpuAlert, patrolRuntimeStateForTest(ps, state), nil)
+ resolved, reason := ps.shouldResolveAlertState(context.Background(), cpuAlert, patrolRuntimeStateForTest(ps, state), nil, "")
if !resolved || !strings.Contains(reason, "cpu dropped") {
t.Fatalf("expected cpu alert to resolve, got resolved=%v reason=%q", resolved, reason)
}
@@ -98,7 +98,7 @@ func TestShouldResolveAlert_CPUAndOffline(t *testing.T) {
StartTime: now.Add(-30 * time.Minute),
}
state.VMs = []models.VM{{ID: "vm-1", Name: "vm-1", Status: "running"}}
- resolved, reason = ps.shouldResolveAlertState(context.Background(), offlineAlert, patrolRuntimeStateForTest(ps, state), nil)
+ resolved, reason = ps.shouldResolveAlertState(context.Background(), offlineAlert, patrolRuntimeStateForTest(ps, state), nil, "")
if !resolved || !strings.Contains(reason, "resource is now online") {
t.Fatalf("expected offline alert to resolve, got resolved=%v reason=%q", resolved, reason)
}
@@ -130,7 +130,7 @@ func TestReviewAndResolveAlerts(t *testing.T) {
}
state := models.StateSnapshot{Storage: []models.Storage{{ID: "storage-1", Usage: 70}}}
- resolved := ps.reviewAndResolveAlertsState(context.Background(), patrolRuntimeStateForTest(ps, state), false)
+ resolved := ps.reviewAndResolveAlertsState(context.Background(), patrolRuntimeStateForTest(ps, state), false, "")
if resolved != 1 {
t.Fatalf("expected 1 alert resolved, got %d", resolved)
}
diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.go
index 8d54e9357c..ca137d9089 100644
--- a/internal/ai/patrol_run.go
+++ b/internal/ai/patrol_run.go
@@ -11,6 +11,7 @@ import (
"strings"
"time"
+ "github.com/google/uuid"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/circuit"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
@@ -264,6 +265,7 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
start := time.Now()
runID := fmt.Sprintf("%d", start.UnixNano())
+ executionID := uuid.NewString()
patrolType := "patrol"
GetPatrolMetrics().RecordRun(string(trigger), "full")
@@ -404,7 +406,7 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
// Ensure stream state is clean for this run before the first streamed event.
p.resetStreamForRun(runID)
// Run agentic AI analysis — the LLM uses tools to investigate and reports findings
- aiResult, aiErr := p.runAIAnalysisState(ctx, state, scope)
+ aiResult, aiErr := p.runAIAnalysisState(ctx, state, scope, executionID)
if aiErr != nil {
log.Warn().Err(aiErr).Msg("AI Patrol: LLM analysis failed")
runStats.errors++
@@ -530,7 +532,7 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
// AI-based alert review: check active alerts against current state and auto-resolve fixed issues
// Pass llmAllowed so it knows whether AI calls are allowed.
- alertsResolved := p.reviewAndResolveAlertsState(ctx, state, llmAllowed)
+ alertsResolved := p.reviewAndResolveAlertsState(ctx, state, llmAllowed, executionID)
if alertsResolved > 0 {
log.Info().Int("alerts_resolved", alertsResolved).Msg("AI Patrol: Auto-resolved alerts where issues are fixed")
}
@@ -718,6 +720,7 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)
start := time.Now()
runID := fmt.Sprintf("%d", start.UnixNano())
+ executionID := uuid.NewString()
GetPatrolMetrics().RecordRun(string(scope.Reason), "scoped")
var runStats struct {
resourceCount int
@@ -872,7 +875,7 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)
p.resetStreamForRun(runID)
}
// Run agentic AI analysis on filtered state with scope
- aiResult, aiErr := p.runAIAnalysisState(ctx, filteredState, &scope)
+ aiResult, aiErr := p.runAIAnalysisState(ctx, filteredState, &scope, executionID)
if aiErr != nil {
log.Warn().Err(aiErr).Msg("AI Patrol (scoped): LLM analysis failed")
runStats.errors++
@@ -1952,7 +1955,7 @@ func (p *PatrolService) GetCurrentStreamOutput() (string, string) {
// reviewAndResolveAlerts uses AI to review active alerts and resolve those where the issue is fixed.
// This is the core of autonomous alert management - the AI looks at each alert, checks current state,
// and determines if the underlying issue has been resolved.
-func (p *PatrolService) reviewAndResolveAlertsState(ctx context.Context, state patrolRuntimeState, llmAllowed bool) int {
+func (p *PatrolService) reviewAndResolveAlertsState(ctx context.Context, state patrolRuntimeState, llmAllowed bool, executionID string) int {
p.mu.RLock()
resolver := p.alertResolver
aiService := p.aiService
@@ -1995,7 +1998,7 @@ func (p *PatrolService) reviewAndResolveAlertsState(ctx context.Context, state p
}
for _, alert := range alertsToReview {
- shouldResolve, reason := p.shouldResolveAlertState(ctx, alert, state, aiSvc)
+ shouldResolve, reason := p.shouldResolveAlertState(ctx, alert, state, aiSvc, executionID)
if shouldResolve {
if resolver.ResolveAlert(alert.ID) {
resolvedCount++
@@ -2020,7 +2023,7 @@ func (p *PatrolService) reviewAndResolveAlertsState(ctx context.Context, state p
// shouldResolveAlert determines if an alert should be auto-resolved based on current state.
// Returns (shouldResolve, reason)
-func (p *PatrolService) shouldResolveAlertState(ctx context.Context, alert AlertInfo, snap patrolRuntimeState, aiService *Service) (bool, string) {
+func (p *PatrolService) shouldResolveAlertState(ctx context.Context, alert AlertInfo, snap patrolRuntimeState, aiService *Service, executionID string) (bool, string) {
// First, try smart heuristic checks based on alert type
switch alert.Type {
case "usage": // Storage usage alert
@@ -2055,7 +2058,7 @@ func (p *PatrolService) shouldResolveAlertState(ctx context.Context, alert Alert
// For complex cases or when heuristics don't apply, use AI judgment if available
if aiService != nil && aiService.IsEnabled() {
- return p.askAIAboutAlertState(ctx, alert, snap, aiService)
+ return p.askAIAboutAlertState(ctx, alert, snap, aiService, executionID)
}
return false, ""
@@ -2291,7 +2294,7 @@ func (p *PatrolService) isResourceOnlineState(alert AlertInfo, snap patrolRuntim
}
// askAIAboutAlert uses the AI to determine if an alert should be resolved
-func (p *PatrolService) askAIAboutAlertState(ctx context.Context, alert AlertInfo, snap patrolRuntimeState, aiService *Service) (bool, string) {
+func (p *PatrolService) askAIAboutAlertState(ctx context.Context, alert AlertInfo, snap patrolRuntimeState, aiService *Service, executionID string) (bool, string) {
alertType := patrolAlertLookupType(alert)
// Build a focused prompt for the AI
prompt := fmt.Sprintf(`Review this alert and determine if it should be auto-resolved based on current state.
@@ -2317,7 +2320,11 @@ Respond with ONLY one of:
p.getResourceCurrentStateState(alert, snap))
// Use a quick, low-cost AI call
- response, err := aiService.QuickAnalysis(ctx, prompt)
+ response, err := aiService.QuickAnalysis(ctx, QuickAnalysisRequest{
+ Prompt: prompt,
+ ExecutionID: executionID,
+ UseCase: "patrol",
+ })
if err != nil {
log.Debug().Err(err).Str("alertID", alert.ID).Msg("AI Patrol: Failed to get AI judgment on alert")
return false, ""
diff --git a/internal/ai/patrol_run_additional_test.go b/internal/ai/patrol_run_additional_test.go
index f58b89986d..a173bae244 100644
--- a/internal/ai/patrol_run_additional_test.go
+++ b/internal/ai/patrol_run_additional_test.go
@@ -63,7 +63,7 @@ func TestPatrolService_AskAIAboutAlert(t *testing.T) {
}
state := models.StateSnapshot{Nodes: []models.Node{{ID: "node1", Name: "node1", CPU: 10}}}
- resolved, reason := ps.askAIAboutAlertState(context.Background(), alert, patrolRuntimeStateForTest(ps, state), aiSvc)
+ resolved, reason := ps.askAIAboutAlertState(context.Background(), alert, patrolRuntimeStateForTest(ps, state), aiSvc, "patrol-run-123")
if !resolved {
t.Fatalf("expected alert to resolve")
}
@@ -73,6 +73,9 @@ func TestPatrolService_AskAIAboutAlert(t *testing.T) {
if !strings.Contains(provider.lastReq.Messages[1].Content, "Resource: node1 (node)") {
t.Fatalf("expected prompt to include canonical node resource type, got %q", provider.lastReq.Messages[1].Content)
}
+ if provider.lastReq.ExecutionID != "patrol-run-123" {
+ t.Fatalf("execution_id=%q want patrol-run-123", provider.lastReq.ExecutionID)
+ }
}
func TestPatrolService_AskAIAboutAlert_NormalizesUsageType(t *testing.T) {
@@ -96,7 +99,7 @@ func TestPatrolService_AskAIAboutAlert_NormalizesUsageType(t *testing.T) {
}
state := models.StateSnapshot{Storage: []models.Storage{{ID: "storage-1", Name: "local", Usage: 91, Status: "active"}}}
- resolved, _ := ps.askAIAboutAlertState(context.Background(), alert, patrolRuntimeStateForTest(ps, state), aiSvc)
+ resolved, _ := ps.askAIAboutAlertState(context.Background(), alert, patrolRuntimeStateForTest(ps, state), aiSvc, "patrol-run-usage")
if resolved {
t.Fatalf("expected alert to stay unresolved")
}
diff --git a/internal/ai/patrol_run_test.go b/internal/ai/patrol_run_test.go
index 7dede9e0b0..7a58a2351a 100644
--- a/internal/ai/patrol_run_test.go
+++ b/internal/ai/patrol_run_test.go
@@ -1984,7 +1984,7 @@ func TestShouldResolveAlert_StorageUsageDropped(t *testing.T) {
StartTime: time.Now().Add(-1 * time.Hour),
}
- shouldResolve, reason := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil)
+ shouldResolve, reason := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")
if !shouldResolve {
t.Error("expected alert to be resolved (usage dropped below threshold)")
}
@@ -2011,7 +2011,7 @@ func TestShouldResolveAlert_CPUDropped(t *testing.T) {
StartTime: time.Now().Add(-30 * time.Minute),
}
- shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil)
+ shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")
if !shouldResolve {
t.Error("expected alert to be resolved (CPU dropped)")
}
@@ -2033,7 +2033,7 @@ func TestShouldResolveAlert_OfflineNowOnline(t *testing.T) {
StartTime: time.Now().Add(-1 * time.Hour),
}
- shouldResolve, reason := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil)
+ shouldResolve, reason := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")
if !shouldResolve {
t.Error("expected offline alert to be resolved (resource now online)")
}
@@ -2056,7 +2056,7 @@ func TestShouldResolveAlert_NoMatch(t *testing.T) {
StartTime: time.Now().Add(-30 * time.Minute),
}
- shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil)
+ shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")
if shouldResolve {
t.Error("expected alert NOT to be resolved when resource not found")
}
@@ -2080,7 +2080,7 @@ func TestShouldResolveAlert_StorageStillHigh(t *testing.T) {
StartTime: time.Now().Add(-1 * time.Hour),
}
- shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil)
+ shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")
if shouldResolve {
t.Error("expected alert NOT to be resolved (storage usage still above threshold)")
}
@@ -2107,7 +2107,7 @@ func TestShouldResolveAlert_CPUScaleRegression(t *testing.T) {
StartTime: time.Now().Add(-30 * time.Minute),
}
- shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil)
+ shouldResolve, _ := ps.shouldResolveAlertState(nil, alert, patrolRuntimeStateForTest(ps, state), nil, "")
if shouldResolve {
t.Error("expected CPU alert NOT to be resolved (95% is still above 90% threshold)")
}
@@ -2150,7 +2150,7 @@ func TestReviewAndResolveAlerts_NilResolver(t *testing.T) {
ps := NewPatrolService(nil, nil)
state := models.StateSnapshot{}
- result := ps.reviewAndResolveAlertsState(nil, patrolRuntimeStateForTest(ps, state), true)
+ result := ps.reviewAndResolveAlertsState(nil, patrolRuntimeStateForTest(ps, state), true, "")
if result != 0 {
t.Errorf("expected 0 resolved with nil resolver, got %d", result)
}
@@ -2164,7 +2164,7 @@ func TestReviewAndResolveAlerts_NoActiveAlerts(t *testing.T) {
ps.mu.Unlock()
state := models.StateSnapshot{}
- result := ps.reviewAndResolveAlertsState(nil, patrolRuntimeStateForTest(ps, state), true)
+ result := ps.reviewAndResolveAlertsState(nil, patrolRuntimeStateForTest(ps, state), true, "")
if result != 0 {
t.Errorf("expected 0 resolved with no alerts, got %d", result)
}
@@ -2191,7 +2191,7 @@ func TestReviewAndResolveAlerts_SkipsRecentAlerts(t *testing.T) {
Nodes: []models.Node{{ID: "n1", Name: "node-1", Status: "online"}},
}
- result := ps.reviewAndResolveAlertsState(nil, patrolRuntimeStateForTest(ps, state), true)
+ result := ps.reviewAndResolveAlertsState(nil, patrolRuntimeStateForTest(ps, state), true, "")
if result != 0 {
t.Errorf("expected 0 resolved (alert too recent), got %d", result)
}
diff --git a/internal/ai/patrol_triage_integration_test.go b/internal/ai/patrol_triage_integration_test.go
index c722b6dc74..32a77f0d1e 100644
--- a/internal/ai/patrol_triage_integration_test.go
+++ b/internal/ai/patrol_triage_integration_test.go
@@ -22,7 +22,7 @@ func TestRunAIAnalysis_TriageQuietSkipsLLM(t *testing.T) {
t.Fatalf("expected quiet triage state, got IsQuiet=%v", triage.IsQuiet)
}
- res, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, state), nil)
+ res, err := ps.runAIAnalysisState(context.Background(), patrolRuntimeStateForTest(ps, state), nil, "")
if err != nil {
t.Fatalf("runAIAnalysis() unexpected error for quiet triage: %v", err)
}
diff --git a/internal/ai/providers/quickstart.go b/internal/ai/providers/quickstart.go
index 9a1c9dcca9..f24bc283a0 100644
--- a/internal/ai/providers/quickstart.go
+++ b/internal/ai/providers/quickstart.go
@@ -60,8 +60,8 @@ func NewQuickstartClient(licenseID string) *QuickstartClient {
// QuickstartServerState is the authoritative quickstart inventory snapshot
// returned by the license server alongside a Patrol response.
type QuickstartServerState struct {
- CreditsRemaining int
- CreditsTotal int
+ CreditsRemaining *int
+ CreditsTotal *int
TokenExpiresAt *time.Time
}
@@ -96,8 +96,8 @@ type quickstartResponse struct {
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
InputTokens int `json:"input_tokens,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
- CreditsRemaining int `json:"credits_remaining,omitempty"`
- CreditsTotal int `json:"credits_total,omitempty"`
+ CreditsRemaining *int `json:"credits_remaining,omitempty"`
+ CreditsTotal *int `json:"credits_total,omitempty"`
QuickstartTokenExpiresAt string `json:"quickstart_token_expires_at,omitempty"`
TokenExpiresAt string `json:"token_expires_at,omitempty"`
Code string `json:"code,omitempty"`
@@ -219,6 +219,10 @@ func (c *QuickstartClient) Chat(ctx context.Context, req ChatRequest) (*ChatResp
if resp.StatusCode != http.StatusOK {
var failure quickstartResponse
if err := json.Unmarshal(respBody, &failure); err == nil {
+ if failure.Code == "quickstart_credits_exhausted" && failure.CreditsRemaining == nil {
+ remaining := 0
+ failure.CreditsRemaining = &remaining
+ }
c.syncServerState(failure)
}
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
@@ -228,8 +232,8 @@ func (c *QuickstartClient) Chat(ctx context.Context, req ChatRequest) (*ChatResp
StatusCode: resp.StatusCode,
Code: strings.TrimSpace(failure.Code),
Message: firstNonEmpty(strings.TrimSpace(failure.Error), strings.TrimSpace(string(respBody))),
- CreditsRemaining: failure.CreditsRemaining,
- CreditsTotal: failure.CreditsTotal,
+ CreditsRemaining: quickstartOptionalInt(failure.CreditsRemaining),
+ CreditsTotal: quickstartOptionalInt(failure.CreditsTotal),
}
// Don't retry on client errors (4xx)
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
@@ -345,15 +349,27 @@ func (c *QuickstartClient) syncServerState(result quickstartResponse) {
if c == nil || c.onStateSync == nil {
return
}
- state := QuickstartServerState{
- CreditsRemaining: result.CreditsRemaining,
- CreditsTotal: result.CreditsTotal,
+ state := QuickstartServerState{}
+ hasState := false
+ if result.CreditsRemaining != nil {
+ remaining := *result.CreditsRemaining
+ state.CreditsRemaining = &remaining
+ hasState = true
+ }
+ if result.CreditsTotal != nil {
+ total := *result.CreditsTotal
+ state.CreditsTotal = &total
+ hasState = true
}
if rawExpiry := firstNonEmpty(result.QuickstartTokenExpiresAt, result.TokenExpiresAt); rawExpiry != "" {
if parsed, err := time.Parse(time.RFC3339, rawExpiry); err == nil {
state.TokenExpiresAt = &parsed
+ hasState = true
}
}
+ if !hasState {
+ return
+ }
c.onStateSync(state)
}
@@ -372,3 +388,10 @@ func firstNonEmpty(values ...string) string {
}
return ""
}
+
+func quickstartOptionalInt(v *int) int {
+ if v == nil {
+ return 0
+ }
+ return *v
+}
diff --git a/internal/ai/providers/quickstart_test.go b/internal/ai/providers/quickstart_test.go
index d9da6fc701..ac11348cc3 100644
--- a/internal/ai/providers/quickstart_test.go
+++ b/internal/ai/providers/quickstart_test.go
@@ -58,6 +58,8 @@ func TestQuickstartClientWithToken_UsesBearerAuthAndSyncsServerState(t *testing.
var seenExecutionID string
var synced QuickstartServerState
var syncCalls int
+ remaining := 16
+ total := 25
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req quickstartRequest
@@ -72,8 +74,8 @@ func TestQuickstartClientWithToken_UsesBearerAuthAndSyncsServerState(t *testing.
Content: "hello",
Model: quickstartModel,
StopReason: "end_turn",
- CreditsRemaining: 16,
- CreditsTotal: 25,
+ CreditsRemaining: &remaining,
+ CreditsTotal: &total,
QuickstartTokenExpiresAt: "2026-04-02T12:00:00Z",
}); err != nil {
t.Fatalf("encode response: %v", err)
@@ -109,8 +111,11 @@ func TestQuickstartClientWithToken_UsesBearerAuthAndSyncsServerState(t *testing.
if syncCalls != 1 {
t.Fatalf("syncCalls=%d want 1", syncCalls)
}
- if synced.CreditsRemaining != 16 || synced.CreditsTotal != 25 {
- t.Fatalf("synced credits=%d/%d want 16/25", synced.CreditsRemaining, synced.CreditsTotal)
+ if synced.CreditsRemaining == nil || synced.CreditsTotal == nil {
+ t.Fatalf("expected synced credits, got %v/%v", synced.CreditsRemaining, synced.CreditsTotal)
+ }
+ if *synced.CreditsRemaining != 16 || *synced.CreditsTotal != 25 {
+ t.Fatalf("synced credits=%d/%d want 16/25", *synced.CreditsRemaining, *synced.CreditsTotal)
}
if synced.TokenExpiresAt == nil {
t.Fatal("expected token expiry sync")
@@ -124,13 +129,15 @@ func TestQuickstartClientWithToken_AcceptsTokenExpiresAtAlias(t *testing.T) {
var synced QuickstartServerState
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ remaining := 24
+ total := 25
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(quickstartResponse{
Content: "hello",
Model: quickstartModel,
StopReason: "end_turn",
- CreditsRemaining: 24,
- CreditsTotal: 25,
+ CreditsRemaining: &remaining,
+ CreditsTotal: &total,
TokenExpiresAt: "2026-04-03T19:00:00Z",
}); err != nil {
t.Fatalf("encode response: %v", err)
@@ -163,11 +170,13 @@ func TestQuickstartClientWithToken_ExhaustionSyncsStateAndReturnsTypedError(t *t
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPaymentRequired)
w.Header().Set("Content-Type", "application/json")
+ remaining := 0
+ total := 25
if err := json.NewEncoder(w).Encode(quickstartResponse{
Error: "credits exhausted",
Code: "quickstart_credits_exhausted",
- CreditsRemaining: 0,
- CreditsTotal: 25,
+ CreditsRemaining: &remaining,
+ CreditsTotal: &total,
}); err != nil {
t.Fatalf("encode response: %v", err)
}
@@ -192,7 +201,40 @@ func TestQuickstartClientWithToken_ExhaustionSyncsStateAndReturnsTypedError(t *t
if syncCalls != 1 {
t.Fatalf("syncCalls=%d want 1", syncCalls)
}
- if synced.CreditsRemaining != 0 || synced.CreditsTotal != 25 {
- t.Fatalf("synced credits=%d/%d want 0/25", synced.CreditsRemaining, synced.CreditsTotal)
+ if synced.CreditsRemaining == nil || synced.CreditsTotal == nil {
+ t.Fatalf("expected synced credits, got %v/%v", synced.CreditsRemaining, synced.CreditsTotal)
+ }
+ if *synced.CreditsRemaining != 0 || *synced.CreditsTotal != 25 {
+ t.Fatalf("synced credits=%d/%d want 0/25", *synced.CreditsRemaining, *synced.CreditsTotal)
+ }
+}
+
+func TestQuickstartClientWithToken_DoesNotZeroCreditsWhenErrorOmitsInventory(t *testing.T) {
+ var syncCalls int
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusBadGateway)
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(quickstartResponse{
+ Error: "temporary upstream failure",
+ }); err != nil {
+ t.Fatalf("encode response: %v", err)
+ }
+ }))
+ defer server.Close()
+
+ t.Setenv("PULSE_AI_QUICKSTART_PROXY_URL", server.URL)
+
+ client := NewQuickstartClientWithToken("qst_live_test", func(state QuickstartServerState) {
+ syncCalls++
+ }, nil)
+ _, err := client.Chat(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "Hi"}},
+ })
+ if err == nil {
+ t.Fatal("expected quickstart error")
+ }
+ if syncCalls != 0 {
+ t.Fatalf("syncCalls=%d want 0 when error omits inventory", syncCalls)
}
}
diff --git a/internal/ai/quickstart.go b/internal/ai/quickstart.go
index 70952ac40e..0ea3dfafd2 100644
--- a/internal/ai/quickstart.go
+++ b/internal/ai/quickstart.go
@@ -332,11 +332,22 @@ func (m *PersistentQuickstartCreditManager) syncServerState(serverState provider
return
}
- state.QuickstartCreditsRemaining = max(0, serverState.CreditsRemaining)
- state.QuickstartCreditsTotal = max(0, serverState.CreditsTotal)
+ updated := false
+ if serverState.CreditsRemaining != nil {
+ state.QuickstartCreditsRemaining = max(0, *serverState.CreditsRemaining)
+ updated = true
+ }
+ if serverState.CreditsTotal != nil {
+ state.QuickstartCreditsTotal = max(0, *serverState.CreditsTotal)
+ updated = true
+ }
if serverState.TokenExpiresAt != nil {
expiryUnix := serverState.TokenExpiresAt.UTC().Unix()
state.QuickstartTokenExpiresAt = &expiryUnix
+ updated = true
+ }
+ if !updated {
+ return
}
nowUnix := m.now().Unix()
state.LastSyncedAt = &nowUnix
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 05307694fa..5d1ab6819b 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -161,6 +161,15 @@ type PatrolExecuteRequest struct {
MaxTurns int `json:"max_turns,omitempty"`
}
+// QuickAnalysisRequest represents a lightweight single-turn analysis request.
+// ExecutionID lets higher-level workflows group ancillary calls under one
+// commercial run instead of charging each helper call separately.
+type QuickAnalysisRequest struct {
+ Prompt string `json:"prompt"`
+ ExecutionID string `json:"execution_id,omitempty"`
+ UseCase string `json:"use_case,omitempty"`
+}
+
// PatrolStreamResponse contains the results of a patrol execution via the chat service
type PatrolStreamResponse struct {
Content string `json:"content"`
@@ -1733,7 +1742,7 @@ func (s *Service) createPatrolProviderForModel(modelStr string) (providers.Strea
// QuickAnalysis performs a lightweight AI analysis for simple decisions.
// This is used for things like determining if an alert should be auto-resolved.
// It uses a single-turn, no-tools call for efficiency.
-func (s *Service) QuickAnalysis(ctx context.Context, prompt string) (string, error) {
+func (s *Service) QuickAnalysis(ctx context.Context, req QuickAnalysisRequest) (string, error) {
s.mu.RLock()
provider := s.provider
cfg := s.cfg
@@ -1756,13 +1765,19 @@ func (s *Service) QuickAnalysis(ctx context.Context, prompt string) (string, err
},
{
Role: "user",
- Content: prompt,
+ Content: req.Prompt,
},
}
+ executionID := strings.TrimSpace(req.ExecutionID)
+ if executionID == "" {
+ executionID = uuid.NewString()
+ }
+
resp, err := provider.Chat(ctx, providers.ChatRequest{
- Messages: messages,
- Model: model,
+ Messages: messages,
+ Model: model,
+ ExecutionID: executionID,
})
if err != nil {
return "", fmt.Errorf("Pulse Assistant analysis failed: %w", err)
diff --git a/internal/ai/service_coverage_imp_test.go b/internal/ai/service_coverage_imp_test.go
index 2efe3c05ea..6e99867962 100644
--- a/internal/ai/service_coverage_imp_test.go
+++ b/internal/ai/service_coverage_imp_test.go
@@ -18,7 +18,7 @@ func TestService_QuickAnalysis(t *testing.T) {
svc := NewService(nil, nil)
// Case 1: No provider configured
- _, err := svc.QuickAnalysis(context.Background(), "test")
+ _, err := svc.QuickAnalysis(context.Background(), QuickAnalysisRequest{Prompt: "test"})
if err == nil || !strings.Contains(err.Error(), "not enabled") {
t.Errorf("Expected error about provider not enabled, got: %v", err)
}
@@ -29,6 +29,9 @@ func TestService_QuickAnalysis(t *testing.T) {
if req.Model != "fast-model" {
return nil, nil // Should use patrol model
}
+ if req.ExecutionID != "patrol-run-123" {
+ t.Fatalf("execution_id=%q want patrol-run-123", req.ExecutionID)
+ }
return &providers.ChatResponse{
Content: "Analysis Result",
}, nil
@@ -40,7 +43,11 @@ func TestService_QuickAnalysis(t *testing.T) {
PatrolModel: "fast-model",
}
- res, err := svc.QuickAnalysis(context.Background(), "Analysis prompt")
+ res, err := svc.QuickAnalysis(context.Background(), QuickAnalysisRequest{
+ Prompt: "Analysis prompt",
+ ExecutionID: "patrol-run-123",
+ UseCase: "patrol",
+ })
if err != nil {
t.Fatalf("QuickAnalysis failed: %v", err)
}
@@ -52,7 +59,7 @@ func TestService_QuickAnalysis(t *testing.T) {
mockProv.chatFunc = func(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {
return &providers.ChatResponse{Content: ""}, nil
}
- _, err = svc.QuickAnalysis(context.Background(), "test")
+ _, err = svc.QuickAnalysis(context.Background(), QuickAnalysisRequest{Prompt: "test"})
if err == nil {
t.Error("Expected error for empty response")
}