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
Replace Patrol quickstart with server bootstrap
rcourtman57cc212f3496
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex a6305f992f..7f446984e4 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -123,6 +123,13 @@ management, and fleet control surfaces.## Extension Points1. Add or change install-command generation, canonical /api/auto-register behavior, or installer download behavior through the owned `internal/api/` files above.+ That same shared `internal/api/` adjacency does not transfer ownership of+ Patrol quickstart bootstrap or mobile Patrol-provider bridging:+ `internal/api/ai_handlers.go` and `internal/api/chat_service_adapter.go`+ may be invoked by lifecycle-adjacent surfaces, but server-issued+ quickstart tokens, Patrol quickstart credit snapshots, and AI runtime auth+ remain `ai-runtime` plus `api-contracts` concerns rather than install-token+ or lifecycle credential state.2. Add or change update continuity and persisted-version handoff through `internal/agentupdate/`.3. Add or change runtime-side Unified Agent startup, first-report assembly, and enroll/runtime continuity through `internal/hostagent/`.Proxmox host-agent setup must treat local `proxmox-registered` markers as a cache, not authority: before skipping token setup or node repair, `internal/hostagent/proxmox_setup.go` must revalidate the current type and candidate hosts against Pulse through the canonical auto-register contract.diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex cc10cced6f..2c51e616f8 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -114,6 +114,18 @@ may exist only as an explicit environment-controlled rollout escape hatch, andthe canonical quickstart proxy contract remains an OpenAI-compatible server-ownedsurface that lives behind the public license API rather than a tenant-local ormobile-local adapter.+That same Patrol quickstart boundary is now server-authoritative end to end.+`internal/ai/quickstart.go` must bootstrap before the first Patrol-only+quickstart use, prefer installation identity from `activation.enc` when an+activation token exists, and otherwise persist one stable community+`client_installation_id` plus the returned token snapshot under+`quickstart.enc` through the shared `internal/config/persistence.go` and+`internal/config/quickstart_state.go` helpers. `internal/ai/providers/quickstart.go`+must authenticate Patrol proxy calls with `Authorization: Bearer <quickstart_token>`,+sync `credits_remaining` / `credits_total` back into that cache on every server+response, and invalidate the cached token on auth rejection instead of reviving+local counter truth. Explicit BYOK provider credentials still outrank Patrol+quickstart whenever both are present.That same provider-model contract applies to the chat explore pre-pass in`internal/ai/chat/service_explore.go`: any runtime model that is valid for themain chat execution path, including `quickstart:minimax-2.5m`, must resolvediff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 30d0f73794..ec8adf07e0 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -231,6 +231,13 @@ Own canonical runtime payload shapes between backend and frontend.6. Keep Patrol status payloads explicit enough that the frontend can present blocked runtime state without treating a previously healthy summary snapshot as current runtime truth, and keep Patrol recency semantics explicit in transport by reserving `last_patrol_at` for completed full patrols while exposing any Patrol activity separately through `last_activity_at`and the scoped-trigger status payload on that same Patrol status surface, so queued scoped work, busy-mode state, and per-source enablement (`alert` versus `anomaly`) stay transport-backed instead of being inferred by page-local heuristicsand the split Patrol trigger settings contract, so `patrol_alert_triggers_enabled` and `patrol_anomaly_triggers_enabled` are the canonical AI settings fields while legacy `patrol_event_triggers_enabled` remains a compatibility aggregate rather than the primary control surface+ and the server-authoritative quickstart contract, so `/api/settings/ai` and+ `/api/patrol/status` keep `quickstart_credits_remaining`,+ `quickstart_credits_total`, and `using_quickstart` as canonical transport+ fields sourced from the latest quickstart bootstrap or proxy response rather+ than from local grant counters, and shared handlers must not invent+ client-authored commercial identity or synthetic credits when the quickstart+ server is unavailable7. Keep Patrol summary payload consumers aligned on one assessment hierarchy: transport-driven Patrol summary surfaces may show supporting counts and outcomes, but the canonical assessment and verification states must remain singular and not be repeated as a second compact verdict strip8. Keep Patrol verification and activity facts unified on one transport-backed secondary status area: when frontend consumers combine Patrol status payloads (`runtime_state`, `last_patrol_at`, `last_activity_at`, `trigger_status`) with run-history transport, the latest run result, activity mix, scoped-trigger state, and circuit-breaker context must read as one supporting explanation beneath the primary assessment instead of being re-expanded into a separate full-width status strip plus duplicate summary layersand the main Patrol page composition boundary, so once that governeddiff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex bf0ded1c3d..a07a1a1372 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -97,7 +97,7 @@ agreement, and cloud-specific enforcement rules.6. Add or change the hosted account portal API, task-first browser shell, maintained portal frontend/bundle, or account-scoped workspace/access/billing handoff through `internal/cloudcp/portal/` and `internal/cloudcp/routes.go`7. Add or change Stripe provisioning plan resolution through `internal/cloudcp/stripe/provisioner.go`8. Add or change activation/grant lifecycle or dev-mode capability widening through `pkg/licensing/dev_mode_features.go`, `pkg/licensing/service.go`, `pkg/licensing/grant_refresh.go`, and `pkg/licensing/revocation_poll.go`-9. Add or change license-server transport through `pkg/licensing/license_server_client.go`+9. Add or change license-server transport through `pkg/licensing/license_server_client.go` and `pkg/licensing/quickstart_bootstrap.go`10. Add or change encrypted activation persistence through `pkg/licensing/persistence.go` and `pkg/licensing/activation_store.go`11. Add or change hosted trial token semantics through `pkg/licensing/trial_activation.go`12. Add or change hosted signup provisioning through `internal/hosted/provisioner.go`@@ -237,6 +237,15 @@ backward-compatible decode alias for older local stubs and historical testfixtures. Future exchange-path changes must not reintroduce a split contractwhere the shared Pulse runtime and the real `pulse-pro/license-server` disagreeon the activation payload shape.+That same license-server transport boundary now owns Patrol quickstart+bootstrap. `pkg/licensing/license_server_client.go` and+`pkg/licensing/quickstart_bootstrap.go` must treat+`POST /v1/quickstart/bootstrap` as the canonical exchange for a server-issued+quickstart token plus the authoritative quickstart credit snapshot. Activated+installs authenticate that bootstrap with the installation token, community+installs send a stable `client_installation_id`, and local runtime cache files+may memoize the returned token and counts but may not treat those cached counts+as commercial authority.The self-hosted commercial counted unit is now also locked to monitoredsystems rather than agent installs. `max_monitored_systems` is the liveruntime and UI contract, while legacy `max_agents` / `max_nodes` aliases arediff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex 6b4eafbe29..03dfcb9764 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -1898,7 +1898,8 @@"label": "license server transport proof","match_prefixes": [],"match_files": [- "pkg/licensing/license_server_client.go"+ "pkg/licensing/license_server_client.go",+ "pkg/licensing/quickstart_bootstrap.go"],"allow_same_subsystem_tests": false,"test_prefixes": [],diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex ff9f7ea0f2..b353af2fd3 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -104,6 +104,13 @@ querying, and the operator-facing storage health presentation layer.19. Preserve shipped local security-doc guidance in shared `internal/api/` config/setup helpers so storage- and recovery-adjacent transport surfaces do not reintroduce GitHub `main` security links when the running build already serves its own local security documentation route.20. Keep shared `internal/api/` Patrol transport and alert-trigger edits feature-isolated: Patrol-specific recency fields, callback fan-out, or alert-bridge wiring changes must not leak into recovery queries, storage links, or recovery-adjacent install/setup flows unless this contract changes in the same slice.The same adjacency rule applies to AI settings transport in `internal/api/ai_handlers.go`: provider auth state, masked-secret payload fields, and provider-test model selection remain AI/runtime plus API-contract concerns and must not be absorbed into storage/recovery transport ownership just because those handlers live under the shared backend API tree.+ That same adjacent boundary also owns the server-authoritative Patrol+ quickstart contract: bootstrap-triggered `quickstart_credits_remaining`,+ `quickstart_credits_total`, `using_quickstart`, and cached bearer-token+ state exposed through shared AI handlers are transport facts owned by the+ AI/runtime plus API-contract lanes, and storage/recovery surfaces must not+ reintroduce local quickstart accounting, token lifecycle, or commercial+ identity rules.21. Keep provider-backed recovery onboarding on the adjacent platform-connections contract. When `internal/api/` grows or changes TrueNAS connection CRUD, masked-secret preservation, saved-connection retest routes, edit-form saved-test payload overlays, or similar provider setup flows, storage and recovery may consume the resulting recovery points but must not absorb that connection-management ownership into storage/recovery-local handlers or page flows.22. Keep backend-native platform actions on the adjacent AI/runtime and platform contracts. When `internal/api/` wires native TrueNAS app control for Assistant, storage and recovery may consume the refreshed recovery points afterward, but they must not grow a parallel recovery-local action transport or action-specific payload shape.23. Keep backend-native platform diagnostics on the adjacent AI/runtime and platform contracts. When `internal/api/` wires native TrueNAS app log reads for Assistant, storage and recovery may use those diagnostics during investigation, but they must not grow a parallel recovery-local log transport or diagnostic payload shape.diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 64680a85c3..0f722f5519 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -77,28 +77,38 @@ type Config struct {type Service struct {mu sync.RWMutex- cfg *config.AIConfig- dataDir string- stateProvider StateProvider- readState unifiedresources.ReadState- agentServer AgentServer- executor *tools.PulseToolExecutor- actionAuditStore unifiedresources.ResourceStore- sessions *SessionStore- agenticLoop *AgenticLoop- provider providers.StreamingProvider- providerFactory func(modelStr string) (providers.StreamingProvider, error)- started bool- autonomousMode bool- contextPrefetcher *ContextPrefetcher- budgetChecker func() error // Optional mid-run budget enforcement- orgID string+ cfg *config.AIConfig+ dataDir string+ stateProvider StateProvider+ readState unifiedresources.ReadState+ agentServer AgentServer+ executor *tools.PulseToolExecutor+ actionAuditStore unifiedresources.ResourceStore+ sessions *SessionStore+ agenticLoop *AgenticLoop+ provider providers.StreamingProvider+ providerFactory func(modelStr string) (providers.StreamingProvider, error)+ patrolProviderFactory func(modelStr string) (providers.StreamingProvider, error)+ started bool+ autonomousMode bool+ contextPrefetcher *ContextPrefetcher+ budgetChecker func() error // Optional mid-run budget enforcement+ orgID stringactiveMu sync.RWMutexactiveExecutions map[string]map[*AgenticLoop]struct{}questionExecutions map[string]*AgenticLoop}+// SetPatrolProviderFactory installs a Patrol-only provider factory override.+// This lets Patrol use a different quickstart contract without changing normal+// interactive chat provider selection in the same slice.+func (s *Service) SetPatrolProviderFactory(factory func(modelStr string) (providers.StreamingProvider, error)) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.patrolProviderFactory = factory+}+// NewService creates a new chat servicefunc NewService(cfg Config) *Service {// Create tool executor@@ -765,7 +775,7 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca}// Create a temporary provider for the patrol model- provider, err := s.createProviderForModel(patrolModel)+ provider, err := s.createPatrolProviderForModel(patrolModel)if err != nil {return nil, fmt.Errorf("failed to create patrol provider: %w", err)}@@ -941,6 +951,13 @@ func (s *Service) createProviderForModel(modelStr string) (providers.StreamingPr}}+func (s *Service) createPatrolProviderForModel(modelStr string) (providers.StreamingProvider, error) {+ if s.patrolProviderFactory != nil {+ return s.patrolProviderFactory(modelStr)+ }+ return s.createProviderForModel(modelStr)+}+// ListAvailableTools returns tool names available for the given prompt.func (s *Service) ListAvailableTools(ctx context.Context, prompt string) []string {s.mu.RLock()diff --git a/internal/ai/patrol.go b/internal/ai/patrol.goindex 224200ad8b..5c8d5ef45a 100644--- a/internal/ai/patrol.go+++ b/internal/ai/patrol.go@@ -88,7 +88,10 @@ const (PatrolRuntimeStateActive PatrolRuntimeState = "active")-const patrolQuickstartCreditsExhaustedReason = "Quickstart credits exhausted. Connect your API key to continue using AI Patrol."+const (+ patrolQuickstartCreditsExhaustedReason = "Quickstart credits exhausted. Connect your API key to continue using AI Patrol."+ patrolQuickstartUnavailableReason = "Quickstart credits require internet access. Connect your API key for offline AI Patrol."+)type PatrolStatus struct {RuntimeState PatrolRuntimeState `json:"runtime_state"`diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.goindex 0b4d6e4c4a..3e3cedc42e 100644--- a/internal/ai/patrol_run.go+++ b/internal/ai/patrol_run.go@@ -12,10 +12,10 @@ import ("time""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""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing""github.com/rs/zerolog/log")@@ -369,8 +369,10 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Triggeif !canRunLLM {reason := "AI not configured - set up a provider in Settings > Pulse Assistant"if !aiServiceEnabled {- // Distinguish between exhausted credits and no AI configured- if qsMgr != nil && !qsMgr.HasBYOK() && !qsMgr.HasCredits() {+ if p.aiService != nil && strings.TrimSpace(p.aiService.QuickstartBlockedReason()) != "" {+ reason = p.aiService.QuickstartBlockedReason()+ } else if qsMgr != nil && !qsMgr.HasBYOK() && !qsMgr.HasCredits() {+ // Distinguish between exhausted credits and no AI configured.reason = patrolQuickstartCreditsExhaustedReason} else {reason = "AI not configured - set up a provider in Settings > Pulse Assistant"@@ -386,6 +388,11 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge// Check if using quickstart credits — verify credits remain before startingusingQuickstart := p.aiService != nil && p.aiService.IsUsingQuickstart()+ if usingQuickstart && p.aiService != nil && strings.TrimSpace(p.aiService.QuickstartBlockedReason()) != "" {+ p.setBlockedReason(p.aiService.QuickstartBlockedReason())+ log.Info().Str("reason", p.aiService.QuickstartBlockedReason()).Msg("AI Patrol: Skipping run - quickstart unavailable")+ return+ }if usingQuickstart && qsMgr != nil && !qsMgr.HasCredits() {p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)log.Info().Msg("AI Patrol: Skipping run - quickstart credits exhausted")@@ -409,7 +416,7 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Triggeif usingQuickstart && (strings.Contains(errMsg, "dial tcp") || strings.Contains(errMsg, "no such host") || strings.Contains(errMsg, "connection refused") || strings.Contains(errMsg, "i/o timeout")) {title = "Pulse Patrol: Quickstart credits require internet"description = "Pulse Patrol cannot reach the quickstart proxy server. Quickstart credits require an internet connection."- recommendation = "Quickstart credits require internet access. Connect your API key for offline AI Patrol."+ recommendation = patrolQuickstartUnavailableReason} else if strings.Contains(errMsg, "Insufficient Balance") || strings.Contains(errMsg, "402") {title = "Pulse Patrol: Insufficient API credits"description = "Pulse Patrol cannot analyze your infrastructure because your provider account has insufficient credits."@@ -444,19 +451,21 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger TriggeLastSeenAt: time.Now(),}trackFinding(errorFinding)++ if usingQuickstart {+ switch {+ case providers.IsQuickstartCreditsExhausted(aiErr):+ p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)+ case providers.IsQuickstartUnavailable(aiErr), quickstartBootstrapUnavailable(aiErr):+ p.setBlockedReason(patrolQuickstartUnavailableReason)+ }+ }} else if aiResult != nil {runStats.aiAnalysis = aiResultrunStats.rejectedFindings = aiResult.RejectedFindingsrunStats.triageFlags = aiResult.TriageFlagsrunStats.triageSkippedLLM = aiResult.TriageSkippedLLM- // Consume a quickstart credit after successful run (only if LLM was actually used)- if usingQuickstart && !aiResult.TriageSkippedLLM && qsMgr != nil {- if err := qsMgr.ConsumeCredit(); err != nil {- log.Warn().Err(err).Msg("AI Patrol: Failed to consume quickstart credit")- }- }-// Auto-resolve previous patrol error finding if this run succeedederrorFindingID := generateFindingID("ai-service", "reliability", "ai-patrol-error")if existing := p.findings.Get(errorFindingID); existing != nil && !existing.IsResolved() {@@ -830,7 +839,9 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)if !canRunLLM {reason := "AI not configured - set up a provider in Settings > Pulse Assistant"if !aiServiceEnabled {- if scopedQsMgr != nil && !scopedQsMgr.HasBYOK() && !scopedQsMgr.HasCredits() {+ if p.aiService != nil && strings.TrimSpace(p.aiService.QuickstartBlockedReason()) != "" {+ reason = p.aiService.QuickstartBlockedReason()+ } else if scopedQsMgr != nil && !scopedQsMgr.HasBYOK() && !scopedQsMgr.HasCredits() {reason = patrolQuickstartCreditsExhaustedReason}} else if !llmAllowed {@@ -843,6 +854,11 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)}// Check if using quickstart credits — verify credits remain before starting+ if scopedUsingQuickstart && p.aiService != nil && strings.TrimSpace(p.aiService.QuickstartBlockedReason()) != "" {+ p.setBlockedReason(p.aiService.QuickstartBlockedReason())+ log.Info().Str("reason", p.aiService.QuickstartBlockedReason()).Msg("AI Patrol: Skipping scoped run - quickstart unavailable")+ return+ }if scopedUsingQuickstart && scopedQsMgr != nil && !scopedQsMgr.HasCredits() {p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)log.Info().Msg("AI Patrol: Skipping scoped run - quickstart credits exhausted")@@ -860,19 +876,20 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)if aiErr != nil {log.Warn().Err(aiErr).Msg("AI Patrol (scoped): LLM analysis failed")runStats.errors+++ if scopedUsingQuickstart {+ switch {+ case providers.IsQuickstartCreditsExhausted(aiErr):+ p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)+ case providers.IsQuickstartUnavailable(aiErr), quickstartBootstrapUnavailable(aiErr):+ p.setBlockedReason(patrolQuickstartUnavailableReason)+ }+ }} else if aiResult != nil {runStats.aiAnalysis = aiResultrunStats.rejectedFindings = aiResult.RejectedFindingsrunStats.triageFlags = aiResult.TriageFlagsrunStats.triageSkippedLLM = aiResult.TriageSkippedLLM- // Consume a quickstart credit after successful scoped run- if scopedUsingQuickstart && !aiResult.TriageSkippedLLM && scopedQsMgr != nil {- if err := scopedQsMgr.ConsumeCredit(); err != nil {- log.Warn().Err(err).Msg("AI Patrol (scoped): Failed to consume quickstart credit")- }- }-// Findings are already recorded via patrol_report_finding tool calls.for _, f := range aiResult.Findings {if f.Severity == FindingSeverityWarning || f.Severity == FindingSeverityCritical {@@ -1562,17 +1579,25 @@ func (p *PatrolService) GetStatus() PatrolStatus {if p.quickstartCredits != nil {status.QuickstartCreditsRemaining = p.quickstartCredits.CreditsRemaining()- status.QuickstartCreditsTotal = pkglicensing.QuickstartCreditsTotal+ status.QuickstartCreditsTotal = p.quickstartCredits.CreditsTotal()status.UsingQuickstart = p.aiService != nil && p.aiService.IsUsingQuickstart()}- quickstartBlocked := p.config.Enabled &&+ quickstartReason := ""+ if p.aiService != nil {+ quickstartReason = strings.TrimSpace(p.aiService.QuickstartBlockedReason())+ }+ if quickstartReason == "" &&+ p.config.Enabled &&p.quickstartCredits != nil &&!p.quickstartCredits.HasBYOK() &&- !p.quickstartCredits.HasCredits()- if quickstartBlocked {- status.BlockedReason = patrolQuickstartCreditsExhaustedReason- } else if strings.TrimSpace(status.BlockedReason) == patrolQuickstartCreditsExhaustedReason {+ !p.quickstartCredits.HasCredits() {+ quickstartReason = patrolQuickstartCreditsExhaustedReason+ }+ if quickstartReason != "" {+ status.BlockedReason = quickstartReason+ } else if strings.TrimSpace(status.BlockedReason) == patrolQuickstartCreditsExhaustedReason ||+ strings.TrimSpace(status.BlockedReason) == patrolQuickstartUnavailableReason {status.BlockedReason = ""}diff --git a/internal/ai/patrol_run_test.go b/internal/ai/patrol_run_test.goindex 991739f3db..7dede9e0b0 100644--- a/internal/ai/patrol_run_test.go+++ b/internal/ai/patrol_run_test.go@@ -1,6 +1,7 @@package aiimport (+ "context""strings""sync""testing"@@ -10,19 +11,26 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/providers""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing")type stubPatrolQuickstartCreditManager struct {remaining int+ total intbyok bool}-func (m *stubPatrolQuickstartCreditManager) HasCredits() bool { return m.remaining > 0 }-func (m *stubPatrolQuickstartCreditManager) CreditsRemaining() int { return m.remaining }-func (m *stubPatrolQuickstartCreditManager) ConsumeCredit() error { return nil }+func (m *stubPatrolQuickstartCreditManager) EnsureBootstrap(context.Context) error { return nil }+func (m *stubPatrolQuickstartCreditManager) HasCredits() bool { return m.remaining > 0 }+func (m *stubPatrolQuickstartCreditManager) CreditsRemaining() int { return m.remaining }+func (m *stubPatrolQuickstartCreditManager) CreditsTotal() int {+ if m.total > 0 {+ return m.total+ }+ return pkglicensing.QuickstartCreditsTotal+}func (m *stubPatrolQuickstartCreditManager) HasBYOK() bool { return m.byok }func (m *stubPatrolQuickstartCreditManager) GetProvider() providers.Provider { return nil }-func (m *stubPatrolQuickstartCreditManager) GrantCredits() error { return nil }// --- filterStateByScope tests ---diff --git a/internal/ai/providers/quickstart.go b/internal/ai/providers/quickstart.goindex 5c74c822a4..8a7a7d80ef 100644--- a/internal/ai/providers/quickstart.go+++ b/internal/ai/providers/quickstart.go@@ -29,9 +29,13 @@ const (// quickstart proxy. It forwards patrol chat requests through the public// commercial API edge so users don't need their own API key.type QuickstartClient struct {- // licenseID identifies the workspace (for rate limiting / credit tracking server-side).+ // licenseID is the legacy caller-chosen identity path.licenseID string- client *http.Client+ // quickstartToken is the server-issued bearer token path.+ quickstartToken string+ client *http.Client+ onStateSync func(QuickstartServerState)+ onTokenInvalid func()}func quickstartProxyURL() string {@@ -42,6 +46,7 @@ func quickstartProxyURL() string {}// NewQuickstartClient creates a quickstart provider that uses the hosted proxy.+// This is the legacy identity path retained for non-Patrol callers.func NewQuickstartClient(licenseID string) *QuickstartClient {return &QuickstartClient{licenseID: licenseID,@@ -51,34 +56,119 @@ 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+ TokenExpiresAt *time.Time+}++// NewQuickstartClientWithToken creates a quickstart provider that authenticates+// requests with a server-issued bearer token.+func NewQuickstartClientWithToken(quickstartToken string, onStateSync func(QuickstartServerState), onTokenInvalid func()) *QuickstartClient {+ return &QuickstartClient{+ quickstartToken: strings.TrimSpace(quickstartToken),+ onStateSync: onStateSync,+ onTokenInvalid: onTokenInvalid,+ client: &http.Client{+ Timeout: quickstartRequestTimeout,+ },+ }+}+// quickstartRequest is the payload sent to the hosted proxy.type quickstartRequest struct {Messages []Message `json:"messages"`System string `json:"system,omitempty"`Tools []Tool `json:"tools,omitempty"`- // LicenseID lets the server track credit usage per workspace.- LicenseID string `json:"license_id"`+ // LicenseID is retained only for the legacy caller-chosen identity path.+ LicenseID string `json:"license_id,omitempty"`}// quickstartResponse is the response from the hosted proxy.type quickstartResponse struct {- Content string `json:"content"`- Model string `json:"model"`- StopReason string `json:"stop_reason,omitempty"`- ToolCalls []ToolCall `json:"tool_calls,omitempty"`- InputTokens int `json:"input_tokens,omitempty"`- OutputTokens int `json:"output_tokens,omitempty"`+ Content string `json:"content"`+ Model string `json:"model"`+ StopReason string `json:"stop_reason,omitempty"`+ 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"`+ QuickstartTokenExpiresAt string `json:"quickstart_token_expires_at,omitempty"`+ Code string `json:"code,omitempty"`// Error is set when the server returns a structured error.Error string `json:"error,omitempty"`}+// QuickstartRequestError captures a structured quickstart proxy failure.+type QuickstartRequestError struct {+ StatusCode int+ Code string+ Message string+ CreditsRemaining int+ CreditsTotal int+}++func (e *QuickstartRequestError) Error() string {+ if e == nil {+ return "quickstart: request failed"+ }+ if msg := strings.TrimSpace(e.Message); msg != "" {+ return "quickstart: " + msg+ }+ return fmt.Sprintf("quickstart: server returned %d", e.StatusCode)+}++func (e *QuickstartRequestError) exhausted() bool {+ if e == nil {+ return false+ }+ if e.StatusCode == http.StatusPaymentRequired {+ return true+ }+ if strings.EqualFold(strings.TrimSpace(e.Code), "quickstart_credits_exhausted") {+ return true+ }+ return e.CreditsTotal > 0 && e.CreditsRemaining == 0+}++func (e *QuickstartRequestError) unavailable() bool {+ if e == nil {+ return false+ }+ switch e.StatusCode {+ case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:+ return true+ default:+ return strings.Contains(strings.ToLower(strings.TrimSpace(e.Code)), "unavailable")+ }+}++// IsQuickstartCreditsExhausted reports whether err represents an exhausted+// quickstart inventory response from the server.+func IsQuickstartCreditsExhausted(err error) bool {+ typed, ok := err.(*QuickstartRequestError)+ return ok && typed.exhausted()+}++// IsQuickstartUnavailable reports whether err represents a quickstart transport+// failure returned by the license server.+func IsQuickstartUnavailable(err error) bool {+ typed, ok := err.(*QuickstartRequestError)+ return ok && typed.unavailable()+}+// Chat sends a chat request through the Pulse-hosted quickstart proxy.func (c *QuickstartClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error) {payload := quickstartRequest{- Messages: req.Messages,- System: req.System,- Tools: req.Tools,- LicenseID: c.licenseID,+ Messages: req.Messages,+ System: req.System,+ Tools: req.Tools,+ }+ if strings.TrimSpace(c.quickstartToken) == "" {+ payload.LicenseID = c.licenseID}body, err := json.Marshal(payload)@@ -104,6 +194,9 @@ func (c *QuickstartClient) Chat(ctx context.Context, req ChatRequest) (*ChatRespreturn nil, fmt.Errorf("quickstart: create request: %w", err)}httpReq.Header.Set("Content-Type", "application/json")+ if token := strings.TrimSpace(c.quickstartToken); token != "" {+ httpReq.Header.Set("Authorization", "Bearer "+token)+ }resp, err := c.client.Do(httpReq)if err != nil {@@ -120,7 +213,20 @@ func (c *QuickstartClient) Chat(ctx context.Context, req ChatRequest) (*ChatResp}if resp.StatusCode != http.StatusOK {- lastErr = fmt.Errorf("quickstart: server returned %d: %s", resp.StatusCode, string(respBody))+ var failure quickstartResponse+ if err := json.Unmarshal(respBody, &failure); err == nil {+ c.syncServerState(failure)+ }+ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ c.invalidateToken()+ }+ lastErr = &QuickstartRequestError{+ StatusCode: resp.StatusCode,+ Code: strings.TrimSpace(failure.Code),+ Message: firstNonEmpty(strings.TrimSpace(failure.Error), strings.TrimSpace(string(respBody))),+ CreditsRemaining: failure.CreditsRemaining,+ CreditsTotal: failure.CreditsTotal,+ }// Don't retry on client errors (4xx)if resp.StatusCode >= 400 && resp.StatusCode < 500 {return nil, lastErr@@ -136,6 +242,7 @@ func (c *QuickstartClient) Chat(ctx context.Context, req ChatRequest) (*ChatRespif result.Error != "" {return nil, fmt.Errorf("quickstart: server error: %s", result.Error)}+ c.syncServerState(result)return &ChatResponse{Content: result.Content,@@ -153,11 +260,18 @@ func (c *QuickstartClient) Chat(ctx context.Context, req ChatRequest) (*ChatResp// TestConnection validates connectivity to the quickstart proxy.func (c *QuickstartClient) TestConnection(ctx context.Context) error {// Simple connectivity check — send a minimal request.- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, quickstartProxyURL(), bytes.NewReader([]byte(`{"messages":[],"license_id":"`+c.licenseID+`"}`)))+ requestBody := `{"messages":[]}`+ if strings.TrimSpace(c.quickstartToken) == "" {+ requestBody = `{"messages":[],"license_id":"` + c.licenseID + `"}`+ }+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, quickstartProxyURL(), bytes.NewReader([]byte(requestBody)))if err != nil {return fmt.Errorf("quickstart: create test request: %w", err)}httpReq.Header.Set("Content-Type", "application/json")+ if token := strings.TrimSpace(c.quickstartToken); token != "" {+ httpReq.Header.Set("Authorization", "Bearer "+token)+ }resp, err := c.client.Do(httpReq)if err != nil {@@ -222,3 +336,35 @@ func (c *QuickstartClient) ListModels(_ context.Context) ([]ModelInfo, error) {},}, nil}++func (c *QuickstartClient) syncServerState(result quickstartResponse) {+ if c == nil || c.onStateSync == nil {+ return+ }+ state := QuickstartServerState{+ CreditsRemaining: result.CreditsRemaining,+ CreditsTotal: result.CreditsTotal,+ }+ if rawExpiry := strings.TrimSpace(result.QuickstartTokenExpiresAt); rawExpiry != "" {+ if parsed, err := time.Parse(time.RFC3339, rawExpiry); err == nil {+ state.TokenExpiresAt = &parsed+ }+ }+ c.onStateSync(state)+}++func (c *QuickstartClient) invalidateToken() {+ if c == nil || c.onTokenInvalid == nil {+ return+ }+ c.onTokenInvalid()+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ return trimmed+ }+ }+ return ""+}diff --git a/internal/ai/providers/quickstart_test.go b/internal/ai/providers/quickstart_test.goindex 2e01949f81..6f5bbc13bb 100644--- a/internal/ai/providers/quickstart_test.go+++ b/internal/ai/providers/quickstart_test.go@@ -6,6 +6,7 @@ import ("net/http""net/http/httptest""testing"+ "time")func TestQuickstartProxyURL_Default(t *testing.T) {@@ -50,3 +51,106 @@ func TestQuickstartClientChat_UsesOverrideProxyURL(t *testing.T) {t.Fatalf("content=%q want hello", resp.Content)}}++func TestQuickstartClientWithToken_UsesBearerAuthAndSyncsServerState(t *testing.T) {+ var seenAuthorization string+ var seenLicenseID string+ var synced QuickstartServerState+ var syncCalls int++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var req quickstartRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ t.Fatalf("decode request: %v", err)+ }+ seenAuthorization = r.Header.Get("Authorization")+ seenLicenseID = req.LicenseID+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(quickstartResponse{+ Content: "hello",+ Model: quickstartModel,+ StopReason: "end_turn",+ CreditsRemaining: 16,+ CreditsTotal: 25,+ QuickstartTokenExpiresAt: "2026-04-02T12:00:00Z",+ }); 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) {+ synced = state+ syncCalls+++ }, nil)+ resp, err := client.Chat(context.Background(), ChatRequest{+ Messages: []Message{{Role: "user", Content: "Hi"}},+ })+ if err != nil {+ t.Fatalf("Chat(): %v", err)+ }+ if seenAuthorization != "Bearer qst_live_test" {+ t.Fatalf("Authorization=%q want Bearer qst_live_test", seenAuthorization)+ }+ if seenLicenseID != "" {+ t.Fatalf("license_id=%q want empty for bearer-token quickstart", seenLicenseID)+ }+ if resp.Content != "hello" {+ t.Fatalf("content=%q want hello", resp.Content)+ }+ 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.TokenExpiresAt == nil {+ t.Fatal("expected token expiry sync")+ }+ if got := synced.TokenExpiresAt.UTC().Format(time.RFC3339); got != "2026-04-02T12:00:00Z" {+ t.Fatalf("TokenExpiresAt=%q want 2026-04-02T12:00:00Z", got)+ }+}++func TestQuickstartClientWithToken_ExhaustionSyncsStateAndReturnsTypedError(t *testing.T) {+ var synced QuickstartServerState+ var syncCalls int++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusPaymentRequired)+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(quickstartResponse{+ Error: "credits exhausted",+ Code: "quickstart_credits_exhausted",+ CreditsRemaining: 0,+ CreditsTotal: 25,+ }); 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) {+ synced = state+ syncCalls+++ }, nil)+ _, err := client.Chat(context.Background(), ChatRequest{+ Messages: []Message{{Role: "user", Content: "Hi"}},+ })+ if err == nil {+ t.Fatal("expected quickstart exhaustion error")+ }+ if !IsQuickstartCreditsExhausted(err) {+ t.Fatalf("expected typed quickstart exhaustion, got %v", err)+ }+ 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)+ }+}diff --git a/internal/ai/quickstart.go b/internal/ai/quickstart.goindex 69cf0e9e26..55e8f614f7 100644--- a/internal/ai/quickstart.go+++ b/internal/ai/quickstart.go@@ -1,179 +1,444 @@package aiimport (+ "context"+ "errors""fmt"+ "net/http"+ "os"+ "strings""sync"+ "time"+ "github.com/google/uuid""github.com/rcourtman/pulse-go-rewrite/internal/ai/providers""github.com/rcourtman/pulse-go-rewrite/internal/config"pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing""github.com/rs/zerolog/log")-// QuickstartCreditManager provides credit checking and consumption for quickstart-// patrol runs. It is injected into the PatrolService and AI Service by the router.+const (+ quickstartBootstrapUseCase = "patrol"+ quickstartBootstrapRefreshWindow = 5 * time.Minute+ quickstartProviderUnavailableText = "Quickstart credits require internet access. Connect your API key for offline AI Patrol."+)++// QuickstartCreditManager owns the persisted quickstart bootstrap state used by+// Patrol when no BYOK provider is configured. Cached local state is never+// authoritative for entitlement; it only memoizes the last server snapshot.type QuickstartCreditManager interface {- // HasCredits returns true if quickstart credits are available (granted and not exhausted).+ EnsureBootstrap(ctx context.Context) errorHasCredits() bool- // CreditsRemaining returns the number of unused credits (0 if not granted).CreditsRemaining() int- // ConsumeCredit decrements one credit after a successful patrol run.- // Returns false if no credits remain.- ConsumeCredit() error- // HasBYOK returns true if the user has at least one provider with their own API key.+ CreditsTotal() intHasBYOK() bool- // GetProvider returns a quickstart Provider for making LLM calls through the hosted proxy.- // Returns nil if credits are exhausted.GetProvider() providers.Provider- // GrantCredits ensures credits are granted (idempotent). Called on first AI enable.- GrantCredits() error}-// FileQuickstartCreditManager implements QuickstartCreditManager backed by FileBillingStore.-type FileQuickstartCreditManager struct {- mu sync.Mutex- billingStore *config.FileBillingStore- orgID string- orgResolver func() string- aiConfig func() *config.AIConfig // Getter for current AI config (for BYOK check)- licenseID string // Workspace identifier for the proxy+type quickstartBootstrapClient interface {+ BootstrapQuickstart(ctx context.Context, bearerToken string, req pkglicensing.QuickstartBootstrapRequest) (*pkglicensing.QuickstartBootstrapResponse, error)}-// NewFileQuickstartCreditManager creates a credit manager backed by the billing store.-func NewFileQuickstartCreditManager(- billingStore *config.FileBillingStore,+// PersistentQuickstartCreditManager persists the server-issued quickstart token+// and the latest server-reported inventory in quickstart.enc.+type PersistentQuickstartCreditManager struct {+ mu sync.RWMutex+ orgID string+ persistence *config.ConfigPersistence+ aiConfig func() *config.AIConfig+ client quickstartBootstrapClient+ now func() time.Time+ hostname func() (string, error)+ newID func() string+ state *config.QuickstartState+}++// NewPersistentQuickstartCreditManager creates a server-authoritative+// quickstart manager backed by quickstart.enc.+func NewPersistentQuickstartCreditManager(+ persistence *config.ConfigPersistence,orgID string,aiConfigGetter func() *config.AIConfig,- licenseID string,-) *FileQuickstartCreditManager {- return NewFileQuickstartCreditManagerWithOrgResolver(billingStore, orgID, nil, aiConfigGetter, licenseID)+) *PersistentQuickstartCreditManager {+ return NewPersistentQuickstartCreditManagerWithClient(+ persistence,+ orgID,+ aiConfigGetter,+ pkglicensing.NewLicenseServerClient(""),+ )}-// NewFileQuickstartCreditManagerWithOrgResolver creates a credit manager that-// can resolve the effective billing org dynamically for each read/write.-func NewFileQuickstartCreditManagerWithOrgResolver(- billingStore *config.FileBillingStore,+// NewPersistentQuickstartCreditManagerWithClient exists for unit tests.+func NewPersistentQuickstartCreditManagerWithClient(+ persistence *config.ConfigPersistence,orgID string,- orgResolver func() string,aiConfigGetter func() *config.AIConfig,- licenseID string,-) *FileQuickstartCreditManager {- return &FileQuickstartCreditManager{- billingStore: billingStore,- orgID: orgID,- orgResolver: orgResolver,- aiConfig: aiConfigGetter,- licenseID: licenseID,+ client quickstartBootstrapClient,+) *PersistentQuickstartCreditManager {+ if aiConfigGetter == nil {+ aiConfigGetter = func() *config.AIConfig { return nil }+ }+ if client == nil {+ client = pkglicensing.NewLicenseServerClient("")+ }+ return &PersistentQuickstartCreditManager{+ orgID: strings.TrimSpace(orgID),+ persistence: persistence,+ aiConfig: aiConfigGetter,+ client: client,+ now: func() time.Time { return time.Now().UTC() },+ hostname: os.Hostname,+ newID: uuid.NewString,}}-func (m *FileQuickstartCreditManager) effectiveOrgID() string {+func (m *PersistentQuickstartCreditManager) EnsureBootstrap(ctx context.Context) error {if m == nil {- return ""+ return fmt.Errorf("quickstart: manager unavailable")}- if m.orgResolver != nil {- if resolved := m.orgResolver(); resolved != "" {- return resolved- }+ if ctx == nil {+ ctx = context.Background()}- return m.orgID-}-func (m *FileQuickstartCreditManager) getBillingState() *pkglicensing.BillingState {- if m.billingStore == nil {+ m.mu.Lock()+ defer m.mu.Unlock()++ state, err := m.loadStateLocked()+ if err != nil {+ return err+ }+ if !m.bootstrapNeededLocked(state, m.now()) {return nil}- state, err := m.billingStore.GetBillingState(m.effectiveOrgID())++ bearerToken, req, err := m.bootstrapRequestLocked(state)if err != nil {- log.Warn().Err(err).Msg("Quickstart: failed to read billing state")- return nil+ return err+ }++ resp, err := m.client.BootstrapQuickstart(ctx, bearerToken, req)+ if err != nil {+ if quickstartBootstrapCreditsExhausted(err) {+ state.QuickstartCreditsRemaining = 0+ nowUnix := m.now().Unix()+ state.LastSyncedAt = &nowUnix+ if persistErr := m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state)); persistErr != nil {+ log.Warn().Err(persistErr).Str("orgID", m.orgID).Msg("Quickstart: failed to persist exhausted bootstrap state")+ }+ }+ return err}- return state++ m.applyBootstrapLocked(state, resp)+ return m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state))}-func (m *FileQuickstartCreditManager) HasCredits() bool {- state := m.getBillingState()+func (m *PersistentQuickstartCreditManager) HasCredits() bool {+ state := m.stateSnapshot()+ return state != nil && state.QuickstartCreditsRemaining > 0+}++func (m *PersistentQuickstartCreditManager) CreditsRemaining() int {+ state := m.stateSnapshot()if state == nil {- return false+ return 0}- return state.HasQuickstartCredits()+ return state.QuickstartCreditsRemaining}-func (m *FileQuickstartCreditManager) CreditsRemaining() int {- state := m.getBillingState()+func (m *PersistentQuickstartCreditManager) CreditsTotal() int {+ state := m.stateSnapshot()if state == nil {return 0}- return state.QuickstartCreditsRemaining()+ return state.QuickstartCreditsTotal+}++func (m *PersistentQuickstartCreditManager) HasBYOK() bool {+ if m == nil || m.aiConfig == nil {+ return false+ }+ cfg := m.aiConfig()+ if cfg == nil {+ return false+ }+ return len(cfg.GetConfiguredProviders()) > 0}-func (m *FileQuickstartCreditManager) ConsumeCredit() error {+func (m *PersistentQuickstartCreditManager) GetProvider() providers.Provider {+ if m == nil {+ return nil+ }+m.mu.Lock()defer m.mu.Unlock()- effectiveOrgID := m.effectiveOrgID()- state, err := m.billingStore.GetBillingState(effectiveOrgID)+ state, err := m.loadStateLocked()if err != nil {- return fmt.Errorf("quickstart: read billing state: %w", err)+ log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to load cached quickstart state")+ return nil+ }+ if state == nil || state.QuickstartCreditsRemaining <= 0 {+ return nil+ }+ if strings.TrimSpace(state.QuickstartToken) == "" || state.TokenExpired(m.now()) {+ return nil}++ token := state.QuickstartToken+ return providers.NewQuickstartClientWithToken(+ token,+ m.syncServerState,+ m.invalidateToken,+ )+}++func (m *PersistentQuickstartCreditManager) stateSnapshot() *config.QuickstartState {+ if m == nil {+ return nil+ }++ m.mu.Lock()+ defer m.mu.Unlock()++ state, err := m.loadStateLocked()+ if err != nil {+ log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to read cached state")+ return &config.QuickstartState{}+ }+ return config.NormalizeQuickstartState(state)+}++func (m *PersistentQuickstartCreditManager) loadStateLocked() (*config.QuickstartState, error) {+ if m.state != nil {+ return m.state, nil+ }+ if m.persistence == nil {+ m.state = &config.QuickstartState{}+ return m.state, fmt.Errorf("quickstart: persistence unavailable")+ }+ state, err := m.persistence.LoadQuickstartState()+ if err != nil {+ return nil, fmt.Errorf("quickstart: load quickstart state: %w", err)+ }+ m.state = config.NormalizeQuickstartState(state)+ return m.state, nil+}++func (m *PersistentQuickstartCreditManager) bootstrapNeededLocked(state *config.QuickstartState, now time.Time) bool {if state == nil {- return fmt.Errorf("quickstart: no billing state")+ return true}+ if strings.TrimSpace(state.QuickstartToken) == "" {+ return true+ }+ if state.TokenExpired(now) {+ return true+ }+ if state.LastSyncedAt == nil || *state.LastSyncedAt <= 0 {+ return true+ }+ return now.Unix()-*state.LastSyncedAt >= int64(quickstartBootstrapRefreshWindow/time.Second)+}- if !state.ConsumeQuickstartCredit() {- return fmt.Errorf("quickstart: no credits remaining")+func (m *PersistentQuickstartCreditManager) bootstrapRequestLocked(state *config.QuickstartState) (string, pkglicensing.QuickstartBootstrapRequest, error) {+ if state == nil {+ return "", pkglicensing.QuickstartBootstrapRequest{}, fmt.Errorf("quickstart: missing state")+ }++ instanceName := ""+ if hostname, err := m.hostname(); err == nil {+ instanceName = strings.TrimSpace(hostname)+ }++ req := pkglicensing.QuickstartBootstrapRequest{+ InstanceName: instanceName,+ UseCase: quickstartBootstrapUseCase,}- if err := m.billingStore.SaveBillingState(effectiveOrgID, state); err != nil {- return fmt.Errorf("quickstart: save billing state: %w", err)+ if m.persistence == nil {+ return "", req, fmt.Errorf("quickstart: persistence unavailable")}- remaining := state.QuickstartCreditsRemaining()- log.Info().- Int("used", state.QuickstartCreditsUsed).- Int("remaining", remaining).- Msg("Quickstart: consumed one patrol credit")+ licensePersistence, err := pkglicensing.NewPersistence(m.persistence.GetConfigDir())+ if err != nil {+ return "", req, fmt.Errorf("quickstart: load license persistence: %w", err)+ }+ activationState, err := licensePersistence.LoadActivationState()+ if err != nil {+ return "", req, fmt.Errorf("quickstart: load activation state: %w", err)+ }- return nil+ if activationState != nil && strings.TrimSpace(activationState.InstallationToken) != "" {+ req.InstanceFingerprint = strings.TrimSpace(activationState.InstanceFingerprint)+ return strings.TrimSpace(activationState.InstallationToken), req, nil+ }++ if strings.TrimSpace(state.ClientInstallationID) == "" {+ state.ClientInstallationID = m.newID()+ if err := m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state)); err != nil {+ return "", req, fmt.Errorf("quickstart: persist client installation id: %w", err)+ }+ }++ req.ClientInstallationID = state.ClientInstallationID+ req.InstanceFingerprint = state.ClientInstallationID+ return "", req, nil}-func (m *FileQuickstartCreditManager) HasBYOK() bool {- cfg := m.aiConfig()- if cfg == nil {- return false+func (m *PersistentQuickstartCreditManager) applyBootstrapLocked(state *config.QuickstartState, resp *pkglicensing.QuickstartBootstrapResponse) {+ if state == nil || resp == nil {+ return}- return len(cfg.GetConfiguredProviders()) > 0++ state.QuickstartToken = strings.TrimSpace(resp.QuickstartToken)+ state.QuickstartCreditsRemaining = max(0, resp.CreditsRemaining)+ state.QuickstartCreditsTotal = max(0, resp.CreditsTotal)+ if expiry := parseQuickstartRFC3339(resp.QuickstartTokenExpiresAt); expiry != nil {+ state.QuickstartTokenExpiresAt = expiry+ } else {+ state.QuickstartTokenExpiresAt = nil+ }+ nowUnix := m.now().Unix()+ state.LastSyncedAt = &nowUnix}-func (m *FileQuickstartCreditManager) GetProvider() providers.Provider {- if !m.HasCredits() {- return nil+func (m *PersistentQuickstartCreditManager) syncServerState(serverState providers.QuickstartServerState) {+ if m == nil {+ return+ }++ m.mu.Lock()+ defer m.mu.Unlock()++ state, err := m.loadStateLocked()+ if err != nil {+ log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to load cached state for sync")+ return+ }++ state.QuickstartCreditsRemaining = max(0, serverState.CreditsRemaining)+ state.QuickstartCreditsTotal = max(0, serverState.CreditsTotal)+ if serverState.TokenExpiresAt != nil {+ expiryUnix := serverState.TokenExpiresAt.UTC().Unix()+ state.QuickstartTokenExpiresAt = &expiryUnix+ }+ nowUnix := m.now().Unix()+ state.LastSyncedAt = &nowUnix++ if m.persistence == nil {+ return+ }+ if err := m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state)); err != nil {+ log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to persist synced server state")}- return providers.NewQuickstartClient(m.licenseID)}-func (m *FileQuickstartCreditManager) GrantCredits() error {+func (m *PersistentQuickstartCreditManager) invalidateToken() {+ if m == nil {+ return+ }+m.mu.Lock()defer m.mu.Unlock()- effectiveOrgID := m.effectiveOrgID()- state, err := m.billingStore.GetBillingState(effectiveOrgID)+ state, err := m.loadStateLocked()if err != nil {- return fmt.Errorf("quickstart: read billing state: %w", err)+ log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to load cached state for token invalidation")+ return}- if state == nil {- state = pkglicensing.DefaultBillingState()++ state.QuickstartToken = ""+ state.QuickstartTokenExpiresAt = nil+ nowUnix := m.now().Unix()+ state.LastSyncedAt = &nowUnix++ if m.persistence == nil {+ return+ }+ if err := m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state)); err != nil {+ log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to persist invalidated token state")}+}- if !state.GrantQuickstartCredits() {- // Already granted — idempotent.- return nil+func quickstartBlockedReasonFromError(err error) string {+ switch {+ case err == nil:+ return ""+ case providers.IsQuickstartCreditsExhausted(err), quickstartBootstrapCreditsExhausted(err):+ return patrolQuickstartCreditsExhaustedReason+ case providers.IsQuickstartUnavailable(err), quickstartBootstrapUnavailable(err):+ return patrolQuickstartUnavailableReason+ default:+ return quickstartProviderUnavailableText}+}++// QuickstartBlockedReasonForError exposes quickstart block classification to+// adjacent runtime/API layers without duplicating the mapping logic.+func QuickstartBlockedReasonForError(err error) string {+ return quickstartBlockedReasonFromError(err)+}- if err := m.billingStore.SaveBillingState(effectiveOrgID, state); err != nil {- return fmt.Errorf("quickstart: save billing state: %w", err)+// QuickstartUnavailableReason returns the canonical Patrol quickstart+// availability message shown when the server-authoritative bootstrap path+// cannot be reached.+func QuickstartUnavailableReason() string {+ return patrolQuickstartUnavailableReason+}++func quickstartBootstrapCreditsExhausted(err error) bool {+ var serverErr *pkglicensing.LicenseServerError+ if !errors.As(err, &serverErr) {+ return false+ }+ if serverErr.StatusCode == http.StatusPaymentRequired {+ return true}+ return strings.EqualFold(strings.TrimSpace(serverErr.Code), "quickstart_credits_exhausted")+}++func quickstartBootstrapUnavailable(err error) bool {+ var serverErr *pkglicensing.LicenseServerError+ if errors.As(err, &serverErr) {+ switch serverErr.StatusCode {+ case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:+ return true+ }+ return serverErr.Retryable+ }++ lower := strings.ToLower(strings.TrimSpace(err.Error()))+ switch {+ case strings.Contains(lower, "connection refused"),+ strings.Contains(lower, "no such host"),+ strings.Contains(lower, "dial tcp"),+ strings.Contains(lower, "i/o timeout"),+ strings.Contains(lower, "context deadline exceeded"),+ strings.Contains(lower, "network is unreachable"),+ strings.Contains(lower, "network unreachable"):+ return true+ default:+ return false+ }+}- log.Info().Msg("Quickstart: granted 25 free patrol credits to workspace")- return nil+func parseQuickstartRFC3339(raw string) *int64 {+ raw = strings.TrimSpace(raw)+ if raw == "" {+ return nil+ }+ parsed, err := time.Parse(time.RFC3339, raw)+ if err != nil {+ return nil+ }+ unix := parsed.UTC().Unix()+ return &unix+}++func max(a, b int) int {+ if a > b {+ return a+ }+ return b}diff --git a/internal/ai/quickstart_test.go b/internal/ai/quickstart_test.goindex c0c9f065e8..88b8a2745f 100644--- a/internal/ai/quickstart_test.go+++ b/internal/ai/quickstart_test.go@@ -1,52 +1,164 @@package aiimport (+ "context""testing"+ "time""github.com/rcourtman/pulse-go-rewrite/internal/config"pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing")-func TestFileQuickstartCreditManager_OrgResolverUsesEffectiveBillingOrg(t *testing.T) {- baseDir := t.TempDir()- billingStore := config.NewFileBillingStore(baseDir)+type stubQuickstartBootstrapClient struct {+ calls int+ bearer string+ req pkglicensing.QuickstartBootstrapRequest+ resp *pkglicensing.QuickstartBootstrapResponse+ err error+}- state := pkglicensing.DefaultBillingState()- state.GrantQuickstartCredits()- if err := billingStore.SaveBillingState("default", state); err != nil {- t.Fatalf("SaveBillingState(default): %v", err)+func (s *stubQuickstartBootstrapClient) BootstrapQuickstart(ctx context.Context, bearerToken string, req pkglicensing.QuickstartBootstrapRequest) (*pkglicensing.QuickstartBootstrapResponse, error) {+ s.calls+++ s.bearer = bearerToken+ s.req = req+ if s.err != nil {+ return nil, s.err}+ return s.resp, nil+}- mgr := NewFileQuickstartCreditManagerWithOrgResolver(- billingStore,- "t-tenant",- func() string { return "default" },- func() *config.AIConfig { return &config.AIConfig{Enabled: true} },- "t-tenant",- )+func TestPersistentQuickstartCreditManager_EnsureBootstrapUsesActivationIdentity(t *testing.T) {+ dir := t.TempDir()+ persistence := config.NewConfigPersistence(dir)- if !mgr.HasCredits() {- t.Fatal("expected quickstart credits through resolved billing org")+ licensePersistence, err := pkglicensing.NewPersistence(persistence.GetConfigDir())+ if err != nil {+ t.Fatalf("NewPersistence(): %v", err)}- if got := mgr.CreditsRemaining(); got != pkglicensing.QuickstartCreditsTotal {- t.Fatalf("CreditsRemaining() = %d, want %d", got, pkglicensing.QuickstartCreditsTotal)+ if err := licensePersistence.SaveActivationState(&pkglicensing.ActivationState{+ InstallationID: "inst_live_test",+ InstallationToken: "pit_live_test",+ InstanceFingerprint: "fp-live-test",+ }); err != nil {+ t.Fatalf("SaveActivationState(): %v", err)}- if err := mgr.ConsumeCredit(); err != nil {- t.Fatalf("ConsumeCredit(): %v", err)++ client := &stubQuickstartBootstrapClient{+ resp: &pkglicensing.QuickstartBootstrapResponse{+ QuickstartToken: "qst_live_activation",+ QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),+ CreditsRemaining: 19,+ CreditsTotal: 25,+ },}+ mgr := NewPersistentQuickstartCreditManagerWithClient(persistence, "default", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)+ mgr.hostname = func() (string, error) { return "pulse-test", nil }- defaultState, err := billingStore.GetBillingState("default")- if err != nil {- t.Fatalf("GetBillingState(default): %v", err)+ if err := mgr.EnsureBootstrap(context.Background()); err != nil {+ t.Fatalf("EnsureBootstrap(): %v", err)+ }+ if client.calls != 1 {+ t.Fatalf("BootstrapQuickstart calls = %d, want 1", client.calls)+ }+ if client.bearer != "pit_live_test" {+ t.Fatalf("bearer = %q, want pit_live_test", client.bearer)+ }+ if client.req.ClientInstallationID != "" {+ t.Fatalf("ClientInstallationID = %q, want empty", client.req.ClientInstallationID)+ }+ if client.req.InstanceFingerprint != "fp-live-test" {+ t.Fatalf("InstanceFingerprint = %q, want fp-live-test", client.req.InstanceFingerprint)}- if defaultState == nil || defaultState.QuickstartCreditsUsed != 1 {- t.Fatalf("expected resolved default billing state to consume one credit, got %#v", defaultState)+ if mgr.CreditsRemaining() != 19 {+ t.Fatalf("CreditsRemaining() = %d, want 19", mgr.CreditsRemaining())+ }+ if mgr.CreditsTotal() != 25 {+ t.Fatalf("CreditsTotal() = %d, want 25", mgr.CreditsTotal())+ }+ if mgr.GetProvider() == nil {+ t.Fatal("expected quickstart provider after activation bootstrap")+ }+}++func TestPersistentQuickstartCreditManager_EnsureBootstrapPersistsCommunityInstallationID(t *testing.T) {+ dir := t.TempDir()+ persistence := config.NewConfigPersistence(dir)++ client := &stubQuickstartBootstrapClient{+ resp: &pkglicensing.QuickstartBootstrapResponse{+ QuickstartToken: "qst_live_community",+ QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),+ CreditsRemaining: 17,+ CreditsTotal: 25,+ },+ }+ mgr := NewPersistentQuickstartCreditManagerWithClient(persistence, "default", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)+ mgr.hostname = func() (string, error) { return "pulse-community", nil }+ mgr.newID = func() string { return "community-install-1" }++ if err := mgr.EnsureBootstrap(context.Background()); err != nil {+ t.Fatalf("EnsureBootstrap(): %v", err)}- tenantState, err := billingStore.GetBillingState("t-tenant")+ if client.calls != 1 {+ t.Fatalf("BootstrapQuickstart calls = %d, want 1", client.calls)+ }+ if client.bearer != "" {+ t.Fatalf("bearer = %q, want empty", client.bearer)+ }+ if client.req.ClientInstallationID != "community-install-1" {+ t.Fatalf("ClientInstallationID = %q, want community-install-1", client.req.ClientInstallationID)+ }+ if client.req.InstanceFingerprint != "community-install-1" {+ t.Fatalf("InstanceFingerprint = %q, want community-install-1", client.req.InstanceFingerprint)+ }++ loaded, err := persistence.LoadQuickstartState()if err != nil {- t.Fatalf("GetBillingState(t-tenant): %v", err)+ t.Fatalf("LoadQuickstartState(): %v", err)+ }+ if loaded.ClientInstallationID != "community-install-1" {+ t.Fatalf("persisted ClientInstallationID = %q, want community-install-1", loaded.ClientInstallationID)+ }+ if loaded.QuickstartToken != "qst_live_community" {+ t.Fatalf("persisted QuickstartToken = %q, want qst_live_community", loaded.QuickstartToken)+ }+}++func TestPersistentQuickstartCreditManager_LoadsPersistedTokenWithoutBootstrap(t *testing.T) {+ dir := t.TempDir()+ persistence := config.NewConfigPersistence(dir)+ expiresAt := time.Now().Add(30 * time.Minute).UTC().Unix()+ lastSyncedAt := time.Now().UTC().Unix()+ if err := persistence.SaveQuickstartState(config.QuickstartState{+ ClientInstallationID: "community-install-1",+ QuickstartToken: "qst_live_cached",+ QuickstartTokenExpiresAt: &expiresAt,+ QuickstartCreditsRemaining: 11,+ QuickstartCreditsTotal: 25,+ LastSyncedAt: &lastSyncedAt,+ }); err != nil {+ t.Fatalf("SaveQuickstartState(): %v", err)+ }++ client := &stubQuickstartBootstrapClient{+ resp: &pkglicensing.QuickstartBootstrapResponse{+ QuickstartToken: "qst_should_not_be_used",+ CreditsRemaining: 1,+ CreditsTotal: 25,+ },+ }+ mgr := NewPersistentQuickstartCreditManagerWithClient(persistence, "default", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)++ if err := mgr.EnsureBootstrap(context.Background()); err != nil {+ t.Fatalf("EnsureBootstrap(): %v", err)+ }+ if client.calls != 0 {+ t.Fatalf("BootstrapQuickstart calls = %d, want 0 for fresh cached state", client.calls)+ }+ if mgr.CreditsRemaining() != 11 {+ t.Fatalf("CreditsRemaining() = %d, want 11", mgr.CreditsRemaining())}- if tenantState != nil {- t.Fatalf("expected no tenant shadow billing state, got %#v", tenantState)+ if mgr.GetProvider() == nil {+ t.Fatal("expected provider from cached quickstart token")}}diff --git a/internal/ai/service.go b/internal/ai/service.goindex d058c4628c..e8719538f3 100644--- a/internal/ai/service.go+++ b/internal/ai/service.go@@ -5,6 +5,7 @@ import ("crypto/sha256""encoding/hex""encoding/json"+ "errors""fmt""io""net"@@ -215,6 +216,8 @@ type Service struct {quickstartCredits QuickstartCreditManager// usingQuickstart tracks whether the current provider was set via quickstart creditsusingQuickstart bool+ // quickstartBlockedReason captures why Patrol-only quickstart is currently unavailable.+ quickstartBlockedReason string}type executionLimits struct {@@ -617,6 +620,7 @@ func (s *Service) SetChatService(cs ChatServiceProvider) {s.mu.Lock()defer s.mu.Unlock()s.chatService = cs+ s.configurePatrolQuickstartProviderFactoryLocked()}// GetChatService returns the chat service for investigation orchestrator@@ -1478,11 +1482,16 @@ func (s *Service) LoadConfig() error {s.cfg = cfgs.usingQuickstart = false+ s.quickstartBlockedReason = ""// Don't initialize provider if AI is not enabled or not configuredif cfg == nil || !cfg.Enabled || !cfg.IsConfigured() {- // Check if quickstart credits can fill the gap (enabled but no BYOK)- if cfg != nil && cfg.Enabled && s.quickstartCredits != nil && s.quickstartCredits.HasCredits() {+ // Check if quickstart can fill the Patrol gap (enabled but no BYOK).+ if cfg != nil && cfg.Enabled && s.quickstartCredits != nil {+ if err := s.quickstartCredits.EnsureBootstrap(context.Background()); err != nil {+ s.quickstartBlockedReason = quickstartBlockedReasonFromError(err)+ log.Warn().Err(err).Str("orgID", s.orgID).Msg("Quickstart bootstrap failed during AI service load")+ }qp := s.quickstartCredits.GetProvider()if qp != nil {s.provider = qp@@ -1497,6 +1506,11 @@ func (s *Service) LoadConfig() error {Msg("AI service initialized via quickstart credits (no BYOK)")return nil}+ if s.quickstartBlockedReason == "" && !s.quickstartCredits.HasCredits() {+ s.quickstartBlockedReason = patrolQuickstartCreditsExhaustedReason+ } else if s.quickstartBlockedReason == "" {+ s.quickstartBlockedReason = patrolQuickstartUnavailableReason+ }}s.provider = nilreturn nil@@ -1613,7 +1627,11 @@ func (s *Service) IsEnabled() bool {return true}// Also enabled if quickstart credits are available (even without BYOK)- if s.cfg != nil && s.cfg.Enabled && s.quickstartCredits != nil && s.quickstartCredits.HasCredits() {+ if s.cfg != nil &&+ s.cfg.Enabled &&+ s.quickstartCredits != nil &&+ s.quickstartCredits.HasCredits() &&+ strings.TrimSpace(s.quickstartBlockedReason) == "" {return true}return false@@ -1626,6 +1644,13 @@ func (s *Service) IsUsingQuickstart() bool {return s.usingQuickstart}+// QuickstartBlockedReason returns the current Patrol quickstart blocking reason.+func (s *Service) QuickstartBlockedReason() string {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return strings.TrimSpace(s.quickstartBlockedReason)+}+// SetQuickstartCredits sets the quickstart credit manager on both the// service and its patrol sub-service so credit checks work at runtime.func (s *Service) SetQuickstartCredits(mgr QuickstartCreditManager) {@@ -1635,6 +1660,7 @@ func (s *Service) SetQuickstartCredits(mgr QuickstartCreditManager) {if s.patrolService != nil {s.patrolService.SetQuickstartCredits(mgr)}+ s.configurePatrolQuickstartProviderFactoryLocked()}// GetQuickstartCredits returns the quickstart credit manager.@@ -1644,6 +1670,72 @@ func (s *Service) GetQuickstartCredits() QuickstartCreditManager {return s.quickstartCredits}+type patrolProviderFactorySetter interface {+ SetPatrolProviderFactory(func(modelStr string) (providers.StreamingProvider, error))+}++func (s *Service) configurePatrolQuickstartProviderFactoryLocked() {+ setter, ok := s.chatService.(patrolProviderFactorySetter)+ if !ok {+ return+ }+ setter.SetPatrolProviderFactory(s.createPatrolProviderForModel)+}++func (s *Service) createPatrolProviderForModel(modelStr string) (providers.StreamingProvider, error) {+ s.mu.RLock()+ cfg := s.cfg+ quickstartMgr := s.quickstartCredits+ defaultProvider := s.provider+ s.mu.RUnlock()++ providerName, _ := config.ParseModelString(modelStr)+ if providerName != config.AIProviderQuickstart {+ provider, err := providers.NewForModel(cfg, modelStr)+ if err != nil {+ if streaming, ok := defaultProvider.(providers.StreamingProvider); ok {+ return streaming, nil+ }+ return nil, err+ }+ streaming, ok := provider.(providers.StreamingProvider)+ if !ok {+ return nil, fmt.Errorf("patrol provider %q does not support streaming", provider.Name())+ }+ return streaming, nil+ }++ if quickstartMgr == nil {+ return nil, fmt.Errorf("quickstart is not configured")+ }+ if err := quickstartMgr.EnsureBootstrap(context.Background()); err != nil {+ s.mu.Lock()+ s.quickstartBlockedReason = quickstartBlockedReasonFromError(err)+ s.mu.Unlock()+ return nil, err+ }+ provider := quickstartMgr.GetProvider()+ if provider == nil {+ reason := patrolQuickstartUnavailableReason+ if !quickstartMgr.HasCredits() {+ reason = patrolQuickstartCreditsExhaustedReason+ }+ s.mu.Lock()+ s.quickstartBlockedReason = reason+ s.mu.Unlock()+ return nil, errors.New(reason)+ }+ streaming, ok := provider.(providers.StreamingProvider)+ if !ok {+ return nil, fmt.Errorf("quickstart provider does not support streaming")+ }++ s.mu.Lock()+ s.quickstartBlockedReason = ""+ s.mu.Unlock()+ return streaming, nil+}+// 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.diff --git a/internal/ai/service_quickstart_test.go b/internal/ai/service_quickstart_test.gonew file mode 100644index 0000000000..c1663b19f2--- /dev/null+++ b/internal/ai/service_quickstart_test.go@@ -0,0 +1,89 @@+package ai++import (+ "context"+ "net/http"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"+)++type stubServiceQuickstartManager struct {+ ensureErr error+ remaining int+ total int+ provider providers.Provider+ byok bool+}++func (m *stubServiceQuickstartManager) EnsureBootstrap(context.Context) error { return m.ensureErr }+func (m *stubServiceQuickstartManager) HasCredits() bool { return m.remaining > 0 }+func (m *stubServiceQuickstartManager) CreditsRemaining() int { return m.remaining }+func (m *stubServiceQuickstartManager) CreditsTotal() int {+ if m.total > 0 {+ return m.total+ }+ return pkglicensing.QuickstartCreditsTotal+}+func (m *stubServiceQuickstartManager) HasBYOK() bool { return m.byok }+func (m *stubServiceQuickstartManager) GetProvider() providers.Provider { return m.provider }++func TestServiceLoadConfig_PrefersBYOKProviderOverQuickstart(t *testing.T) {+ dir := t.TempDir()+ persistence := config.NewConfigPersistence(dir)+ cfg := config.NewDefaultAIConfig()+ cfg.Enabled = true+ cfg.Model = "ollama:llama3"+ cfg.OllamaBaseURL = "http://127.0.0.1:11434"+ if err := persistence.SaveAIConfig(*cfg); err != nil {+ t.Fatalf("SaveAIConfig(): %v", err)+ }++ svc := NewService(persistence, nil)+ svc.SetQuickstartCredits(&stubServiceQuickstartManager{+ ensureErr: &pkglicensing.LicenseServerError{StatusCode: http.StatusServiceUnavailable, Code: "temporarily_unavailable", Message: "down", Retryable: true},+ remaining: 25,+ total: 25,+ provider: providers.NewQuickstartClientWithToken("qst_live_test", nil, nil),+ })++ if err := svc.LoadConfig(); err != nil {+ t.Fatalf("LoadConfig(): %v", err)+ }+ if svc.IsUsingQuickstart() {+ t.Fatal("expected BYOK provider to win over quickstart")+ }+ if svc.QuickstartBlockedReason() != "" {+ t.Fatalf("QuickstartBlockedReason() = %q, want empty when BYOK is configured", svc.QuickstartBlockedReason())+ }+ if !svc.IsEnabled() {+ t.Fatal("expected BYOK AI service to remain enabled")+ }+}++func TestServiceLoadConfig_TracksQuickstartBootstrapFailure(t *testing.T) {+ dir := t.TempDir()+ persistence := config.NewConfigPersistence(dir)+ cfg := config.NewDefaultAIConfig()+ cfg.Enabled = true+ if err := persistence.SaveAIConfig(*cfg); err != nil {+ t.Fatalf("SaveAIConfig(): %v", err)+ }++ svc := NewService(persistence, nil)+ svc.SetQuickstartCredits(&stubServiceQuickstartManager{+ ensureErr: &pkglicensing.LicenseServerError{StatusCode: http.StatusServiceUnavailable, Code: "temporarily_unavailable", Message: "down", Retryable: true},+ })++ if err := svc.LoadConfig(); err != nil {+ t.Fatalf("LoadConfig(): %v", err)+ }+ if svc.QuickstartBlockedReason() != patrolQuickstartUnavailableReason {+ t.Fatalf("QuickstartBlockedReason() = %q, want %q", svc.QuickstartBlockedReason(), patrolQuickstartUnavailableReason)+ }+ if svc.IsEnabled() {+ t.Fatal("expected AI service to remain disabled when bootstrap failed and no BYOK exists")+ }+}diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex 4c2b72c379..c210225383 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -228,15 +228,13 @@ func NewAISettingsHandler(mtp *config.MultiTenantPersistence, mtm *monitoring.Mu// Wire quickstart credit manager before LoadConfig so the quickstart// provider path is available during initial configuration.if defaultPersistence != nil {- billingStore := config.NewFileBillingStore(defaultPersistence.DataDir())- qsMgr := ai.NewFileQuickstartCreditManager(- billingStore,+ qsMgr := ai.NewPersistentQuickstartCreditManager(+ defaultPersistence,"default",func() *config.AIConfig {cfg, _ := handler.loadAIConfigForPersistence(context.Background(), "default", defaultPersistence)return cfg},- "default",)defaultAIService.SetQuickstartCredits(qsMgr)if _, err := handler.loadAIConfigForPersistence(context.Background(), "default", defaultPersistence); err != nil {@@ -324,29 +322,13 @@ func (h *AISettingsHandler) GetAIService(ctx context.Context) *ai.Service {svc.SetAlertAnalyzerFactory(getCreateAlertAnalyzer())// Wire quickstart credit manager before LoadConfig so the quickstart// provider path is available during initial configuration.- // Use the base data dir (not tenant-scoped dir) because FileBillingStore- // internally resolves org paths: base/orgs/<org>/billing.json.- billingBaseDir := mtPersistence.BaseDataDir()- billingStore := config.NewFileBillingStore(billingBaseDir)- qsMgr := ai.NewFileQuickstartCreditManagerWithOrgResolver(- billingStore,+ qsMgr := ai.NewPersistentQuickstartCreditManager(+ persistence,orgID,- func() string {- if !h.hostedMode {- return orgID- }- _, effectiveOrgID, err := loadHostedEffectiveBillingState(billingStore, orgID)- if err != nil {- log.Warn().Str("orgID", orgID).Err(err).Msg("Failed to resolve hosted quickstart billing org fallback")- return orgID- }- return effectiveOrgID- },func() *config.AIConfig {cfg, _ := h.loadAIConfigForPersistence(context.Background(), orgID, persistence)return cfg},- orgID,)svc.SetQuickstartCredits(qsMgr)if _, err := h.loadAIConfigForPersistence(context.Background(), orgID, persistence); err != nil {@@ -2302,10 +2284,15 @@ func (h *AISettingsHandler) populateQuickstartFields(ctx context.Context, resp *if qsMgr == nil {return}- resp.QuickstartCreditsTotal = quickstartCreditsTotalFromLicensing+ if err := qsMgr.EnsureBootstrap(ctx); err != nil {+ log.Debug().Err(err).Msg("Quickstart bootstrap unavailable while populating AI settings")+ }+ resp.QuickstartCreditsTotal = qsMgr.CreditsTotal()remaining := qsMgr.CreditsRemaining()resp.QuickstartCreditsRemaining = remaining- resp.QuickstartCreditsUsed = quickstartCreditsTotalFromLicensing - remaining+ if resp.QuickstartCreditsTotal > remaining {+ resp.QuickstartCreditsUsed = resp.QuickstartCreditsTotal - remaining+ }resp.QuickstartCreditsAvailable = qsMgr.HasCredits()resp.UsingQuickstart = aiSvc.IsUsingQuickstart()}@@ -2525,8 +2512,8 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *httsettings.OpenAIBaseURL = strings.TrimSpace(*req.OpenAIBaseURL)}- // Track whether we need to grant quickstart credits (deferred until after all validation).- grantQuickstartCredits := false+ // Track whether we should opportunistically refresh quickstart state after validation.+ refreshQuickstartState := falseif req.Enabled != nil {// Only allow enabling if at least one provider is configured OR quickstart credits are availableif *req.Enabled {@@ -2535,20 +2522,18 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt// Check if quickstart credits can bridge the gapaiSvc := h.GetAIService(r.Context())hasQuickstart := false+ var bootstrapErr errorif aiSvc != nil {if qsMgr := aiSvc.GetQuickstartCredits(); qsMgr != nil {- hasQuickstart = qsMgr.HasCredits()- // First-time enable: grant credits to check availability.- // This is safe even if later validation fails — grants are- // idempotent and every workspace is entitled to 25 credits.- if !hasQuickstart {- if err := qsMgr.GrantCredits(); err == nil {- hasQuickstart = qsMgr.HasCredits()- }- }+ bootstrapErr = qsMgr.EnsureBootstrap(r.Context())+ hasQuickstart = qsMgr.HasCredits() && qsMgr.GetProvider() != nil}}if !hasQuickstart {+ if strings.TrimSpace(ai.QuickstartBlockedReasonForError(bootstrapErr)) == ai.QuickstartUnavailableReason() {+ http.Error(w, ai.QuickstartUnavailableReason(), http.StatusBadGateway)+ return+ }http.Error(w, "Please configure a provider (API key or Ollama URL) before enabling Pulse Assistant", http.StatusBadRequest)return}@@ -2561,9 +2546,9 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *httsettings.PatrolModel = quickstartModelStrsettings.ChatModel = quickstartModelStr} else {- // BYOK is configured — still grant quickstart credits (idempotent)- // so every workspace gets the 25 free runs.- grantQuickstartCredits = true+ // BYOK is configured — refresh quickstart state best-effort so the+ // Patrol status API can still report the current server snapshot.+ refreshQuickstartState = true}}settings.Enabled = *req.Enabled@@ -2694,12 +2679,12 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *httsettings.DiscoveryIntervalHours = 24}- // Grant quickstart credits now that all validation has passed (idempotent).- if grantQuickstartCredits {+ // Refresh quickstart bootstrap state now that validation has passed.+ if refreshQuickstartState {if aiSvc := h.GetAIService(r.Context()); aiSvc != nil {if qsMgr := aiSvc.GetQuickstartCredits(); qsMgr != nil {- if err := qsMgr.GrantCredits(); err != nil {- log.Warn().Err(err).Msg("Failed to grant quickstart credits")+ if err := qsMgr.EnsureBootstrap(r.Context()); err != nil {+ log.Warn().Err(err).Msg("Failed to refresh quickstart bootstrap state")}}}diff --git a/internal/api/ai_handlers_patrol_actions_additional_test.go b/internal/api/ai_handlers_patrol_actions_additional_test.goindex 21282bd453..5bb39e6ca6 100644--- a/internal/api/ai_handlers_patrol_actions_additional_test.go+++ b/internal/api/ai_handlers_patrol_actions_additional_test.go@@ -2,6 +2,7 @@ package apiimport ("bytes"+ "context""encoding/json""net/http""net/http/httptest"@@ -116,14 +117,29 @@ func addUnifiedRuntimeFinding(store *unified.UnifiedStore, id string, detectedAttype stubQuickstartCreditManager struct {remaining int+ total int+ provider providers.Provider}-func (m *stubQuickstartCreditManager) HasCredits() bool { return m.remaining > 0 }-func (m *stubQuickstartCreditManager) CreditsRemaining() int { return m.remaining }-func (m *stubQuickstartCreditManager) ConsumeCredit() error { return nil }-func (m *stubQuickstartCreditManager) HasBYOK() bool { return false }-func (m *stubQuickstartCreditManager) GetProvider() providers.Provider { return nil }-func (m *stubQuickstartCreditManager) GrantCredits() error { return nil }+func (m *stubQuickstartCreditManager) EnsureBootstrap(context.Context) error { return nil }+func (m *stubQuickstartCreditManager) HasCredits() bool { return m.remaining > 0 }+func (m *stubQuickstartCreditManager) CreditsRemaining() int { return m.remaining }+func (m *stubQuickstartCreditManager) CreditsTotal() int {+ if m.total > 0 {+ return m.total+ }+ return pkglicensing.QuickstartCreditsTotal+}+func (m *stubQuickstartCreditManager) HasBYOK() bool { return false }+func (m *stubQuickstartCreditManager) GetProvider() providers.Provider {+ if m.provider != nil {+ return m.provider+ }+ if m.remaining <= 0 {+ return nil+ }+ return providers.NewQuickstartClientWithToken("qst_live_test", nil, nil)+}func TestHandleGetPatrolStatus_IncludesQuickstartFields(t *testing.T) {handler, _, _, _ := setupAIHandlerWithPatrol(t)diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.goindex 48c95ee40a..2507869a14 100644--- a/internal/api/ai_handlers_test.go+++ b/internal/api/ai_handlers_test.go@@ -51,6 +51,31 @@ func saveEnabledTestAIConfig(t *testing.T, persistence *config.ConfigPersistencerequire.NoError(t, persistence.SaveAIConfig(*aiCfg))}+func useTestQuickstartBootstrapServer(t *testing.T, assertRequest func(*http.Request, map[string]any)) {+ t.Helper()++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ require.Equal(t, http.MethodPost, r.Method)+ require.Equal(t, "/v1/quickstart/bootstrap", r.URL.Path)++ var reqBody map[string]any+ require.NoError(t, json.NewDecoder(r.Body).Decode(&reqBody))+ if assertRequest != nil {+ assertRequest(r, reqBody)+ }++ w.Header().Set("Content-Type", "application/json")+ require.NoError(t, json.NewEncoder(w).Encode(map[string]any{+ "quickstart_token": "qst_live_handler_test",+ "quickstart_token_expires_at": time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),+ "credits_remaining": 25,+ "credits_total": 25,+ }))+ }))+ t.Cleanup(server.Close)+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)+}+func TestAISettingsHandler_GetAndUpdateSettings_RoundTrip(t *testing.T) {t.Parallel()@@ -201,6 +226,14 @@ func TestAISettingsResponse_UsesCanonicalEmptyCollections(t *testing.T) {func TestAISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart(t *testing.T) {t.Setenv("PULSE_HOSTED_MODE", "true")+ useTestQuickstartBootstrapServer(t, func(r *http.Request, reqBody map[string]any) {+ assert.Empty(t, strings.TrimSpace(r.Header.Get("Authorization")))+ clientInstallationID, _ := reqBody["client_installation_id"].(string)+ instanceFingerprint, _ := reqBody["instance_fingerprint"].(string)+ assert.NotEmpty(t, clientInstallationID)+ assert.Equal(t, clientInstallationID, instanceFingerprint)+ assert.Equal(t, "patrol", reqBody["use_case"])+ })tmp := t.TempDir()mtp := config.NewMultiTenantPersistence(tmp)@@ -231,6 +264,14 @@ func TestAISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart(t *testingfunc TestAISettingsHandler_GetHostedTenantSettings_InheritsDefaultHostedBillingState(t *testing.T) {t.Setenv("PULSE_HOSTED_MODE", "true")+ useTestQuickstartBootstrapServer(t, func(r *http.Request, reqBody map[string]any) {+ assert.Empty(t, strings.TrimSpace(r.Header.Get("Authorization")))+ clientInstallationID, _ := reqBody["client_installation_id"].(string)+ instanceFingerprint, _ := reqBody["instance_fingerprint"].(string)+ assert.NotEmpty(t, clientInstallationID)+ assert.Equal(t, clientInstallationID, instanceFingerprint)+ assert.Equal(t, "patrol", reqBody["use_case"])+ })tmp := t.TempDir()mtp := config.NewMultiTenantPersistence(tmp)@@ -260,6 +301,35 @@ func TestAISettingsHandler_GetHostedTenantSettings_InheritsDefaultHostedBillingSassert.True(t, persistence.HasAIConfig())}+func TestAISettingsHandler_UpdateSettings_QuickstartBootstrapBeforeEnable(t *testing.T) {+ tmp := t.TempDir()+ cfg := &config.Config{DataPath: tmp}+ persistence := config.NewConfigPersistence(tmp)+ handler := newTestAISettingsHandler(cfg, persistence, nil)++ quickstartMgr := &stubQuickstartCreditManager{+ remaining: 25,+ total: 25,+ }+ handler.defaultAIService.SetQuickstartCredits(quickstartMgr)++ body, _ := json.Marshal(AISettingsUpdateRequest{+ Enabled: ptr(true),+ })+ req := httptest.NewRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))+ rec := httptest.NewRecorder()+ handler.HandleUpdateAISettings(rec, req)++ require.Equal(t, http.StatusOK, rec.Code, "body=%s", rec.Body.String())++ var resp AISettingsResponse+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))+ assert.True(t, resp.Enabled)+ assert.Equal(t, config.DefaultModelForProvider(config.AIProviderQuickstart), resp.Model)+ assert.Equal(t, 25, resp.QuickstartCreditsRemaining)+ assert.Equal(t, 25, resp.QuickstartCreditsTotal)+}+func TestAISettingsHandler_UpdateSettings_OpenRouterKeySetAndClear(t *testing.T) {t.Parallel()diff --git a/internal/api/chat_service_adapter.go b/internal/api/chat_service_adapter.goindex 238f21bb10..d927928011 100644--- a/internal/api/chat_service_adapter.go+++ b/internal/api/chat_service_adapter.go@@ -6,6 +6,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai""github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"+ "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")@@ -91,6 +92,10 @@ func (a *chatServiceAdapter) ReloadConfig(ctx context.Context, cfg *config.AIConreturn a.svc.Restart(ctx, cfg)}+func (a *chatServiceAdapter) SetPatrolProviderFactory(factory func(string) (providers.StreamingProvider, error)) {+ a.svc.SetPatrolProviderFactory(factory)+}+// GetExecutor exposes the underlying chat service's tool executor so that// patrol can set the finding creator. This satisfies the// chatServiceExecutorAccessor interface in the ai package.diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex aabed9f304..7bf47f32c3 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -88,6 +88,44 @@ func TestContract_WireAIChatDependencies_WiresTrueNASAppActionProvider(t *testin}}+func TestContract_AIQuickstartPayloadFieldsRemainCanonical(t *testing.T) {+ settingsBody, err := json.Marshal(AISettingsResponse{+ QuickstartCreditsRemaining: 7,+ QuickstartCreditsTotal: 25,+ UsingQuickstart: true,+ })+ if err != nil {+ t.Fatalf("marshal AI settings response: %v", err)+ }+ if !bytes.Contains(settingsBody, []byte(`"quickstart_credits_remaining":7`)) {+ t.Fatalf("expected AI settings payload to expose quickstart_credits_remaining, got %s", settingsBody)+ }+ if !bytes.Contains(settingsBody, []byte(`"quickstart_credits_total":25`)) {+ t.Fatalf("expected AI settings payload to expose quickstart_credits_total, got %s", settingsBody)+ }+ if !bytes.Contains(settingsBody, []byte(`"using_quickstart":true`)) {+ t.Fatalf("expected AI settings payload to expose using_quickstart, got %s", settingsBody)+ }++ statusBody, err := json.Marshal(PatrolStatusResponse{+ QuickstartCreditsRemaining: 7,+ QuickstartCreditsTotal: 25,+ UsingQuickstart: true,+ })+ if err != nil {+ t.Fatalf("marshal patrol status response: %v", err)+ }+ if !bytes.Contains(statusBody, []byte(`"quickstart_credits_remaining":7`)) {+ t.Fatalf("expected patrol status payload to expose quickstart_credits_remaining, got %s", statusBody)+ }+ if !bytes.Contains(statusBody, []byte(`"quickstart_credits_total":25`)) {+ t.Fatalf("expected patrol status payload to expose quickstart_credits_total, got %s", statusBody)+ }+ if !bytes.Contains(statusBody, []byte(`"using_quickstart":true`)) {+ t.Fatalf("expected patrol status payload to expose using_quickstart, got %s", statusBody)+ }+}+func TestContract_ChartMetricPointsPreserveMillisecondPrecision(t *testing.T) {pointTime := time.Date(2026, time.March, 31, 12, 0, 0, 987_000_000, time.UTC)diff --git a/internal/config/persistence.go b/internal/config/persistence.goindex 8437149554..690739df00 100644--- a/internal/config/persistence.go+++ b/internal/config/persistence.go@@ -38,6 +38,7 @@ type ConfigPersistence struct {ssoFile stringapiTokensFile stringaiFile string+ quickstartFile stringaiFindingsFile stringaiPatrolRunsFile stringaiUsageHistoryFile string@@ -101,6 +102,7 @@ type resolvedConfigPersistencePaths struct {ssoFile stringapiTokensFile stringaiFile string+ quickstartFile stringaiFindingsFile stringaiPatrolRunsFile stringaiUsageHistoryFile string@@ -165,6 +167,10 @@ func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPersif err != nil {return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve ai.enc: %w", err)}+ quickstartFile, err := resolveLeaf("quickstart.enc")+ if err != nil {+ return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve quickstart.enc: %w", err)+ }aiFindingsFile, err := resolveLeaf("ai_findings.json")if err != nil {return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve ai_findings.json: %w", err)@@ -210,6 +216,7 @@ func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPersssoFile: ssoFile,apiTokensFile: apiTokensFile,aiFile: aiFile,+ quickstartFile: quickstartFile,aiFindingsFile: aiFindingsFile,aiPatrolRunsFile: aiPatrolRunsFile,aiUsageHistoryFile: aiUsageHistoryFile,@@ -260,6 +267,7 @@ func newConfigPersistence(configDir string) (*ConfigPersistence, error) {ssoFile: resolvedPaths.ssoFile,apiTokensFile: resolvedPaths.apiTokensFile,aiFile: resolvedPaths.aiFile,+ quickstartFile: resolvedPaths.quickstartFile,aiFindingsFile: resolvedPaths.aiFindingsFile,aiPatrolRunsFile: resolvedPaths.aiPatrolRunsFile,aiUsageHistoryFile: resolvedPaths.aiUsageHistoryFile,diff --git a/internal/config/quickstart_state.go b/internal/config/quickstart_state.gonew file mode 100644index 0000000000..23ed2e77a5--- /dev/null+++ b/internal/config/quickstart_state.go@@ -0,0 +1,128 @@+package config++import (+ "encoding/json"+ "fmt"+ "os"+ "strings"+ "time"+)++// QuickstartState is the machine-owned local cache for the server-authoritative+// quickstart bootstrap contract.+type QuickstartState struct {+ ClientInstallationID string `json:"client_installation_id,omitempty"`+ QuickstartToken string `json:"quickstart_token,omitempty"`+ QuickstartTokenExpiresAt *int64 `json:"quickstart_token_expires_at,omitempty"`+ QuickstartCreditsTotal int `json:"quickstart_credits_total,omitempty"`+ QuickstartCreditsRemaining int `json:"quickstart_credits_remaining,omitempty"`+ LastSyncedAt *int64 `json:"last_synced_at,omitempty"`+}++// NormalizeQuickstartState returns a deep-cloned, normalized quickstart state.+func NormalizeQuickstartState(state *QuickstartState) *QuickstartState {+ if state == nil {+ return &QuickstartState{}+ }++ cp := *state+ normalized := &cp+ normalized.ClientInstallationID = strings.TrimSpace(normalized.ClientInstallationID)+ normalized.QuickstartToken = strings.TrimSpace(normalized.QuickstartToken)+ normalized.QuickstartTokenExpiresAt = cloneQuickstartInt64Ptr(state.QuickstartTokenExpiresAt)+ normalized.LastSyncedAt = cloneQuickstartInt64Ptr(state.LastSyncedAt)+ if normalized.QuickstartCreditsTotal < 0 {+ normalized.QuickstartCreditsTotal = 0+ }+ if normalized.QuickstartCreditsRemaining < 0 {+ normalized.QuickstartCreditsRemaining = 0+ }+ if normalized.QuickstartCreditsTotal > 0 && normalized.QuickstartCreditsRemaining > normalized.QuickstartCreditsTotal {+ normalized.QuickstartCreditsRemaining = normalized.QuickstartCreditsTotal+ }+ return normalized+}++func cloneQuickstartInt64Ptr(value *int64) *int64 {+ if value == nil {+ return nil+ }+ cloned := *value+ return &cloned+}++// TokenExpired reports whether the cached quickstart token is expired at the+// supplied timestamp.+func (s *QuickstartState) TokenExpired(now time.Time) bool {+ if s == nil || s.QuickstartTokenExpiresAt == nil || *s.QuickstartTokenExpiresAt <= 0 {+ return false+ }+ return now.Unix() >= *s.QuickstartTokenExpiresAt+}++// SaveQuickstartState persists the machine-owned quickstart cache.+func (c *ConfigPersistence) SaveQuickstartState(state QuickstartState) error {+ c.mu.Lock()+ defer c.mu.Unlock()++ if err := c.EnsureConfigDir(); err != nil {+ return fmt.Errorf("prepare config directory for quickstart state: %w", err)+ }++ normalized := NormalizeQuickstartState(&state)+ data, err := json.Marshal(normalized)+ if err != nil {+ return fmt.Errorf("marshal quickstart state: %w", err)+ }++ if c.crypto != nil {+ encrypted, err := c.crypto.Encrypt(data)+ if err != nil {+ return fmt.Errorf("encrypt quickstart state: %w", err)+ }+ data = encrypted+ }++ if err := c.writeConfigFileLocked(c.quickstartFile, data, 0o600); err != nil {+ return fmt.Errorf("persist quickstart state: %w", err)+ }++ return nil+}++// LoadQuickstartState retrieves the cached quickstart bootstrap state.+func (c *ConfigPersistence) LoadQuickstartState() (*QuickstartState, error) {+ c.mu.Lock()+ defer c.mu.Unlock()++ var state QuickstartState+ migratedPlaintext, _, err := loadEncryptedJSONLocked(c, c.quickstartFile, &state, "quickstart state")+ if err != nil {+ if os.IsNotExist(err) {+ return &QuickstartState{}, nil+ }+ return nil, err+ }++ normalized := NormalizeQuickstartState(&state)+ if migratedPlaintext {+ jsonData, err := json.Marshal(normalized)+ if err != nil {+ return nil, fmt.Errorf("marshal quickstart state migration rewrite: %w", err)+ }+ if err := rewriteEncryptedJSONLocked(c, c.quickstartFile, jsonData, "quickstart state migration rewrite"); err != nil {+ return nil, err+ }+ }++ return normalized, nil+}++// HasQuickstartState reports whether quickstart.enc exists on disk.+func (c *ConfigPersistence) HasQuickstartState() bool {+ if c == nil || c.fs == nil {+ return false+ }+ _, err := c.fs.Stat(c.quickstartFile)+ return err == nil+}diff --git a/internal/config/quickstart_state_test.go b/internal/config/quickstart_state_test.gonew file mode 100644index 0000000000..be1add8e4d--- /dev/null+++ b/internal/config/quickstart_state_test.go@@ -0,0 +1,74 @@+package config++import (+ "bytes"+ "os"+ "path/filepath"+ "testing"+)++func TestQuickstartStateSaveAndLoad(t *testing.T) {+ dir := t.TempDir()+ persistence := NewConfigPersistence(dir)++ expiresAt := int64(1774449000)+ lastSyncedAt := int64(1774448000)+ state := QuickstartState{+ ClientInstallationID: "community-install-1",+ QuickstartToken: "qst_live_test_123",+ QuickstartTokenExpiresAt: &expiresAt,+ QuickstartCreditsTotal: 25,+ QuickstartCreditsRemaining: 17,+ LastSyncedAt: &lastSyncedAt,+ }++ if err := persistence.SaveQuickstartState(state); err != nil {+ t.Fatalf("SaveQuickstartState: %v", err)+ }++ loaded, err := persistence.LoadQuickstartState()+ if err != nil {+ t.Fatalf("LoadQuickstartState: %v", err)+ }+ if loaded.ClientInstallationID != state.ClientInstallationID {+ t.Fatalf("ClientInstallationID = %q, want %q", loaded.ClientInstallationID, state.ClientInstallationID)+ }+ if loaded.QuickstartToken != state.QuickstartToken {+ t.Fatalf("QuickstartToken = %q, want %q", loaded.QuickstartToken, state.QuickstartToken)+ }+ if loaded.QuickstartCreditsRemaining != state.QuickstartCreditsRemaining {+ t.Fatalf("QuickstartCreditsRemaining = %d, want %d", loaded.QuickstartCreditsRemaining, state.QuickstartCreditsRemaining)+ }+ if loaded.QuickstartCreditsTotal != state.QuickstartCreditsTotal {+ t.Fatalf("QuickstartCreditsTotal = %d, want %d", loaded.QuickstartCreditsTotal, state.QuickstartCreditsTotal)+ }+ if loaded.QuickstartTokenExpiresAt == nil || *loaded.QuickstartTokenExpiresAt != expiresAt {+ t.Fatalf("QuickstartTokenExpiresAt = %v, want %d", loaded.QuickstartTokenExpiresAt, expiresAt)+ }+ if loaded.LastSyncedAt == nil || *loaded.LastSyncedAt != lastSyncedAt {+ t.Fatalf("LastSyncedAt = %v, want %d", loaded.LastSyncedAt, lastSyncedAt)+ }++ raw, err := os.ReadFile(filepath.Join(dir, "quickstart.enc"))+ if err != nil {+ t.Fatalf("ReadFile(quickstart.enc): %v", err)+ }+ if bytes.Contains(raw, []byte(state.QuickstartToken)) {+ t.Fatal("quickstart.enc should not contain the raw quickstart token")+ }+}++func TestLoadQuickstartState_MissingReturnsEmptyState(t *testing.T) {+ persistence := NewConfigPersistence(t.TempDir())++ loaded, err := persistence.LoadQuickstartState()+ if err != nil {+ t.Fatalf("LoadQuickstartState: %v", err)+ }+ if loaded == nil {+ t.Fatal("expected empty quickstart state, got nil")+ }+ if loaded.QuickstartToken != "" || loaded.QuickstartCreditsRemaining != 0 || loaded.ClientInstallationID != "" {+ t.Fatalf("expected zero-value quickstart state, got %#v", loaded)+ }+}diff --git a/pkg/licensing/license_server_client.go b/pkg/licensing/license_server_client.goindex c8f294171e..c67ad0453c 100644--- a/pkg/licensing/license_server_client.go+++ b/pkg/licensing/license_server_client.go@@ -140,6 +140,44 @@ func (c *LicenseServerClient) RefreshGrant(ctx context.Context, installationID,return &result, nil}+// BootstrapQuickstart exchanges a runtime identity for a short-lived+// quickstart token and the current authoritative quickstart inventory.+// Activated installs should pass their installation token as bearerToken.+func (c *LicenseServerClient) BootstrapQuickstart(ctx context.Context, bearerToken string, req QuickstartBootstrapRequest) (*QuickstartBootstrapResponse, error) {+ body, err := json.Marshal(req)+ if err != nil {+ return nil, fmt.Errorf("marshal quickstart bootstrap request: %w", err)+ }++ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/v1/quickstart/bootstrap", bytes.NewReader(body))+ if err != nil {+ return nil, fmt.Errorf("create quickstart bootstrap request: %w", err)+ }+ httpReq.Header.Set("Content-Type", "application/json")+ if token := strings.TrimSpace(bearerToken); token != "" {+ httpReq.Header.Set("Authorization", "Bearer "+token)+ }++ bootstrapClient := *c.httpClient+ bootstrapClient.Timeout = 10 * time.Second++ resp, err := bootstrapClient.Do(httpReq)+ if err != nil {+ return nil, fmt.Errorf("quickstart bootstrap request failed: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {+ return nil, c.parseError(resp)+ }++ var result QuickstartBootstrapResponse+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil {+ return nil, fmt.Errorf("decode quickstart bootstrap response: %w", err)+ }+ return &result, nil+}+// FetchRevocations polls the revocation feed for events after the given sequence number.// The feedToken authenticates access to the revocation feed.func (c *LicenseServerClient) FetchRevocations(ctx context.Context, feedToken string, sinceSeq int64, limit int) (*RevocationFeedResponse, error) {diff --git a/pkg/licensing/license_server_client_test.go b/pkg/licensing/license_server_client_test.goindex 31ca248b06..d3e5952b8b 100644--- a/pkg/licensing/license_server_client_test.go+++ b/pkg/licensing/license_server_client_test.go@@ -342,3 +342,90 @@ func TestClientRefreshGrant(t *testing.T) {}})}++func TestClientBootstrapQuickstart(t *testing.T) {+ t.Run("uses installation bearer token when provided", func(t *testing.T) {+ var seenAuthorization string+ var seenRequest QuickstartBootstrapRequest++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Errorf("Method = %q, want POST", r.Method)+ }+ if r.URL.Path != "/v1/quickstart/bootstrap" {+ t.Errorf("Path = %q, want /v1/quickstart/bootstrap", r.URL.Path)+ }+ seenAuthorization = r.Header.Get("Authorization")+ if err := json.NewDecoder(r.Body).Decode(&seenRequest); err != nil {+ t.Fatalf("decode request: %v", err)+ }+ w.WriteHeader(http.StatusCreated)+ json.NewEncoder(w).Encode(QuickstartBootstrapResponse{+ QuickstartToken: "qst_live_123",+ QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),+ CreditsRemaining: 17,+ CreditsTotal: 25,+ })+ }))+ defer server.Close()++ client := NewLicenseServerClient(server.URL)+ resp, err := client.BootstrapQuickstart(context.Background(), "pit_live_token", QuickstartBootstrapRequest{+ InstanceFingerprint: "fp-123",+ InstanceName: "pulse-test",+ UseCase: "patrol",+ })+ if err != nil {+ t.Fatalf("BootstrapQuickstart failed: %v", err)+ }+ if seenAuthorization != "Bearer pit_live_token" {+ t.Fatalf("Authorization = %q, want Bearer pit_live_token", seenAuthorization)+ }+ if seenRequest.UseCase != "patrol" {+ t.Fatalf("UseCase = %q, want patrol", seenRequest.UseCase)+ }+ if resp.QuickstartToken != "qst_live_123" {+ t.Fatalf("QuickstartToken = %q, want qst_live_123", resp.QuickstartToken)+ }+ if resp.CreditsRemaining != 17 || resp.CreditsTotal != 25 {+ t.Fatalf("credits = %d/%d, want 17/25", resp.CreditsRemaining, resp.CreditsTotal)+ }+ })++ t.Run("uses community installation id when no auth token is present", func(t *testing.T) {+ var seenAuthorization string+ var seenRequest QuickstartBootstrapRequest++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ seenAuthorization = r.Header.Get("Authorization")+ if err := json.NewDecoder(r.Body).Decode(&seenRequest); err != nil {+ t.Fatalf("decode request: %v", err)+ }+ json.NewEncoder(w).Encode(QuickstartBootstrapResponse{+ QuickstartToken: "qst_live_community",+ CreditsRemaining: 25,+ CreditsTotal: 25,+ })+ }))+ defer server.Close()++ client := NewLicenseServerClient(server.URL)+ resp, err := client.BootstrapQuickstart(context.Background(), "", QuickstartBootstrapRequest{+ ClientInstallationID: "community-install-1",+ InstanceFingerprint: "community-install-1",+ UseCase: "patrol",+ })+ if err != nil {+ t.Fatalf("BootstrapQuickstart failed: %v", err)+ }+ if seenAuthorization != "" {+ t.Fatalf("Authorization = %q, want empty", seenAuthorization)+ }+ if seenRequest.ClientInstallationID != "community-install-1" {+ t.Fatalf("ClientInstallationID = %q, want community-install-1", seenRequest.ClientInstallationID)+ }+ if resp.QuickstartToken != "qst_live_community" {+ t.Fatalf("QuickstartToken = %q, want qst_live_community", resp.QuickstartToken)+ }+ })+}diff --git a/pkg/licensing/quickstart_bootstrap.go b/pkg/licensing/quickstart_bootstrap.gonew file mode 100644index 0000000000..5b56eaacd1--- /dev/null+++ b/pkg/licensing/quickstart_bootstrap.go@@ -0,0 +1,22 @@+package licensing++// QuickstartBootstrapRequest is sent to the license server to exchange a+// runtime identity for a server-issued quickstart token.+//+// Activated installs authenticate the request with their installation token.+// Community installs omit auth and instead send a stable client installation id.+type QuickstartBootstrapRequest struct {+ ClientInstallationID string `json:"client_installation_id,omitempty"`+ InstanceFingerprint string `json:"instance_fingerprint,omitempty"`+ InstanceName string `json:"instance_name,omitempty"`+ UseCase string `json:"use_case,omitempty"`+}++// QuickstartBootstrapResponse contains the server-issued quickstart token and+// the current authoritative quickstart inventory snapshot.+type QuickstartBootstrapResponse struct {+ QuickstartToken string `json:"quickstart_token"`+ QuickstartTokenExpiresAt string `json:"quickstart_token_expires_at,omitempty"`+ CreditsRemaining int `json:"credits_remaining"`+ CreditsTotal int `json:"credits_total"`+}