Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Support enterprise mobile approval proof backend

rcourtman2fdf0e16c88a
diff --git a/cmd/pulse/commands_test.go b/cmd/pulse/commands_test.go
index 776c53ef38..ce19291ab7 100644
--- a/cmd/pulse/commands_test.go
+++ b/cmd/pulse/commands_test.go
@@ -67,8 +67,8 @@ func TestResolveMetricsPortFromEnvPrefersPrefixedOverride(t *testing.T) {
t.Setenv("PULSE_METRICS_PORT", "0")
t.Setenv("METRICS_PORT", "9091")
- if got := resolveMetricsPortFromEnv(nil, 7655); got != 0 {
- t.Fatalf("resolveMetricsPortFromEnv() = %d, want 0", got)
+ if got := server.ResolveMetricsPortFromEnv(nil, 7655); got != 0 {
+ t.Fatalf("ResolveMetricsPortFromEnv() = %d, want 0", got)
}
}
@@ -76,8 +76,8 @@ func TestResolveMetricsPortFromEnvFallsBackOnInvalidValue(t *testing.T) {
t.Setenv("PULSE_METRICS_PORT", "not-a-port")
var stderr bytes.Buffer
- if got := resolveMetricsPortFromEnv(&stderr, 9091); got != 9091 {
- t.Fatalf("resolveMetricsPortFromEnv() = %d, want fallback 9091", got)
+ if got := server.ResolveMetricsPortFromEnv(&stderr, 9091); got != 9091 {
+ t.Fatalf("ResolveMetricsPortFromEnv() = %d, want fallback 9091", got)
}
assert.Contains(t, stderr.String(), "Ignoring invalid PULSE_METRICS_PORT value")
}
diff --git a/cmd/pulse/main.go b/cmd/pulse/main.go
index f54518fddc..365d5a4874 100644
--- a/cmd/pulse/main.go
+++ b/cmd/pulse/main.go
@@ -5,8 +5,6 @@ import (
"fmt"
"io"
"os"
- "strconv"
- "strings"
"github.com/rcourtman/pulse-go-rewrite/internal/updates"
"github.com/rcourtman/pulse-go-rewrite/pkg/pulsecli"
@@ -21,29 +19,9 @@ var (
metricsPort = 9091
)
-func resolveMetricsPortFromEnv(stderr io.Writer, fallback int) int {
- for _, envName := range []string{"PULSE_METRICS_PORT", "METRICS_PORT"} {
- raw := strings.TrimSpace(os.Getenv(envName))
- if raw == "" {
- continue
- }
-
- port, err := strconv.Atoi(raw)
- if err != nil || port < 0 || port > 65535 {
- if stderr != nil {
- fmt.Fprintf(stderr, "Ignoring invalid %s value %q; using metrics port %d\n", envName, raw, fallback)
- }
- return fallback
- }
- return port
- }
-
- return fallback
-}
-
func runServer(ctx context.Context) error {
updates.BuildVersion = Version
- server.MetricsPort = resolveMetricsPortFromEnv(os.Stderr, metricsPort)
+ server.MetricsPort = server.ResolveMetricsPortFromEnv(os.Stderr, metricsPort)
return server.Run(ctx, Version)
}
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index b38040b364..abf63b3004 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -207,6 +207,12 @@ relay bootstrap reads use one effective hosted billing lease before
lifecycle-adjacent flows inspect runtime readiness, so install and setup
surfaces do not observe a tenant-org Pulse Assistant state that disagrees
with the machine-owned hosted entitlement already backing the same instance.
+That same shared dependency now also assumes settings-driven AI enablement can
+cold-start the direct Assistant runtime and approval persistence without a
+prior chat session. Lifecycle-adjacent mobile pairing and setup flows depend
+on `/api/ai/approvals` becoming ready from the first governed settings save,
+not only after some earlier process-start or chat-start side effect has
+already initialized the approval store.
That same shared dependency now also assumes hosted cloud handoff makes tenant
org access real before browser lifecycle continues. Lifecycle-adjacent opens
into hosted workspaces may depend on `internal/api/cloud_handoff_handlers.go`,
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 751d6670a0..90ce48cdaa 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -146,6 +146,14 @@ the request runs under a hosted tenant org with no org-local billing lease,
the same AI runtime path must inherit the default hosted lease for bootstrap
and quickstart-credit reads so tenant-scoped Chat, Patrol, and AI Settings
stay aligned with the machine-owned hosted entitlement state.
+That same runtime boundary also owns approval-store lifecycle in
+`internal/api/ai_handler.go`. Settings-driven enablement and restart must be
+able to cold-start the direct AI runtime, initialize approval persistence, and
+leave `/api/ai/approvals` ready for mobile and remediation flows even when AI
+was disabled at process boot. The approval cleanup loop must follow owned AI
+runtime lifetime rather than an HTTP request context, and approval persistence
+may fail closed only when AI is actually disabled instead of because runtime
+enablement happened after startup.
The same ownership includes the Pulse query tool schema under
`internal/ai/tools/`: topology-query input names must stay canonical inside
the AI runtime itself, so new tool arguments such as `max_proxmox_nodes`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index e46835ffb6..69e2ceb897 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -165,6 +165,7 @@ Own canonical runtime payload shapes between backend and frontend.
19. Keep mobile onboarding payload reads aligned with the server-owned relay-mobile credential: `internal/api/router_routes_ai_relay.go`, `internal/api/onboarding_handlers.go`, and `internal/api/contract_test.go` must allow the dedicated `relay:mobile:access` scope to reach the governed QR, deep-link, and connection-validation payloads without reintroducing a broader `settings:read` requirement for token-authenticated pairing clients.
20. Keep hosted billing-state quickstart payload fields on the shared API contract: `internal/api/hosted_entitlement_refresh.go`, `internal/api/subscription_state_handlers.go`, and `internal/api/contract_test.go` must preserve `quickstart_credits_granted`, `quickstart_credits_used`, and `quickstart_credits_granted_at` through hosted signup, hosted lease refresh, and billing-state reads instead of letting lease rewrites silently erase seeded quickstart inventory.
21. Keep hosted AI settings bootstrap on the shared API contract: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`, `internal/api/ai_handler.go`, and `internal/api/contract_test.go` must treat a missing `ai.enc` in hosted mode as a canonical bootstrap condition, persist one machine-owned quickstart-backed AI config when hosted entitlements grant AI capability, and preserve that configured settings payload as the same public contract that Chat, Patrol, and AI Settings consume.
+22. Keep post-boot AI enablement contract-backed on the shared AI/mobile approval surface: `internal/api/ai_handler.go`, `internal/api/ai_handlers.go`, `internal/api/router_routes_ai_relay.go`, and `internal/api/contract_test.go` must turn the governed approvals-list API into the canonical empty-list payload as soon as settings-driven AI enablement succeeds, rather than leaving that surface on `503 Approval store not initialized` until some separate startup-only side effect happens.
## Forbidden Paths
@@ -2053,3 +2054,11 @@ startup to consume that hosted-aware config path and to refuse caching a
failed tenant chat service, so tenant-org `/api/ai/status` and
`/api/ai/sessions` cannot stay wedged behind a stale pre-bootstrap service
after the lease-backed AI config has been persisted.
+That same shared AI/mobile API contract now also owns approval-list readiness
+for settings-driven enablement. `internal/api/ai_handler.go`,
+`internal/api/ai_handlers.go`, `internal/api/router_routes_ai_relay.go`, and
+`internal/api/contract_test.go` must keep the governed approvals-list surface
+on its empty-list payload once AI is enabled, even when the first enablement
+happens after process startup. A post-boot settings save may not leave that
+surface on `503 Approval store not initialized` just because the direct AI
+runtime had not previously started.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index bf97a78c2d..0cc7677191 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -141,6 +141,12 @@ runtime data-dir authority being replaceable without hangs or leaked state,
and router teardown must close the exact session, CSRF, and recovery-token
workers that router initialized instead of assuming a later global auth-store
binding will clean them up.
+That same shared lifecycle discipline now also applies to Assistant approval
+store cleanup when `internal/api/ai_handler.go` is touched from shared router
+work. Approval persistence must not bind its cleanup loop to one request-scoped
+context and silently disappear after a settings save, because recovery- and
+storage-adjacent runtime proofs depend on the same owned backend lifetime model
+instead of opportunistic request ownership for long-lived background workers.
That same runtime data-dir authority also assumes file-backed stores keep
canonical filenames opaque and machine-owned. Recovery-adjacent session,
knowledge, and discovery records may discover legacy identifier-derived files
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index c27a9cf7f4..5d1b519d22 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -76,6 +76,7 @@ type AIService interface {
// AIHandler handles all AI endpoints using direct AI integration
type AIHandler struct {
stateMu sync.RWMutex
+ approvalStoreMu sync.Mutex
mtPersistence *config.MultiTenantPersistence
mtMonitor *monitoring.MultiTenantMonitor
defaultConfig *config.Config
@@ -93,6 +94,9 @@ type AIHandler struct {
unifiedStores map[string]*unified.UnifiedStore
readState unifiedresources.ReadState
recoveryManager *recoverymanager.Manager
+ approvalStore *approval.Store
+ approvalStoreDir string
+ approvalStoreStop context.CancelFunc
}
// newChatService is the factory function for creating the AI service.
@@ -510,6 +514,59 @@ func (h *AIHandler) SetMultiTenantMonitor(mtm *monitoring.MultiTenantMonitor) {
h.mtMonitor = mtm
}
+func (h *AIHandler) ensureApprovalStore(dataDir string) {
+ if strings.TrimSpace(dataDir) == "" {
+ return
+ }
+
+ h.approvalStoreMu.Lock()
+ defer h.approvalStoreMu.Unlock()
+
+ if h.approvalStore != nil && h.approvalStoreDir == dataDir {
+ approval.SetStore(h.approvalStore)
+ return
+ }
+
+ if h.approvalStoreStop != nil {
+ h.approvalStoreStop()
+ h.approvalStoreStop = nil
+ }
+
+ approvalStore, err := approval.NewStore(approval.StoreConfig{
+ DataDir: dataDir,
+ DefaultTimeout: 5 * time.Minute,
+ MaxApprovals: 100,
+ })
+ if err != nil {
+ h.approvalStore = nil
+ h.approvalStoreDir = ""
+ approval.SetStore(nil)
+ log.Warn().Err(err).Msg("Failed to create approval store, approvals will not be persisted")
+ return
+ }
+
+ cleanupCtx, cleanupCancel := context.WithCancel(context.Background())
+ approvalStore.StartCleanup(cleanupCtx)
+ approval.SetStore(approvalStore)
+ h.approvalStore = approvalStore
+ h.approvalStoreDir = dataDir
+ h.approvalStoreStop = cleanupCancel
+ log.Info().Str("data_dir", dataDir).Msg("Approval store initialized")
+}
+
+func (h *AIHandler) clearApprovalStore() {
+ h.approvalStoreMu.Lock()
+ defer h.approvalStoreMu.Unlock()
+
+ if h.approvalStoreStop != nil {
+ h.approvalStoreStop()
+ h.approvalStoreStop = nil
+ }
+ h.approvalStore = nil
+ h.approvalStoreDir = ""
+ approval.SetStore(nil)
+}
+
// Start initializes and starts the AI chat service.
// The monitor parameter provides state snapshots to the chat service (satisfies chat.StateProvider).
func (h *AIHandler) Start(ctx context.Context, monitor *monitoring.Monitor) error {
@@ -561,19 +618,8 @@ func (h *AIHandler) Start(ctx context.Context, monitor *monitoring.Monitor) erro
h.servicesMu.Unlock()
h.applyServiceInitializer(context.WithValue(context.Background(), OrgIDContextKey, orgID), svc)
- // Initialize approval store for command approval workflow
- approvalStore, err := approval.NewStore(approval.StoreConfig{
- DataDir: dataDir,
- DefaultTimeout: 5 * time.Minute,
- MaxApprovals: 100,
- })
- if err != nil {
- log.Warn().Err(err).Msg("Failed to create approval store, approvals will not be persisted")
- } else {
- approval.SetStore(approvalStore)
- approvalStore.StartCleanup(ctx)
- log.Info().Str("data_dir", dataDir).Msg("Approval store initialized")
- }
+ // Initialize approval store for command approval workflow.
+ h.ensureApprovalStore(dataDir)
log.Info().Msg("Pulse AI started (direct integration)")
return nil
@@ -581,6 +627,7 @@ func (h *AIHandler) Start(ctx context.Context, monitor *monitoring.Monitor) erro
// Stop stops the AI chat service
func (h *AIHandler) Stop(ctx context.Context) error {
+ defer h.clearApprovalStore()
if svc := h.getDefaultService(); svc != nil {
return svc.Stop(ctx)
}
@@ -592,34 +639,61 @@ func (h *AIHandler) Stop(ctx context.Context) error {
func (h *AIHandler) Restart(ctx context.Context) error {
// Load fresh config from persistence to get latest settings
newCfg := h.loadAIConfig(ctx)
-
svc := h.getDefaultService()
+
+ if newCfg == nil || !newCfg.Enabled {
+ h.clearApprovalStore()
+ if svc == nil {
+ return nil
+ }
+ return svc.Restart(ctx, newCfg)
+ }
+
+ // If enabled but not started yet, recover the monitor and bootstrap now.
if svc == nil {
- return nil
+ log.Info().Msg("Starting AI service via restart trigger")
+
+ h.stateMu.RLock()
+ m := h.defaultMonitor
+ mtm := h.mtMonitor
+ h.stateMu.RUnlock()
+
+ if m == nil && mtm != nil {
+ m, _ = mtm.GetMonitor("default")
+ }
+
+ return h.Start(ctx, m)
}
if !svc.IsRunning() {
- // If not running but enabled, try to start
- if newCfg != nil && newCfg.Enabled {
- log.Info().Msg("Starting AI service via restart trigger")
-
- // Recover the monitor: prefer cached default-org monitor, fall back to mtMonitor.
- h.stateMu.RLock()
- m := h.defaultMonitor
- mtm := h.mtMonitor
- h.stateMu.RUnlock()
-
- if m == nil && mtm != nil {
- m, _ = mtm.GetMonitor("default")
- }
+ log.Info().Msg("Starting AI service via restart trigger")
- // Reuse start logic
- return h.Start(ctx, m)
+ // Recover the monitor: prefer cached default-org monitor, fall back to mtMonitor.
+ h.stateMu.RLock()
+ m := h.defaultMonitor
+ mtm := h.mtMonitor
+ h.stateMu.RUnlock()
+
+ if m == nil && mtm != nil {
+ m, _ = mtm.GetMonitor("default")
}
- return nil // Not running and not enabled, nothing to do
+
+ // Reuse start logic
+ return h.Start(ctx, m)
}
- return svc.Restart(ctx, newCfg)
+ if err := svc.Restart(ctx, newCfg); err != nil {
+ return err
+ }
+
+ persistence := h.getPersistence(ctx)
+ if persistence == nil {
+ return nil
+ }
+ dataDir := h.getDataDir(newCfg, persistence.DataDir())
+ h.ensureApprovalStore(dataDir)
+
+ return nil
}
// IsRunning returns whether AI is running
diff --git a/internal/api/ai_handler_restart_test.go b/internal/api/ai_handler_restart_test.go
index 86984eecd6..87ec491aa8 100644
--- a/internal/api/ai_handler_restart_test.go
+++ b/internal/api/ai_handler_restart_test.go
@@ -4,6 +4,7 @@ import (
"context"
"testing"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/stretchr/testify/assert"
@@ -21,10 +22,16 @@ func TestRestart_StartIfStopped(t *testing.T) {
}
mockPersist := new(MockAIPersistence)
+ mockPersist.dataDir = t.TempDir()
h := newTestAIHandler(nil, mockPersist, nil)
// We need h.defaultService to be non-nil for the Restart check to proceed past first nil check
// But it must return IsRunning() = false
h.defaultService = mockSvc
+ prevStore := approval.GetStore()
+ t.Cleanup(func() {
+ h.clearApprovalStore()
+ approval.SetStore(prevStore)
+ })
// Config allows enabling
aiCfg := &config.AIConfig{Enabled: true}
@@ -38,6 +45,38 @@ func TestRestart_StartIfStopped(t *testing.T) {
err := h.Restart(context.Background())
assert.NoError(t, err)
+ assert.NotNil(t, approval.GetStore())
+
+ mockSvc.AssertExpectations(t)
+ mockPersist.AssertExpectations(t)
+}
+
+func TestRestart_StartIfServiceMissing(t *testing.T) {
+ oldNewService := newChatService
+ defer func() { newChatService = oldNewService }()
+
+ mockSvc := new(MockAIService)
+ newChatService = func(cfg chat.Config) AIService {
+ return mockSvc
+ }
+
+ mockPersist := new(MockAIPersistence)
+ mockPersist.dataDir = t.TempDir()
+ h := newTestAIHandler(nil, mockPersist, nil)
+ prevStore := approval.GetStore()
+ t.Cleanup(func() {
+ h.clearApprovalStore()
+ approval.SetStore(prevStore)
+ })
+
+ aiCfg := &config.AIConfig{Enabled: true}
+ mockPersist.On("LoadAIConfig").Return(aiCfg, nil).Twice()
+ mockSvc.On("Start", mock.Anything).Return(nil)
+
+ err := h.Restart(context.Background())
+ assert.NoError(t, err)
+ assert.Equal(t, mockSvc, h.defaultService)
+ assert.NotNil(t, approval.GetStore())
mockSvc.AssertExpectations(t)
mockPersist.AssertExpectations(t)
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index 2383ec5805..044eca4fee 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
@@ -258,21 +259,55 @@ func TestStart_Error(t *testing.T) {
func TestRestart(t *testing.T) {
mockPersist := new(MockAIPersistence)
+ mockPersist.dataDir = t.TempDir()
mockSvc := new(MockAIService)
h := newTestAIHandler(nil, mockPersist, nil)
h.defaultService = mockSvc
+ prevStore := approval.GetStore()
+ t.Cleanup(func() {
+ h.clearApprovalStore()
+ approval.SetStore(prevStore)
+ })
- aiCfg := &config.AIConfig{}
+ aiCfg := &config.AIConfig{Enabled: true}
mockPersist.On("LoadAIConfig").Return(aiCfg, nil)
mockSvc.On("IsRunning").Return(true)
mockSvc.On("Restart", mock.Anything, aiCfg).Return(nil)
err := h.Restart(context.Background())
assert.NoError(t, err)
+ assert.NotNil(t, approval.GetStore())
+}
+
+func TestRestart_DisabledClearsApprovalStore(t *testing.T) {
+ mockPersist := new(MockAIPersistence)
+ mockSvc := new(MockAIService)
+ h := newTestAIHandler(nil, mockPersist, nil)
+ h.defaultService = mockSvc
+
+ prevStore := approval.GetStore()
+ dataDir := t.TempDir()
+ seedStore, err := approval.NewStore(approval.StoreConfig{
+ DataDir: dataDir,
+ DefaultTimeout: time.Minute,
+ MaxApprovals: 10,
+ })
+ if err != nil {
+ t.Fatalf("create seed approval store: %v", err)
+ }
+ approval.SetStore(seedStore)
+ h.approvalStore = seedStore
+ h.approvalStoreDir = dataDir
+ t.Cleanup(func() {
+ h.clearApprovalStore()
+ approval.SetStore(prevStore)
+ })
+
+ mockPersist.On("LoadAIConfig").Return(&config.AIConfig{Enabled: false}, nil)
+ mockSvc.On("Restart", mock.Anything, mock.Anything).Return(nil)
- // Service nil
- h.defaultService = nil
err = h.Restart(context.Background())
assert.NoError(t, err)
+ assert.Nil(t, approval.GetStore())
}
func TestGetService(t *testing.T) {
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index e3057a1d3e..56a3d0135f 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -354,6 +354,37 @@ func TestContract_ApprovalJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_ApprovalListResponseJSONSnapshot(t *testing.T) {
+ payload := map[string]any{
+ "approvals": []approval.ApprovalRequest{},
+ "stats": map[string]int{
+ "approved": 0,
+ "denied": 0,
+ "executions": 0,
+ "expired": 0,
+ "pending": 0,
+ },
+ }
+
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal approval list response: %v", err)
+ }
+
+ const want = `{
+ "approvals":[],
+ "stats":{
+ "approved":0,
+ "denied":0,
+ "executions":0,
+ "expired":0,
+ "pending":0
+ }
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_HostedSignupResponseJSONSnapshot(t *testing.T) {
payload := hostedSignupResponse{
OrgID: "org-123",
diff --git a/pkg/server/metrics_port.go b/pkg/server/metrics_port.go
new file mode 100644
index 0000000000..3960373958
--- /dev/null
+++ b/pkg/server/metrics_port.go
@@ -0,0 +1,31 @@
+package server
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "strconv"
+ "strings"
+)
+
+// ResolveMetricsPortFromEnv returns the configured metrics port using the same
+// env contract for both the core and enterprise binaries.
+func ResolveMetricsPortFromEnv(stderr io.Writer, fallback int) int {
+ for _, envName := range []string{"PULSE_METRICS_PORT", "METRICS_PORT"} {
+ raw := strings.TrimSpace(os.Getenv(envName))
+ if raw == "" {
+ continue
+ }
+
+ port, err := strconv.Atoi(raw)
+ if err != nil || port < 0 || port > 65535 {
+ if stderr != nil {
+ fmt.Fprintf(stderr, "Ignoring invalid %s value %q; using metrics port %d\n", envName, raw, fallback)
+ }
+ return fallback
+ }
+ return port
+ }
+
+ return fallback
+}
diff --git a/pkg/server/metrics_port_test.go b/pkg/server/metrics_port_test.go
new file mode 100644
index 0000000000..de40041952
--- /dev/null
+++ b/pkg/server/metrics_port_test.go
@@ -0,0 +1,27 @@
+package server
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestResolveMetricsPortFromEnvPrefersPrefixedOverride(t *testing.T) {
+ t.Setenv("PULSE_METRICS_PORT", "0")
+ t.Setenv("METRICS_PORT", "9091")
+
+ if got := ResolveMetricsPortFromEnv(nil, 7655); got != 0 {
+ t.Fatalf("ResolveMetricsPortFromEnv() = %d, want 0", got)
+ }
+}
+
+func TestResolveMetricsPortFromEnvFallsBackOnInvalidValue(t *testing.T) {
+ t.Setenv("PULSE_METRICS_PORT", "not-a-port")
+
+ var stderr bytes.Buffer
+ if got := ResolveMetricsPortFromEnv(&stderr, 9091); got != 9091 {
+ t.Fatalf("ResolveMetricsPortFromEnv() = %d, want fallback 9091", got)
+ }
+ if stderr.Len() == 0 {
+ t.Fatal("expected invalid metrics port warning")
+ }
+}
diff --git a/tests/integration/scripts/managed-local-backend.mjs b/tests/integration/scripts/managed-local-backend.mjs
index 6beae19307..0550735065 100644
--- a/tests/integration/scripts/managed-local-backend.mjs
+++ b/tests/integration/scripts/managed-local-backend.mjs
@@ -11,10 +11,72 @@ const DEFAULT_E2E_BOOTSTRAP_TOKEN = '0123456789abcdef0123456789abcdef0123456789a
const DEFAULT_E2E_USERNAME = 'admin';
const DEFAULT_E2E_PASSWORD = 'adminadminadmin';
const DEFAULT_E2E_PRIMARY_API_TOKEN = '1111111111111111111111111111111111111111111111111111111111111111';
+const DEFAULT_LOCAL_BACKEND_VARIANT = 'core';
+const SUPPORTED_LOCAL_BACKEND_VARIANTS = new Set(['core', 'enterprise']);
const trim = (value) => String(value || '').trim();
const buildScopedPathSegment = (value) => String(value).replace(/[^A-Za-z0-9._-]+/g, '-');
+function resolveManagedLocalBackendVariant(env = process.env) {
+ const requestedVariant = trim(env.PULSE_E2E_LOCAL_BACKEND_VARIANT).toLowerCase();
+ if (requestedVariant === '') {
+ return DEFAULT_LOCAL_BACKEND_VARIANT;
+ }
+ if (!SUPPORTED_LOCAL_BACKEND_VARIANTS.has(requestedVariant)) {
+ throw new Error(
+ `Unsupported managed local backend variant ${JSON.stringify(requestedVariant)}. Supported variants: ${Array.from(SUPPORTED_LOCAL_BACKEND_VARIANTS).join(', ')}`,
+ );
+ }
+ return requestedVariant;
+}
+
+function buildManagedLocalBackendBinaryConfig(env, repoRoot) {
+ const backendVariant = resolveManagedLocalBackendVariant(env);
+ if (backendVariant === 'enterprise') {
+ const enterpriseRepoRoot = trim(env.PULSE_E2E_LOCAL_BACKEND_ENTERPRISE_REPO)
+ || path.resolve(repoRoot, '..', 'pulse-enterprise');
+ return {
+ backendVariant,
+ binaryPath: trim(env.PULSE_E2E_LOCAL_BACKEND_BINARY)
+ || path.join(repoRoot, 'tmp', 'integration-local-backend', 'bin', 'pulse-enterprise'),
+ binaryBuildLockPath: path.join(repoRoot, 'tmp', 'locks', 'managed-local-backend-binary-enterprise.lock'),
+ binaryBuildCwd: enterpriseRepoRoot,
+ binaryBuildArgs: ['build', '-buildvcs=false', '-o', '__OUTPUT__', './cmd/pulse-enterprise'],
+ binarySourceRoots: [
+ path.join(enterpriseRepoRoot, 'cmd'),
+ path.join(enterpriseRepoRoot, 'internal'),
+ path.join(enterpriseRepoRoot, 'test'),
+ path.join(repoRoot, 'cmd'),
+ path.join(repoRoot, 'internal'),
+ path.join(repoRoot, 'pkg'),
+ ],
+ binaryManifestPaths: [
+ path.join(enterpriseRepoRoot, 'go.mod'),
+ path.join(enterpriseRepoRoot, 'go.sum'),
+ path.join(repoRoot, 'go.mod'),
+ path.join(repoRoot, 'go.sum'),
+ ],
+ };
+ }
+
+ return {
+ backendVariant,
+ binaryPath: trim(env.PULSE_E2E_LOCAL_BACKEND_BINARY) || path.join(repoRoot, 'pulse'),
+ binaryBuildLockPath: path.join(repoRoot, 'tmp', 'locks', 'managed-local-backend-binary.lock'),
+ binaryBuildCwd: repoRoot,
+ binaryBuildArgs: ['build', '-o', '__OUTPUT__', './cmd/pulse'],
+ binarySourceRoots: [
+ path.join(repoRoot, 'cmd'),
+ path.join(repoRoot, 'internal'),
+ path.join(repoRoot, 'pkg'),
+ ],
+ binaryManifestPaths: [
+ path.join(repoRoot, 'go.mod'),
+ path.join(repoRoot, 'go.sum'),
+ ],
+ };
+}
+
function resolveManagedLocalBackendRunId(env) {
const explicitRunId = trim(env.PULSE_E2E_RUN_ID);
if (explicitRunId !== '') {
@@ -31,6 +93,7 @@ function resolveManagedLocalBackendRunId(env) {
export function buildManagedLocalBackendState(env = process.env) {
const repoRoot = getRepoRoot();
+ const binaryConfig = buildManagedLocalBackendBinaryConfig(env, repoRoot);
const port = trim(env.PULSE_E2E_LOCAL_BACKEND_PORT) || '8765';
const metricsPort = trim(env.PULSE_E2E_LOCAL_BACKEND_METRICS_PORT) || '0';
const host = trim(env.PULSE_E2E_LOCAL_BACKEND_HOST) || '127.0.0.1';
@@ -44,6 +107,7 @@ export function buildManagedLocalBackendState(env = process.env) {
return {
managedLocalBackend: true,
+ backendVariant: binaryConfig.backendVariant,
repoRoot,
port,
metricsPort,
@@ -54,8 +118,12 @@ export function buildManagedLocalBackendState(env = process.env) {
logPath: path.join(rootDir, 'pulse.log'),
pidPath: path.join(rootDir, 'pulse.pid'),
billingStatePath: path.join(rootDir, 'data', 'billing.json'),
- binaryPath: trim(env.PULSE_E2E_LOCAL_BACKEND_BINARY) || path.join(repoRoot, 'pulse'),
- binaryBuildLockPath: path.join(repoRoot, 'tmp', 'locks', 'managed-local-backend-binary.lock'),
+ binaryPath: binaryConfig.binaryPath,
+ binaryBuildLockPath: binaryConfig.binaryBuildLockPath,
+ binaryBuildCwd: binaryConfig.binaryBuildCwd,
+ binaryBuildArgs: binaryConfig.binaryBuildArgs,
+ binarySourceRoots: binaryConfig.binarySourceRoots,
+ binaryManifestPaths: binaryConfig.binaryManifestPaths,
frontendRoot: path.join(repoRoot, 'frontend-modern'),
embeddedFrontendDistPath: path.join(repoRoot, 'internal', 'api', 'frontend-modern', 'dist'),
};
@@ -275,7 +343,9 @@ export async function shouldBuildManagedLocalBackendBinary(state) {
return true;
}
- const sourceRoots = ['cmd', 'internal', 'pkg'].map((segment) => path.join(state.repoRoot, segment));
+ const sourceRoots = Array.isArray(state.binarySourceRoots) && state.binarySourceRoots.length > 0
+ ? state.binarySourceRoots
+ : ['cmd', 'internal', 'pkg'].map((segment) => path.join(state.repoRoot, segment));
let newestSourceMtime = 0;
for (const sourceRoot of sourceRoots) {
newestSourceMtime = Math.max(newestSourceMtime, await collectNewestGoMtime(sourceRoot));
@@ -286,9 +356,13 @@ export async function shouldBuildManagedLocalBackendBinary(state) {
await collectNewestTreeMtime(state.embeddedFrontendDistPath),
);
- for (const manifestName of ['go.mod', 'go.sum']) {
+ const manifestPaths = Array.isArray(state.binaryManifestPaths) && state.binaryManifestPaths.length > 0
+ ? state.binaryManifestPaths
+ : ['go.mod', 'go.sum'].map((manifestName) => path.join(state.repoRoot, manifestName));
+
+ for (const manifestPath of manifestPaths) {
try {
- const manifestStats = await fs.stat(path.join(state.repoRoot, manifestName));
+ const manifestStats = await fs.stat(manifestPath);
newestSourceMtime = Math.max(newestSourceMtime, manifestStats.mtimeMs);
} catch {
// ignore missing manifest files
@@ -328,13 +402,18 @@ async function ensureBackendBinary(state, logger) {
return;
}
- logger.log(`[integration] Building local backend binary at ${state.binaryPath}`);
+ logger.log(`[integration] Building ${state.backendVariant || 'core'} local backend binary at ${state.binaryPath}`);
const temporaryBinaryPath = `${state.binaryPath}.${process.pid}.tmp`;
+ const binaryBuildCwd = state.binaryBuildCwd || state.repoRoot;
+ const binaryBuildArgs = Array.isArray(state.binaryBuildArgs) && state.binaryBuildArgs.length > 0
+ ? state.binaryBuildArgs.map((arg) => (arg === '__OUTPUT__' ? temporaryBinaryPath : arg))
+ : ['build', '-o', temporaryBinaryPath, './cmd/pulse'];
+ await fs.mkdir(path.dirname(temporaryBinaryPath), { recursive: true });
await fs.rm(temporaryBinaryPath, { force: true });
try {
await new Promise((resolve, reject) => {
- const child = spawn('go', ['build', '-o', temporaryBinaryPath, './cmd/pulse'], {
- cwd: state.repoRoot,
+ const child = spawn('go', binaryBuildArgs, {
+ cwd: binaryBuildCwd,
stdio: 'inherit',
});
child.on('error', reject);
@@ -476,6 +555,7 @@ export async function startManagedLocalBackend({
const runtimeState = {
managedLocalBackend: true,
+ backendVariant: state.backendVariant,
baseURL: state.baseURL,
pid: child.pid,
dataDir: state.dataDir,
diff --git a/tests/integration/scripts/managed-local-backend.test.mjs b/tests/integration/scripts/managed-local-backend.test.mjs
index 7d874c6840..cf9f80d906 100644
--- a/tests/integration/scripts/managed-local-backend.test.mjs
+++ b/tests/integration/scripts/managed-local-backend.test.mjs
@@ -14,10 +14,13 @@ import {
test('buildManagedLocalBackendState uses deterministic defaults', () => {
const state = buildManagedLocalBackendState({});
assert.equal(state.repoRoot.endsWith('/repos/pulse'), true);
+ assert.equal(state.backendVariant, 'core');
assert.equal(state.baseURL, 'http://127.0.0.1:8765');
assert.equal(state.metricsPort, '0');
assert.equal(state.billingStatePath, path.join(state.rootDir, 'data', 'billing.json'));
assert.equal(state.binaryPath, path.join(state.repoRoot, 'pulse'));
+ assert.equal(state.binaryBuildCwd, state.repoRoot);
+ assert.deepEqual(state.binaryBuildArgs, ['build', '-o', '__OUTPUT__', './cmd/pulse']);
assert.equal(
state.embeddedFrontendDistPath,
path.join(state.repoRoot, 'internal', 'api', 'frontend-modern', 'dist'),
@@ -35,6 +38,25 @@ test('buildManagedLocalBackendState scopes the working directory by run id', ()
);
});
+test('buildManagedLocalBackendState supports enterprise variant with sibling repo defaults', () => {
+ const state = buildManagedLocalBackendState({
+ PULSE_E2E_LOCAL_BACKEND_VARIANT: 'enterprise',
+ });
+
+ assert.equal(state.backendVariant, 'enterprise');
+ assert.equal(
+ state.binaryPath,
+ path.join(state.repoRoot, 'tmp', 'integration-local-backend', 'bin', 'pulse-enterprise'),
+ );
+ assert.equal(
+ state.binaryBuildCwd,
+ path.join(path.dirname(state.repoRoot), 'pulse-enterprise'),
+ );
+ assert.deepEqual(state.binaryBuildArgs, ['build', '-buildvcs=false', '-o', '__OUTPUT__', './cmd/pulse-enterprise']);
+ assert.ok(state.binarySourceRoots.some((root) => root.endsWith(path.join('pulse-enterprise', 'internal'))));
+ assert.ok(state.binarySourceRoots.some((root) => root.endsWith(path.join('repos', 'pulse', 'internal'))));
+});
+
test('buildManagedLocalBackendEnv seeds auth, bootstrap token, and billing path', () => {
const state = buildManagedLocalBackendState({
PULSE_E2E_LOCAL_BACKEND_PORT: '9001',
@@ -136,6 +158,57 @@ test('shouldBuildManagedLocalBackendBinary skips rebuild when binary is fresh',
);
});
+test('shouldBuildManagedLocalBackendBinary rebuilds enterprise variant when sibling enterprise source is newer', async () => {
+ const workspaceRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'pulse-managed-backend-enterprise-'));
+ const pulseRepoRoot = path.join(workspaceRoot, 'pulse');
+ const enterpriseRepoRoot = path.join(workspaceRoot, 'pulse-enterprise');
+ const binaryPath = path.join(pulseRepoRoot, 'tmp', 'integration-local-backend', 'bin', 'pulse-enterprise');
+ const enterpriseMainPath = path.join(enterpriseRepoRoot, 'cmd', 'pulse-enterprise', 'main.go');
+ const coreMainPath = path.join(pulseRepoRoot, 'cmd', 'pulse', 'main.go');
+ const embeddedIndexPath = path.join(pulseRepoRoot, 'internal', 'api', 'frontend-modern', 'dist', 'index.html');
+
+ await fs.mkdir(path.dirname(enterpriseMainPath), { recursive: true });
+ await fs.mkdir(path.dirname(coreMainPath), { recursive: true });
+ await fs.mkdir(path.dirname(embeddedIndexPath), { recursive: true });
+ await fs.mkdir(path.dirname(binaryPath), { recursive: true });
+ await fs.writeFile(path.join(pulseRepoRoot, 'go.mod'), 'module example.com/pulse\n');
+ await fs.writeFile(path.join(enterpriseRepoRoot, 'go.mod'), 'module example.com/pulse-enterprise\n');
+ await fs.writeFile(enterpriseMainPath, 'package main\n');
+ await fs.writeFile(coreMainPath, 'package main\n');
+ await fs.writeFile(embeddedIndexPath, '<!doctype html>');
+ await fs.writeFile(binaryPath, 'binary');
+
+ const older = new Date('2026-03-12T09:00:00Z');
+ const newer = new Date('2026-03-12T10:00:00Z');
+ await fs.utimes(binaryPath, older, older);
+ await fs.utimes(coreMainPath, older, older);
+ await fs.utimes(embeddedIndexPath, older, older);
+ await fs.utimes(enterpriseMainPath, newer, newer);
+
+ assert.equal(
+ await shouldBuildManagedLocalBackendBinary({
+ repoRoot: pulseRepoRoot,
+ binaryPath,
+ embeddedFrontendDistPath: path.join(pulseRepoRoot, 'internal', 'api', 'frontend-modern', 'dist'),
+ binarySourceRoots: [
+ path.join(enterpriseRepoRoot, 'cmd'),
+ path.join(enterpriseRepoRoot, 'internal'),
+ path.join(enterpriseRepoRoot, 'test'),
+ path.join(pulseRepoRoot, 'cmd'),
+ path.join(pulseRepoRoot, 'internal'),
+ path.join(pulseRepoRoot, 'pkg'),
+ ],
+ binaryManifestPaths: [
+ path.join(enterpriseRepoRoot, 'go.mod'),
+ path.join(enterpriseRepoRoot, 'go.sum'),
+ path.join(pulseRepoRoot, 'go.mod'),
+ path.join(pulseRepoRoot, 'go.sum'),
+ ],
+ }),
+ true,
+ );
+});
+
test('shouldBuildManagedLocalBackendFrontend rebuilds when frontend sources are newer', async () => {
const repoRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'pulse-managed-backend-'));
const frontendRoot = path.join(repoRoot, 'frontend-modern');