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.

Replace Go tests that grep Go source with behaviour tests

rcourtmanee061ee054c5
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
index 030ef5394e..a3cc5df4b2 100644
--- a/internal/ai/chat/service_tooling_test.go
+++ b/internal/ai/chat/service_tooling_test.go
@@ -638,48 +638,6 @@ func TestExecuteAssistantToolUsesSharedResultTextProjection(t *testing.T) {
}
}
-func TestDirectToolExecutionUsesSharedResultExecutionMapping(t *testing.T) {
- src, err := os.ReadFile("service.go")
- if err != nil {
- t.Fatalf("read service.go: %v", err)
- }
- text := string(src)
-
- if !strings.Contains(text, "agentcapabilities.InterpretDirectToolExecution(result") {
- t.Fatalf("direct tool execution must use shared result execution mapping")
- }
- for _, fragment := range []string{
- "func (s *Service) executeAssistantRegistryToolDirect(",
- `outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, agentcapabilities.PulseRunCommandToolName, args, agentcapabilities.DirectToolExecutionOptions{`,
- `outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, toolName, args, agentcapabilities.DirectToolExecutionOptions{`,
- `result, toolErr := executor.ExecuteTool(ctx, toolName, args)`,
- } {
- if !strings.Contains(text, fragment) {
- t.Fatalf("direct Assistant registry execution must use shared service helper; missing %s", fragment)
- }
- }
- if !strings.Contains(text, "strings.TrimSpace(agentcapabilities.ToolResultText(result))") {
- t.Fatalf("direct topology context must use shared result text projection")
- }
- for _, fragment := range []string{
- "agentcapabilities.HasApprovalRequiredToolMarker(resultText)",
- "agentcapabilities.HasPolicyBlockedToolMarker(resultText)",
- "interpreted := agentcapabilities.InterpretToolResult(result)",
- "interpreted := agentcapabilities.InterpretMCPToolResult(result)",
- "if interpreted.IsError",
- "if interpreted.ApprovalRequired",
- "if interpreted.PolicyBlocked",
- "FormatToolResult(result)",
- "agentcapabilities.DirectMCPToolExecutionOptions",
- "agentcapabilities.InterpretDirectMCPToolExecution(result",
- "agentcapabilities.MCPToolResultText(result)",
- } {
- if strings.Contains(text, fragment) {
- t.Fatalf("direct tool execution must not duplicate shared result execution mapping; found %s", fragment)
- }
- }
-}
-
func TestAgenticLoopUsesSharedProviderToolResultConstruction(t *testing.T) {
src, err := os.ReadFile("agentic.go")
if err != nil {
@@ -729,33 +687,6 @@ func TestAgenticLoopUsesSharedProviderToolResultConstruction(t *testing.T) {
}
}
-func TestProviderMessageConversionUsesSharedProviderToolResultConstruction(t *testing.T) {
- src, err := os.ReadFile("agentic_context.go")
- if err != nil {
- t.Fatalf("read agentic_context.go: %v", err)
- }
- text := string(src)
-
- for _, fragment := range []string{
- "projection := newProviderToolResultContextProjection(m.ToolResult.ToolUseID, m.ToolResult.Content, m.ToolResult.IsError)",
- "pm.ToolResult = &projection.Model",
- "agentcapabilities.NewProviderToolErrorResult(",
- } {
- if !strings.Contains(text, fragment) {
- t.Fatalf("provider message conversion must use shared provider tool-result construction; missing %s", fragment)
- }
- }
- for _, forbidden := range []string{
- "func newProviderToolResult(",
- "func newProviderToolErrorResult(",
- "ToolResult: &providers.ToolResult{",
- } {
- if strings.Contains(text, forbidden) {
- t.Fatalf("provider message conversion must not preserve Assistant-local provider-result wrappers or structs; found %s", forbidden)
- }
- }
-}
-
func TestExecuteAssistantTool_PulseStorageSnapshotsToleratesMalformedRecoveryMetadata(t *testing.T) {
completedAt := time.Date(2026, 2, 24, 10, 30, 0, 0, time.UTC)
svc := &Service{
diff --git a/internal/ai/providers/openai_test.go b/internal/ai/providers/openai_test.go
index 29925231c5..e845f7fa05 100644
--- a/internal/ai/providers/openai_test.go
+++ b/internal/ai/providers/openai_test.go
@@ -1033,6 +1033,9 @@ func TestOpenAIClient_Chat_DeepSeekPreservesReasoningContentForToolTurns(t *test
assert.Equal(t, "assistant", got.Messages[1].Role)
assert.Equal(t, "I need current state first.", got.Messages[1].ReasoningContent)
require.Len(t, got.Messages[1].ToolCalls, 1)
+ assert.Equal(t, "tool", got.Messages[2].Role)
+ assert.Equal(t, "call-1", got.Messages[2].ToolCallID)
+ assert.Equal(t, "healthy", got.Messages[2].Content)
_ = json.NewEncoder(w).Encode(openaiResponse{
ID: "chatcmpl-deepseek-reasoning",
@@ -1067,13 +1070,13 @@ func TestOpenAIClient_Chat_DeepSeekPreservesReasoningContentForToolTurns(t *test
}
func TestOpenAIClient_ChatStream_DeepSeekPreservesReasoningContentForToolTurns(t *testing.T) {
+ received := make(chan openaiStreamRequest, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var got openaiStreamRequest
- require.NoError(t, json.NewDecoder(r.Body).Decode(&got))
- require.Len(t, got.Messages, 3)
- assert.Equal(t, "assistant", got.Messages[1].Role)
- assert.Equal(t, "I need current state first.", got.Messages[1].ReasoningContent)
- require.Len(t, got.Messages[1].ToolCalls, 1)
+ if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+ t.Errorf("decode stream request: %v", err)
+ }
+ received <- got
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
@@ -1100,6 +1103,15 @@ func TestOpenAIClient_ChatStream_DeepSeekPreservesReasoningContentForToolTurns(t
},
}, func(event StreamEvent) {})
require.NoError(t, err)
+
+ got := <-received
+ require.Len(t, got.Messages, 3)
+ assert.Equal(t, "assistant", got.Messages[1].Role)
+ assert.Equal(t, "I need current state first.", got.Messages[1].ReasoningContent)
+ require.Len(t, got.Messages[1].ToolCalls, 1)
+ assert.Equal(t, "tool", got.Messages[2].Role)
+ assert.Equal(t, "call-1", got.Messages[2].ToolCallID)
+ assert.Equal(t, "healthy", got.Messages[2].Content)
}
func TestOpenAIClient_ChatStream_Errors(t *testing.T) {
diff --git a/internal/ai/providers/provider_contract_test.go b/internal/ai/providers/provider_contract_test.go
index 54be576042..de630245d7 100644
--- a/internal/ai/providers/provider_contract_test.go
+++ b/internal/ai/providers/provider_contract_test.go
@@ -83,141 +83,12 @@ func TestProviderContracts_UseCanonicalEmptyCollections(t *testing.T) {
}
func TestProviderContracts_StreamToolInputParsingUsesSharedAgentCapabilities(t *testing.T) {
- for _, path := range []string{"openai.go", "anthropic.go"} {
- source, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("read %s: %v", path, err)
- }
- text := string(source)
- for _, fragment := range []string{
- "agentcapabilities.ParseProviderToolInput(",
- "agentcapabilities.ProviderToolInputOrRaw(",
- } {
- if !strings.Contains(text, fragment) {
- t.Fatalf("%s must use shared provider tool input parsing; missing %s", path, fragment)
- }
- }
- for _, forbidden := range []string{
- `map[string]interface{}{"raw":`,
- `json.Unmarshal([]byte(currentToolInput.String())`,
- `json.Unmarshal([]byte(builder.args.String())`,
- } {
- if strings.Contains(text, forbidden) {
- t.Fatalf("%s must not own provider tool input fallback parsing; found %s", path, forbidden)
- }
- }
- }
-
- providerSource, err := os.ReadFile("provider.go")
- if err != nil {
- t.Fatalf("read provider.go: %v", err)
- }
- if strings.Contains(string(providerSource), "func parseStreamToolInput(") {
- t.Fatal("provider package must not keep a local streamed tool-input parser")
- }
-
parsed, ok := agentcapabilities.ParseProviderToolInput(`{"host":"nas01"}`)
if !ok || parsed["host"] != "nas01" {
t.Fatalf("shared parser returned %#v, %v", parsed, ok)
}
}
-func TestProviderContracts_AnthropicStreamingUsesSharedMessageProjection(t *testing.T) {
- source, err := os.ReadFile("anthropic.go")
- if err != nil {
- t.Fatalf("read anthropic.go: %v", err)
- }
- text := string(source)
-
- if strings.Count(text, "convertMessagesToAnthropic(req.Messages)") != 2 {
- t.Fatal("Anthropic Chat and ChatStream must both use convertMessagesToAnthropic for provider message projection")
- }
-
- streamStart := strings.Index(text, "func (c *AnthropicClient) ChatStream(")
- if streamStart < 0 {
- t.Fatal("missing Anthropic ChatStream")
- }
- streamText := text[streamStart:]
- for _, forbidden := range []string{
- `json.Marshal(m.ToolResult.Content)`,
- `Type: "tool_result"`,
- `Type: "tool_use"`,
- `Content: m.Content`,
- } {
- if strings.Contains(streamText, forbidden) {
- t.Fatalf("Anthropic ChatStream must not duplicate provider message projection; found %s", forbidden)
- }
- }
-}
-
-func TestProviderContracts_OpenAIStreamingUsesSharedMessageProjection(t *testing.T) {
- source, err := os.ReadFile("openai.go")
- if err != nil {
- t.Fatalf("read openai.go: %v", err)
- }
- text := string(source)
-
- if strings.Count(text, "convertMessagesToOpenAI(req, c.shouldSendReasoningContent())") != 2 {
- t.Fatal("OpenAI Chat and ChatStream must both use convertMessagesToOpenAI for provider message projection")
- }
-
- streamStart := strings.Index(text, "func (c *OpenAIClient) ChatStream(")
- if streamStart < 0 {
- t.Fatal("missing OpenAI ChatStream")
- }
- streamText := text[streamStart:]
- modelStart := strings.Index(streamText, "model := req.Model")
- if modelStart < 0 {
- t.Fatal("missing OpenAI ChatStream model setup")
- }
- streamProjectionText := streamText[:modelStart]
- for _, forbidden := range []string{
- `json.Marshal(tc.Input)`,
- `m.ToolResult`,
- `m.ToolCalls`,
- `m.ReasoningContent`,
- `m.Content`,
- } {
- if strings.Contains(streamProjectionText, forbidden) {
- t.Fatalf("OpenAI ChatStream must not duplicate provider message projection; found %s", forbidden)
- }
- }
-}
-
-func TestProviderContracts_GeminiStreamingUsesSharedMessageProjection(t *testing.T) {
- source, err := os.ReadFile("gemini.go")
- if err != nil {
- t.Fatalf("read gemini.go: %v", err)
- }
- text := string(source)
-
- if strings.Count(text, "convertMessagesToGemini(req.Messages)") != 2 {
- t.Fatal("Gemini Chat and ChatStream must both use convertMessagesToGemini for provider message projection")
- }
-
- streamStart := strings.Index(text, "func (c *GeminiClient) ChatStream(")
- if streamStart < 0 {
- t.Fatal("missing Gemini ChatStream")
- }
- streamText := text[streamStart:]
- modelStart := strings.Index(streamText, "model := req.Model")
- if modelStart < 0 {
- t.Fatal("missing Gemini ChatStream model setup")
- }
- streamProjectionText := streamText[:modelStart]
- for _, forbidden := range []string{
- `m.ToolResult`,
- `m.ToolCalls`,
- `m.Content`,
- `FunctionResponse:`,
- `FunctionCall:`,
- } {
- if strings.Contains(streamProjectionText, forbidden) {
- t.Fatalf("Gemini ChatStream must not duplicate provider message projection; found %s", forbidden)
- }
- }
-}
-
func TestProviderToolUsesSharedAgentCapabilitiesShape(t *testing.T) {
var shared agentcapabilities.ProviderTool = Tool{
Name: "diagnose",
diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.go
index dc0591460a..ebf9e21335 100644
--- a/internal/api/ai_handlers_test.go
+++ b/internal/api/ai_handlers_test.go
@@ -55,17 +55,6 @@ func saveEnabledTestAIConfig(t *testing.T, persistence *config.ConfigPersistence
require.NoError(t, persistence.SaveAIConfig(*aiCfg))
}
-func TestAIHandlersUseSafeRemediationCommercialCopy(t *testing.T) {
- files := []string{"ai_handlers.go", "router_routes_ai_relay.go"}
- for _, file := range files {
- source, err := os.ReadFile(file)
- require.NoError(t, err)
- text := string(source)
- require.NotContains(t, text, "Pulse Patrol Auto-Fix requires Pulse Pro")
- require.NotContains(t, text, "Auto-Fix requires Pulse Pro")
- }
-}
-
func TestOrchestratorChatAdapterCarriesTypedInvestigationScope(t *testing.T) {
source, err := os.ReadFile("ai_handlers.go")
require.NoError(t, err)
@@ -120,51 +109,6 @@ func TestAISettingsHandler_AnthropicOAuthSetupFailsClosed(t *testing.T) {
}
}
-func TestAIHandlersDelegateApprovedToolInvocationParsingToSharedCapabilities(t *testing.T) {
- source, err := os.ReadFile("ai_handlers.go")
- require.NoError(t, err)
- aiHandlers := string(source)
- for _, fragment := range []string{
- "isMCPToolCall",
- "parseMCPToolCall",
- "splitToolArgs",
- } {
- require.NotContains(t, aiHandlers, fragment)
- }
-
- source, err = os.ReadFile("router_routes_ai_relay.go")
- require.NoError(t, err)
- relay := string(source)
- require.Contains(t, relay, "agentcapabilities.ParseTextToolInvocation(command)")
- require.NotContains(t, relay, "func parseMCPToolCall(")
- require.NotContains(t, relay, "func splitToolArgs(")
- require.NotContains(t, relay, "func isMCPToolCall(")
-}
-
-func TestAIHandlersUseSharedPatrolFindingAgentErrorCodes(t *testing.T) {
- source, err := os.ReadFile("ai_handlers.go")
- require.NoError(t, err)
- aiHandlers := string(source)
-
- for _, constant := range []string{
- "agentcapabilities.AgentErrCodePatrolUnavailable",
- "agentcapabilities.AgentErrCodeInvalidFindingRequest",
- "agentcapabilities.AgentErrCodeFindingNotFound",
- "agentcapabilities.AgentErrCodeFindingActionNotAllowed",
- } {
- require.Contains(t, aiHandlers, constant)
- }
-
- for _, literal := range []string{
- `writeJSONError(w, http.StatusServiceUnavailable, "` + agentcapabilities.AgentErrCodePatrolUnavailable + `"`,
- `writeJSONErrorWithDetails(w, http.StatusBadRequest, "` + agentcapabilities.AgentErrCodeInvalidFindingRequest + `"`,
- `writeJSONError(w, http.StatusNotFound, "` + agentcapabilities.AgentErrCodeFindingNotFound + `"`,
- `writeJSONError(w, http.StatusConflict, "` + agentcapabilities.AgentErrCodeFindingActionNotAllowed + `"`,
- } {
- require.NotContains(t, aiHandlers, literal)
- }
-}
-
func TestAISettingsHandler_PatrolFindingLifecycleUsesAgentStableUnavailableEnvelope(t *testing.T) {
tmp := t.TempDir()
cfg := &config.Config{DataPath: tmp}
@@ -3059,18 +3003,6 @@ func TestHandleInvestigateAlert_AcceptsCanonicalAlertIdentifier(t *testing.T) {
require.NotContains(t, rec.Header().Get("Content-Type"), "text/event-stream")
}
-func TestHandleInvestigateAlert_ForcesApprovalBoundExecuteRequest(t *testing.T) {
- t.Parallel()
-
- source, err := os.ReadFile("ai_handlers.go")
- require.NoError(t, err)
- text := string(source)
-
- require.Contains(t, text, "autonomousMode := false")
- require.Contains(t, text, "AutonomousMode: &autonomousMode")
- require.Contains(t, text, "RequireCommandApproval: true")
-}
-
func TestHandleInvestigateAlert_UsesVisibleIdleProgressStream(t *testing.T) {
setMockModeForTest(t, true)
withLegacyAssistantStreamIdleInterval(t, 2*time.Millisecond)
@@ -3669,21 +3601,6 @@ func TestAISettingsHandler_PatrolPreflight_RejectsInvalidProviderName(t *testing
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
-func TestAISettingsHandler_PatrolPreflight_DelegatesDeadlineToAIRuntime(t *testing.T) {
- source, err := os.ReadFile("ai_handlers.go")
- require.NoError(t, err)
- text := string(source)
- start := strings.Index(text, "func (h *AISettingsHandler) HandlePatrolPreflight(")
- require.NotEqual(t, -1, start)
- end := strings.Index(text[start:], "\nfunc ")
- if end < 0 {
- end = len(text) - start
- }
- body := text[start : start+end]
- require.Contains(t, body, "RunPatrolToolPreflight(r.Context(), body.Provider, body.Model)")
- require.NotContains(t, body, "context.WithTimeout")
-}
-
func TestAISettingsHandler_PatrolModelReadiness_MethodNotAllowed(t *testing.T) {
t.Parallel()
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 35a91325bb..f0b3cf55af 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -1294,21 +1294,6 @@ func TestContract_MockAvailabilityTargetsUseSavedTargetPayloads(t *testing.T) {
}
}
-func TestPatrolRemediationCommercialCopyUsesSafeRemediationWording(t *testing.T) {
- files := []string{"ai_handlers.go", "router_routes_ai_relay.go"}
- for _, file := range files {
- source, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("read %s: %v", file, err)
- }
- text := string(source)
- if strings.Contains(text, "Pulse Patrol Auto-Fix requires Pulse Pro") ||
- strings.Contains(text, "Auto-Fix requires Pulse Pro") {
- t.Fatalf("%s must not expose legacy Auto-Fix license copy", file)
- }
- }
-}
-
func TestContract_PatrolAutonomyCommunityMonitorUpdatePayload(t *testing.T) {
rawToken := "patrol-autonomy-contract-token-123.12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsWrite}, nil)
@@ -1355,347 +1340,6 @@ func TestContract_PatrolAutonomyCommunityMonitorUpdatePayload(t *testing.T) {
}
}
-func TestContract_AssistantFindingContextUsesModelOnlyHandoff(t *testing.T) {
- handlerSource, err := os.ReadFile(filepath.Clean("ai_handler.go"))
- if err != nil {
- t.Fatalf("read ai_handler.go: %v", err)
- }
- settingsHandlerSource, err := os.ReadFile(filepath.Clean("ai_handlers.go"))
- if err != nil {
- t.Fatalf("read ai_handlers.go: %v", err)
- }
- chatServiceSource, err := os.ReadFile(filepath.Clean("../ai/chat/service.go"))
- if err != nil {
- t.Fatalf("read chat service: %v", err)
- }
- chatSessionSource, err := os.ReadFile(filepath.Clean("../ai/chat/session.go"))
- if err != nil {
- t.Fatalf("read chat session store: %v", err)
- }
- chatTypesSource, err := os.ReadFile(filepath.Clean("../ai/chat/types.go"))
- if err != nil {
- t.Fatalf("read chat types: %v", err)
- }
- patrolHandoffSource, err := os.ReadFile(filepath.Clean("../ai/patrol_assistant_handoff.go"))
- if err != nil {
- t.Fatalf("read Patrol Assistant handoff model: %v", err)
- }
- toolsQuerySource, err := os.ReadFile(filepath.Clean("../ai/tools/tools_query.go"))
- if err != nil {
- t.Fatalf("read AI tools query runtime: %v", err)
- }
-
- handlerText := string(handlerSource)
- for _, required := range []string{
- "requestSuppliedSessionID := requestSessionID != \"\"",
- `if findingID == "" && requestSuppliedSessionID`,
- `svc.GetModelHandoffFindingID(ctx, requestSessionID)`,
- `svc.GetModelHandoffMetadata(ctx, requestSessionID)`,
- `if requestSuppliedSessionID`,
- `svc.ClearModelHandoffContext(ctx, requestSessionID)`,
- `HandoffActions []chat.HandoffAction ` + "`json:\"handoff_actions,omitempty\"`",
- `HandoffMetadata chat.HandoffMetadata ` + "`json:\"handoff_metadata,omitempty\"`",
- "handoffActions := normalizeChatRequestHandoffActions(req.HandoffActions)",
- "handoffMetadata := chat.NormalizeHandoffMetadata(req.HandoffMetadata)",
- "storedMetadata = chat.NormalizeHandoffMetadata(storedMetadata)",
- `if storedMetadata.Kind == "patrol_run"`,
- "handoffMetadata = storedMetadata",
- "h.getPatrolRunForHandoff(ctx, handoffMetadata.RunID)",
- "airuntime.BuildPatrolRunAssistantHandoff(run)",
- "chatRequestHandoffActionLimit",
- "requestHandoffContext := handoffContext",
- "requestHandoffResources := handoffResources",
- "requestHandoffActions := handoffActions",
- "handoffActions = mergeUnifiedFindingRequestHandoffActions(f, buildUnifiedFindingHandoffActions(f, orgID), requestHandoffActions)",
- "handoffContext = mergeUnifiedFindingRequestHandoffContext(buildUnifiedFindingChatContext(f, store, handoffActions), requestHandoffContext, f.ID)",
- "handoffResources = mergeUnifiedFindingRequestHandoffResources(f, buildUnifiedFindingHandoffResources(f, store), requestHandoffResources)",
- "safePatrolFindingRequestHandoffContext",
- "Product Handoff Boundary",
- "livePatrolApprovalForFinding(f.ID, orgID)",
- "chat.HydrateHandoffActionFromApproval(&action, liveApproval)",
- "ApprovalRequestedAt",
- "ApprovalExpiresAt",
- "func chatAutonomousModeForFindingHandoff(requested *bool, findingID, handoffContext string, handoffResources []chat.HandoffResource, handoffActions []chat.HandoffAction, handoffMetadata chat.HandoffMetadata) *bool",
- `if strings.TrimSpace(findingID) != ""`,
- "chatApprovalRequiredAutonomousMode()",
- "autonomousMode := chatAutonomousModeForFindingHandoff(nil, findingID, handoffContext, handoffResources, handoffActions, handoffMetadata)",
- "if assistantApprovalBoundExecuteAuthority(ctx) {",
- "autonomousMode = chatApprovalRequiredAutonomousMode()",
- "AutonomousMode: autonomousMode",
- `appendChatContextLine(&b, "Finding Status", unifiedFindingChatStatus(f, time.Now()))`,
- `appendChatContextLine(&b, "Finding Detected At", f.DetectedAt.Format(time.RFC3339))`,
- `appendChatContextLine(&b, "Finding Last Seen At", f.LastSeenAt.Format(time.RFC3339))`,
- `appendChatContextLine(&b, "Finding Resolved At", f.ResolvedAt.Format(time.RFC3339))`,
- `appendChatContextLine(&b, "Finding Snoozed Until", f.SnoozedUntil.Format(time.RFC3339))`,
- `appendChatContextLine(&b, "Finding Dismissed Reason", f.DismissedReason)`,
- `appendChatContextLine(&b, "Finding Suppressed", "true")`,
- `appendChatContextLine(&b, "Finding Times Raised", strconv.Itoa(f.TimesRaised))`,
- `appendChatContextLine(&b, "AI Context", f.AIContext)`,
- `appendChatContextLine(&b, "Root Cause ID", f.RootCauseID)`,
- `appendStringListChatContext(&b, "Correlated Finding", f.CorrelatedIDs)`,
- "appendUnifiedFindingRelatedContext(&b, f, lookup)",
- "[Related Finding Context]",
- "Related Finding Boundary",
- "formatUnifiedFindingBriefingRecency(f)",
- "latest lifecycle",
- `appendChatContextLine(&b, "Remediation ID", f.RemediationID)`,
- `appendChatContextLine(&b, "Last Investigated At", f.LastInvestigatedAt.Format(time.RFC3339))`,
- `appendChatContextLine(&b, "Investigation Attempts", strconv.Itoa(f.InvestigationAttempts))`,
- `appendChatContextLine(&b, "Loop State", f.LoopState)`,
- `appendChatContextLine(&b, "Regression Count", strconv.Itoa(f.RegressionCount))`,
- `appendChatContextLine(&b, "Last Regression At", f.LastRegressionAt.Format(time.RFC3339))`,
- "appendUnifiedFindingLifecycleEventContext(&b, f.Lifecycle)",
- "formatUnifiedFindingLatestLifecycleEvent(f.Lifecycle)",
- "[Finding Lifecycle Context]",
- "Lifecycle Boundary",
- "appendUnifiedFindingModelBriefingContext(&b, f, handoffActions)",
- "[Finding Briefing]",
- `appendChatContextLine(b, "Recency", formatUnifiedFindingBriefingRecencyFacts(f))`,
- "formatUnifiedFindingBriefingRecencyFacts(f)",
- `appendChatContextLine(b, "Evidence Snapshot", evidence)`,
- `appendChatContextLine(b, "Verification", verification)`,
- "formatInvestigationRecordEvidenceBriefing",
- "formatBriefingStringList",
- `appendChatContextLine(b, "Governed Action Context", actionContext)`,
- "unifiedFindingBriefingActionContext(f, handoffActions)",
- "unifiedFindingPrimaryHandoffAction(f, handoffActions)",
- "Latest Lifecycle Event",
- "Model Boundary",
- `return "suppressed"`,
- "Prompt:",
- "HandoffContext: handoffContext",
- "HandoffResources: handoffResources",
- "HandoffActions: handoffActions",
- "HandoffMetadata: handoffMetadata",
- "SuppressSessionEvent: true",
- } {
- if !strings.Contains(handlerText, required) {
- t.Fatalf("ai_handler.go must preserve model-only finding handoff contract: missing %q", required)
- }
- }
- if strings.Contains(handlerText, "prompt = findingCtx +") {
- t.Fatal("ai_handler.go must not prepend finding context into the persisted prompt")
- }
- for _, forbidden := range []string{
- "Recommended Next Step",
- "unifiedFindingBriefingNextStep",
- } {
- if strings.Contains(handlerText, forbidden) {
- t.Fatalf("ai_handler.go must not synthesize product-authored handoff recommendations: found %q", forbidden)
- }
- }
-
- settingsHandlerText := string(settingsHandlerSource)
- // Gofmt aligns keyed fields with their neighbours. Wiring checks must not
- // fail merely because adding or removing another field changes that padding.
- settingsHandlerWiring := strings.Join(strings.Fields(settingsHandlerText), " ")
- // Patrol remediation now enters as a typed action proposal through the
- // required action broker; the investigation adapter carries no
- // command execution, no autonomy, and no command-shaped approval
- // seeding.
- for _, required := range []string{
- "ActionBroker: h.actionBrokerFor(approval.NormalizeOrgID(orgID))",
- "catalog: h.proposalCatalogFor(orgID)",
- "func (a *orchestratorChatAdapter) ExecuteInvestigationStream(",
- "MaxEvidenceCalls: req.MaxEvidenceCalls",
- "ResourceType: req.ResourceType",
- "ModelTurns: runResult.ModelTurns",
- "EvidenceCalls: runResult.EvidenceCalls",
- } {
- if !strings.Contains(settingsHandlerWiring, strings.Join(strings.Fields(required), " ")) {
- t.Fatalf("ai_handlers.go must wire the typed investigation proposal channel: missing %q", required)
- }
- }
- for _, forbidden := range []string{
- "func (a *orchestratorChatAdapter) ExecuteStream(",
- "func (a *orchestratorChatAdapter) SetAutonomousMode(",
- "func (a *orchestratorChatAdapter) ExecuteCommand(",
- "orchestratorApprovalAdapter",
- "autonomyLevelProviderAdapter",
- "patrolFixVerifierAdapter",
- } {
- if strings.Contains(settingsHandlerText, forbidden) {
- t.Fatalf("ai_handlers.go must not retain a retired command/autonomy adapter: found %q", forbidden)
- }
- }
-
- patrolHandoffText := string(patrolHandoffSource)
- for _, required := range []string{
- "func BuildPatrolRunAssistantHandoff(run PatrolRunRecord) PatrolRunAssistantHandoff",
- "[Patrol Run Context]",
- "Source: Pulse Patrol run history",
- "patrolRunAssistantHandoffResources",
- "sanitizePatrolRunAnalysis",
- "Model Boundary",
- } {
- if !strings.Contains(patrolHandoffText, required) {
- t.Fatalf("Patrol runtime must own safe Assistant run handoff context: missing %q", required)
- }
- }
-
- chatServiceText := string(chatServiceSource)
- for _, required := range []string{
- "handoffContext := strings.TrimSpace(req.HandoffContext)",
- "handoffFindingID := strings.TrimSpace(req.FindingID)",
- "handoffMetadata := NormalizeHandoffMetadata(req.HandoffMetadata)",
- "handoffMetadataCarriesEnvelope",
- "handoffMetadata.Kind == sessionHandoffKindResourceContext",
- "hasRequestHandoffEnvelope",
- "sessions.SetModelHandoffEnvelope(session.ID, handoffFindingID, handoffContext, handoffResources, handoffActions, handoffMetadata)",
- "ClearModelHandoffContext",
- "handoffResources := normalizeHandoffResources(req.HandoffResources)",
- "GetModelHandoffFindingID",
- "GetModelHandoffMetadata",
- "sessions.GetModelHandoffEnvelope(session.ID)",
- "handoffContext = storedContext",
- "handoffResources = storedResources",
- "sessions.SetModelHandoffActions(session.ID, handoffActions)",
- "handoffActions = storedActions",
- "GetActionAuditStore",
- "refreshHandoffActionStatus(handoffActions, s.orgID, s.actionAuditStore)",
- "HydrateHandoffActionFromApproval(&actions[idx], req)",
- "func HydrateHandoffActionFromApproval(action *HandoffAction, req *approval.ApprovalRequest)",
- "approval.RequesterForRequest(req)",
- "action.ActionRequestedBy = requestedBy",
- "mergeHandoffResourcePolicyContext(handoffContext, handoffResources, handoffResourceProvider)",
- "mergeHandoffResourceStateContext(handoffContext, handoffResources, handoffResourceProvider)",
- "mergeHandoffResourceRelationshipContext(handoffContext, handoffResources, handoffResourceProvider)",
- "mergeHandoffResourceTimelineContext(handoffContext, handoffResources, handoffResourceProvider, s.actionAuditStore, time.Now())",
- "handoffContext = mergeHandoffActionContext(handoffContext, handoffActions)",
- "sanitizeHandoffContextForResourcePolicy(handoffContext, handoffResources, handoffResourceProvider)",
- "Action Reference",
- "Action State",
- "Action Plan Expires At",
- "Action Dry Run Summary",
- "Action Result",
- "s.hydrateHandoffResources(session.ID, handoffResources, sessions, unifiedResourceProvider)",
- "injectHandoffContextIntoLatestUserMessage(messages, handoffContext)",
- "Resource Policy Context",
- "Policy Boundary",
- "Resource State Context",
- "labelPrefix+\" Status\"",
- "labelPrefix+\" Capabilities\"",
- "Resource State Boundary",
- "Resource Relationship Context",
- "Relationship Boundary",
- "Timeline Boundary",
- "Approval Status",
- "Action Boundary",
- "User message: ",
- } {
- if !strings.Contains(chatServiceText, required) {
- t.Fatalf("chat service must inject handoff context into model-only turn: missing %q", required)
- }
- }
-
- chatSessionText := string(chatSessionSource)
- if !regexp.MustCompile(`ModelContext\s+\*sessionModelContext`).MatchString(chatSessionText) {
- t.Fatalf("chat session store must persist model-only handoff metadata outside messages: missing %q", "ModelContext *sessionModelContext")
- }
- for _, required := range []string{
- "SetModelHandoffFindingID",
- "SetModelHandoffEnvelope",
- "GetModelHandoffFindingID",
- "GetModelHandoffMetadata",
- "ClearModelHandoffContext",
- "HandoffFindingID string",
- "SetModelHandoffContext",
- "GetModelHandoffContext",
- "GetModelHandoffEnvelope",
- "SetModelHandoffResources",
- "GetModelHandoffResources",
- "HandoffResources []HandoffResource",
- "SetModelHandoffActions",
- "GetModelHandoffActions",
- "HandoffActions []HandoffAction",
- "SetModelHandoffMetadata",
- "HandoffMetadata HandoffMetadata",
- } {
- if !strings.Contains(chatSessionText, required) {
- t.Fatalf("chat session store must persist model-only handoff metadata outside messages: missing %q", required)
- }
- }
-
- chatTypesText := string(chatTypesSource)
- for _, required := range []string{
- "type HandoffResource struct",
- "HandoffResources []HandoffResource",
- "type HandoffAction struct",
- "HandoffActions []HandoffAction",
- "type HandoffMetadata struct",
- "HandoffMetadata HandoffMetadata",
- "ApprovalStatus",
- "ActionID",
- "ActionState",
- "ActionRequestedBy",
- "ActionPlanExpiresAt",
- "ActionDryRunSummary",
- "ActionResult",
- } {
- if !strings.Contains(chatTypesText, required) {
- t.Fatalf("chat request must carry structured handoff resource scope outside messages: missing %q", required)
- }
- }
-
- toolsQueryText := string(toolsQuerySource)
- if !strings.Contains(toolsQueryText, "func CanonicalHandoffResourceRegistration(provider UnifiedResourceProvider") {
- t.Fatal("AI tools runtime must own canonical handoff resource registration")
- }
- if !strings.Contains(toolsQueryText, "func CanonicalHandoffUnifiedResource(provider UnifiedResourceProvider") {
- t.Fatal("AI tools runtime must own canonical handoff unified resource resolution")
- }
-}
-
-func TestContract_AssistantMessageHistoryUsesClientSafeProjection(t *testing.T) {
- handlerSource, err := os.ReadFile(filepath.Clean("ai_handler.go"))
- if err != nil {
- t.Fatalf("read ai_handler.go: %v", err)
- }
- serviceSource, err := os.ReadFile(filepath.Clean("../ai/chat/service.go"))
- if err != nil {
- t.Fatalf("read chat service: %v", err)
- }
- typesSource, err := os.ReadFile(filepath.Clean("../ai/chat/types.go"))
- if err != nil {
- t.Fatalf("read chat types: %v", err)
- }
-
- handlerText := string(handlerSource)
- for _, required := range []string{
- "func (h *AIHandler) HandleMessages(w http.ResponseWriter, r *http.Request, sessionID string)",
- "messages[i] = messages[i].ClientSafe()",
- "json.NewEncoder(w).Encode(messages)",
- } {
- if !strings.Contains(handlerText, required) {
- t.Fatalf("Assistant message-history handler must encode client-safe transcript projection: missing %q", required)
- }
- }
-
- serviceText := string(serviceSource)
- for _, required := range []string{
- "func (s *Service) GetMessages(ctx context.Context, sessionID string) ([]Message, error)",
- "messages[i] = messages[i].ClientSafe()",
- } {
- if !strings.Contains(serviceText, required) {
- t.Fatalf("chat service message-history reads must return client-safe transcript projection: missing %q", required)
- }
- }
-
- typesText := string(typesSource)
- for _, required := range []string{
- "func (m Message) ClientSafe() Message",
- "m = m.NormalizeCollections()",
- `if strings.EqualFold(m.Role, "assistant")`,
- "m.Content = cleanToolCallArtifacts(m.Content)",
- `m.ReasoningContent = ""`,
- "return m",
- } {
- if !strings.Contains(typesText, required) {
- t.Fatalf("chat message client-safe projection must strip hidden reasoning and raw tool-call prose: missing %q", required)
- }
- }
-}
-
func TestContract_InvestigateAlertIsApprovalBound(t *testing.T) {
source, err := os.ReadFile(filepath.Clean("ai_handlers.go"))
if err != nil {
@@ -3689,41 +3333,6 @@ func TestContract_WorkloadChartsUseCanonicalWorkloadIDsForProviderBackedVMs(t *t
}
}
-func TestContract_WorkloadChartMetricBudgetGuardrailsRemainCanonical(t *testing.T) {
- data, err := os.ReadFile("chartapi/service.go")
- if err != nil {
- t.Fatalf("failed to read chartapi/service.go: %v", err)
- }
- source := string(data)
-
- requiredSnippets := []string{
- `var workloadSummaryMetricOrder = []string{`,
- `"cpu",`,
- `"memory",`,
- `"disk",`,
- `"netin",`,
- `"netout",`,
- `var workloadChartsBatchWG sync.WaitGroup`,
- `workloadChartsBatchWG.Add(4)`,
- `podBatchMetrics = monitor.GetGuestMetricsForChartBatch("k8s", podRequests, duration, workloadSummaryMetricOrder...)`,
- `vmBatchMetrics = monitor.GetGuestMetricsForChartBatch("vm", vmRequests, duration, guestSparklineMetricOrder...)`,
- `containerBatchMetrics = monitor.GetGuestMetricsForChartBatch("container", containerRequests, duration, guestSparklineMetricOrder...)`,
- `dockerContainerBatchMetrics = monitor.GetGuestMetricsForChartBatch("dockerContainer", dockerContainerRequests, duration, infrastructureSummaryMetricOrder...)`,
- `summaryChartsCacheTTL = 5 * time.Second`,
- `infrastructureChartsCacheKey(req *http.Request, timeRange string, requestedMetricNames []string) string`,
- `cachedInfrastructureChartsPayload`,
- `cacheInfrastructureChartsPayload`,
- `chartPayloadCacheMaxEntries = 64`,
- `chartPayloadCacheMaxBytes = 16 << 20`,
- `chartPayloads boundedChartPayloadCache`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("chartapi/service.go must contain %q", snippet)
- }
- }
-}
-
func TestContract_GenerateStyledMockSeries_UsesTimestampBasedCurve(t *testing.T) {
now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC).UnixMilli()
@@ -9003,17 +8612,6 @@ func TestContract_SelfHostedCommunityRuntimeCapabilitiesJSONSnapshot(t *testing.
assertJSONSnapshot(t, got, want)
}
-func TestContract_LicenseHandlersPassRuntimeIdentityToActivationService(t *testing.T) {
- source, err := os.ReadFile("licensing_handlers.go")
- if err != nil {
- t.Fatalf("read licensing_handlers.go: %v", err)
- }
- text := string(source)
- if count := strings.Count(text, "SetRuntimeIdentity(h.currentRuntimeIdentity())"); count < 2 {
- t.Fatalf("expected cached and new tenant services to receive runtime identity, count=%d", count)
- }
-}
-
func TestContract_EntitlementPayloadMonitoredSystemUsageUnavailableJSONSnapshot(t *testing.T) {
payload := buildEntitlementPayloadWithUsage(&licenseStatus{
Valid: true,
@@ -14667,50 +14265,6 @@ func TestContract_AssistantChatStreamUsesClientSafeProjection(t *testing.T) {
}
}
-func TestContract_AssistantMockModeRuntimeUsesEffectiveConfig(t *testing.T) {
- handlerSource, err := os.ReadFile(filepath.Clean("ai_handler.go"))
- if err != nil {
- t.Fatalf("read ai_handler.go: %v", err)
- }
- mockStreamSource, err := os.ReadFile(filepath.Clean("../ai/chat/mock_stream.go"))
- if err != nil {
- t.Fatalf("read chat mock stream: %v", err)
- }
-
- handlerText := string(handlerSource)
- for _, required := range []string{
- "func aiChatRuntimeConfigForMockMode(cfg *config.AIConfig) *config.AIConfig",
- "mockmode.IsEnabled()",
- "next.Enabled = true",
- "latestCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(ctx))",
- "aiCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(tenantCtx))",
- "aiCfg = aiChatRuntimeConfigForMockMode(aiCfg)",
- "newCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(ctx))",
- } {
- if !strings.Contains(handlerText, required) {
- t.Fatalf("Assistant mock-mode runtime config must stay effective-only and cover startup/sync paths: missing %q", required)
- }
- }
-
- mockStreamText := string(mockStreamSource)
- for _, required := range []string{
- "var mockAssistantStreamPace =",
- "func pauseMockAssistantStream(ctx context.Context) bool",
- "time.NewTimer(mockAssistantStreamPace)",
- "pauseMockAssistantStream(ctx)",
- "Reading synthetic Pulse inventory.",
- "Summarizing mock inventory result.",
- "Reading mock device inventory.",
- "Summarizing mock device count.",
- "mockAssistantReadToolName",
- "Composing mock Assistant response.",
- } {
- if !strings.Contains(mockStreamText, required) {
- t.Fatalf("Assistant mock stream must pace browser-visible status/tool/content proof: missing %q", required)
- }
- }
-}
-
func TestContract_PushNotificationJSONSnapshots(t *testing.T) {
cases := []struct {
name string
@@ -19283,28 +18837,6 @@ func TestContract_AgentEventsStreamPublishesOnApprovalPending(t *testing.T) {
}
}
-// TestContract_ApprovalStorePostCreateCallback pins the seam the
-// SSE bridge depends on. The approval store must expose a
-// SetOnApprovalCreated setter and CreateApproval must dispatch the
-// callback on its own goroutine after the approval is persisted.
-// Removing or in-lining the callback breaks the bridge silently.
-func TestContract_ApprovalStorePostCreateCallback(t *testing.T) {
- source, err := os.ReadFile("../ai/approval/store.go")
- if err != nil {
- t.Fatalf("read approval/store.go: %v", err)
- }
- src := string(source)
- if !strings.Contains(src, "func (s *Store) SetOnApprovalCreated(cb func(*ApprovalRequest))") {
- t.Error("approval store must expose SetOnApprovalCreated so the API layer can bridge approval creation into the agent SSE stream")
- }
- if !strings.Contains(src, "if cb := s.onApprovalCreated; cb != nil {") {
- t.Error("CreateApproval must check the post-create callback under lock and dispatch it; drift here drops approval.pending events")
- }
- if !strings.Contains(src, "go cb(&snapshot)") {
- t.Error("post-create callback must run on its own goroutine to keep the approval hot path off any consumer's slowness")
- }
-}
-
// TestContract_AgentEventApprovalPendingKindIsStable pins the
// wire-stable event kind string. Renaming AgentEventApprovalPending
// breaks every agent that branches on the SSE event-type field; the
@@ -19569,21 +19101,6 @@ func TestContract_UpdateFunnelTelemetryStaysContentFree(t *testing.T) {
}
}
-// TestContract_ExecutorPostCompletionCallback pins the executor-side
-// seam the API layer attaches the agent SSE bridge to. The Assistant
-// executor no longer dispatches action audits itself (typed actions
-// plan through Pulse Actions), so this pins only that the seam exists.
-func TestContract_ExecutorPostCompletionCallback(t *testing.T) {
- executor, err := os.ReadFile("../ai/tools/executor.go")
- if err != nil {
- t.Fatalf("read executor.go: %v", err)
- }
- executorSrc := string(executor)
- if !strings.Contains(executorSrc, "func (e *PulseToolExecutor) SetOnActionCompleted(cb func(unifiedresources.ActionAuditRecord))") {
- t.Error("executor must expose SetOnActionCompleted so the API layer can bridge action completion into the agent SSE stream")
- }
-}
-
// TestContract_AgentEventActionCompletedKindIsStable pins the
// wire-stable event kind string. Renaming AgentEventActionCompleted
// breaks every agent that branches on the SSE event-type field; the
@@ -19669,85 +19186,6 @@ func TestContract_AgentCapabilitiesManifestVersionIsPinned(t *testing.T) {
}
func TestContract_PulseIntelligenceSurfaceToolProjectionKeepsAssistantAndMCPDistinct(t *testing.T) {
- surfaceSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "surface_contract.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/surface_contract.go: %v", err)
- }
- surfaceContract := string(surfaceSource)
- for _, required := range []string{
- `type SurfaceToolContract struct`,
- `SurfaceToolSourceAssistantRegistry = "assistant_registry"`,
- `SurfaceToolSourceCapabilityManifest = "capability_manifest"`,
- `func ProjectPulseAssistantSurfaceToolContract(`,
- `func ProjectManifestSurfaceToolContract(`,
- `func ProjectManifestSurfaceToolContracts(`,
- `func ResolveManifestSurfaceToolContract(`,
- `func ProjectPulseIntelligenceSurfaceToolContracts(`,
- `type ResolvedSurfaceAffordanceContract struct`,
- `func ResolveSurfaceAffordanceContract(`,
- `ResolveSurfaceAffordanceContract(contract, SurfaceIDPulseAssistant, "")`,
- `ResolveSurfaceAffordanceContract(manifest.SurfaceContract, surface.ID, surface.Label)`,
- `func ManifestSurfaceAffordances(`,
- `func IntersectSurfaceAffordances(`,
- `IntersectSurfaceAffordances(resolvedSurface.Affordances, contract.Affordances)`,
- `ProviderToolNames(providerTools)`,
- `AssistantNativeProviderToolNames()`,
- `if !surface.Affordances.Tools`,
- `if !surface.Affordances.InteractiveQuestions`,
- `ToolNames: offeredNames`,
- `!surface.ExternalAdapter`,
- `FindManifestSurfaceToolContract(manifest, surface.ID)`,
- `requestResponseCapabilityNamesForNames(manifest.Capabilities, contract.ToolNames)`,
- `ProjectManifestSurfaceToolContract(manifest, surface.ID)`,
- } {
- if !strings.Contains(surfaceContract, required) {
- t.Errorf("agentcapabilities must own shared Assistant/MCP surface tool projection; missing %s", required)
- }
- }
- for _, forbidden := range []string{
- `func ProjectPulseMCPSurfaceToolContract(`,
- `projectManifestSurfaceToolContractFromCapabilities`,
- `requestResponseCapabilityNames(manifest.Capabilities)`,
- `ProjectManifestSurfaceToolContract(manifest, SurfaceIDPulseMCP)`,
- `ProjectTools(manifest.Capabilities)`,
- } {
- if strings.Contains(surfaceContract, forbidden) {
- t.Errorf("agentcapabilities surface resolver must not keep MCP-specific or raw-capability fallback projection; found %s", forbidden)
- }
- }
-
- projectionSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "projection.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/projection.go: %v", err)
- }
- projectionContract := string(projectionSource)
- for _, required := range []string{
- `ResolveManifestSurfaceToolContract(manifest, surfaceID)`,
- `ManifestSurfaceAffordances(manifest, contract.SurfaceID)`,
- `if !affordances.Tools`,
- } {
- if !strings.Contains(projectionContract, required) {
- t.Errorf("agentcapabilities projection must resolve external-surface tools through the normalized surface contract; missing %s", required)
- }
- }
-
- // The authenticated surface-tools route and its chat and tools wrappers
- // served only the retired web chat window; they must not come back.
- for _, retired := range []struct{ path, symbol string }{
- {filepath.Join("..", "ai", "tools", "provider_projection.go"), `func (e *PulseToolExecutor) AssistantSurfaceToolContract(`},
- {filepath.Join("..", "ai", "chat", "service.go"), `func (s *Service) AssistantSurfaceToolContract(`},
- {"ai_handler.go", `func (h *AIHandler) HandleAssistantSurfaceTools(`},
- {"router_routes_ai_relay.go", `"/api/ai/assistant/surface-tools"`},
- } {
- source, err := os.ReadFile(retired.path)
- if err != nil {
- t.Fatalf("read %s: %v", retired.path, err)
- }
- if strings.Contains(string(source), retired.symbol) {
- t.Errorf("%s must not reintroduce the retired web chat surface-tools path %s", retired.path, retired.symbol)
- }
- }
-
manifest := agentcapabilities.CanonicalManifest()
contracts := agentcapabilities.ProjectPulseIntelligenceSurfaceToolContracts(manifest, []agentcapabilities.ProviderTool{
{Name: agentcapabilities.PulseQueryToolName},
@@ -20195,24 +19633,6 @@ func TestContract_AgentCapabilitiesManifestRoutesReachRouterWithAdvertisedScope(
}
func TestContract_AgentCapabilitiesRequiredScopeSummaryUsesManifestScopes(t *testing.T) {
- scopesSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "scopes.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/scopes.go: %v", err)
- }
- src := string(scopesSource)
- for _, required := range []string{
- `func NormalizeRequiredScopes(scopes []string) []string`,
- `func RequiredCapabilityScopes(capabilities []Capability) []string`,
- `for _, scope := range auth.AllKnownScopes`,
- `func RequiredScopeList(scopes []string) string`,
- `func RequiredCapabilityScopeList(capabilities []Capability) string`,
- `func ManifestRequiredScopeList(manifest *Manifest) string`,
- } {
- if !strings.Contains(src, required) {
- t.Errorf("agent capabilities scope summary must stay in the shared manifest contract; missing %s", required)
- }
- }
-
got := agentcapabilities.RequiredCapabilityScopes(agentcapabilities.CanonicalManifest().Capabilities)
want := []string{
authpkg.ScopeMonitoringRead,
@@ -20231,21 +19651,6 @@ func TestContract_AgentCapabilitiesRequiredScopeSummaryUsesManifestScopes(t *tes
if !reflect.DeepEqual(manifest.RequiredScopes, want) {
t.Fatalf("canonical agent capability manifest requiredScopes = %v, want %v", manifest.RequiredScopes, want)
}
-
- mcpSource, err := os.ReadFile(filepath.Join("..", "..", "cmd", "pulse-mcp", "main.go"))
- if err != nil {
- t.Fatalf("read cmd/pulse-mcp/main.go: %v", err)
- }
- mcp := string(mcpSource)
- if !strings.Contains(mcp, `agentcapabilities.ManifestRequiredScopeList(manifest)`) {
- t.Error("pulse-mcp token guidance must consume the manifest-owned requiredScopes summary")
- }
- if strings.Contains(mcp, `RequiredCapabilityScopeList(capabilities)`) {
- t.Error("pulse-mcp token guidance must not recompute current manifest scopes from capability rows")
- }
- if strings.Contains(mcp, `monitoring:read scope (and monitoring:write`) {
- t.Error("pulse-mcp startup guidance must not carry a hand-maintained partial scope list")
- }
}
func TestContract_PulseMCPReadmeManifestProjectionStaysGenerated(t *testing.T) {
@@ -20503,2004 +19908,6 @@ func markedContractBlock(content, startMarker, endMarker string) (string, error)
return strings.TrimSpace(content[bodyStart : bodyStart+end]), nil
}
-func TestContract_AssistantProviderSeamsDoNotUseMCPTerminology(t *testing.T) {
- chatServiceSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "service.go"))
- if err != nil {
- t.Fatalf("read internal/ai/chat/service.go: %v", err)
- }
- chatService := string(chatServiceSource)
- for _, fragment := range []string{
- `AssistantAlertProvider = tools.AlertProvider`,
- `AssistantFindingsProvider = tools.FindingsProvider`,
- `AssistantUnifiedResourceProvider = tools.UnifiedResourceProvider`,
- `func (s *Service) ExecuteAssistantTool(ctx context.Context, toolName string, args map[string]interface{}) (string, error)`,
- `Msg("Executing Assistant registry tool directly")`,
- } {
- if !strings.Contains(chatService, fragment) {
- t.Errorf("native Assistant provider seam must be Assistant-owned, missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `MCPAlertProvider`,
- `MCPFindingsProvider`,
- `MCPDiscoveryProvider`,
- `MCPUnifiedResourceProvider`,
- `func (s *Service) ExecuteMCPTool(`,
- `MCP provider type aliases`,
- `Msg("Executing MCP tool directly")`,
- } {
- if strings.Contains(chatService, fragment) {
- t.Errorf("native Assistant provider seam must not be named as the MCP adapter surface; found %s", fragment)
- }
- }
-
- apiHandlerSource, err := os.ReadFile("ai_handler.go")
- if err != nil {
- t.Fatalf("read internal/api/ai_handler.go: %v", err)
- }
- apiHandler := string(apiHandlerSource)
- for _, fragment := range []string{
- `SetAlertProvider(provider chat.AssistantAlertProvider)`,
- `SetFindingsProvider(provider chat.AssistantFindingsProvider)`,
- `SetUnifiedResourceProvider(provider chat.AssistantUnifiedResourceProvider)`,
- } {
- if !strings.Contains(apiHandler, fragment) {
- t.Errorf("API chat service interface must expose Assistant provider seams; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `chat.MCPAlertProvider`,
- `chat.MCPFindingsProvider`,
- `chat.MCPDiscoveryProvider`,
- `chat.MCPUnifiedResourceProvider`,
- `for MCP tools`,
- } {
- if strings.Contains(apiHandler, fragment) {
- t.Errorf("API chat service interface must not describe native Assistant providers as MCP tools; found %s", fragment)
- }
- }
-
- settingsHandlerSource, err := os.ReadFile("ai_handlers.go")
- if err != nil {
- t.Fatalf("read internal/api/ai_handlers.go: %v", err)
- }
- settingsHandler := string(settingsHandlerSource)
- for _, fragment := range []string{
- `Used by Router to update Assistant tool visibility without restarting AI chat.`,
- `Update Assistant control settings if the control level changed.`,
- `This updates tool visibility without restarting AI chat.`,
- } {
- if !strings.Contains(settingsHandler, fragment) {
- t.Errorf("AI settings handler must describe control refresh as native Assistant tool visibility; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `Update MCP control settings`,
- `MCP control settings`,
- `MCP tool visibility`,
- } {
- if strings.Contains(settingsHandler, fragment) {
- t.Errorf("AI settings handler must not describe native Assistant control refresh as MCP wiring; found %s", fragment)
- }
- }
-
- routerSource, err := os.ReadFile("router.go")
- if err != nil {
- t.Fatalf("read internal/api/router.go: %v", err)
- }
- router := string(routerSource)
- for _, fragment := range []string{
- `ai.NewFindingsToolAdapter(findingsStore)`,
- `tools.NewAlertManagerToolAdapter(alertManager)`,
- `NewAssistantAgentProfileManager(persistence, licenseSvc)`,
- `AI chat Assistant tool providers wired`,
- `Wire control settings change callback to update Assistant tool visibility`,
- } {
- if !strings.Contains(router, fragment) {
- t.Errorf("router must wire native Assistant providers without MCP terminology; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `ai.NewFindingsMCPAdapter(findingsStore)`,
- `tools.NewAlertManagerMCPAdapter(alertManager)`,
- `tools.NewDiscoveryMCPAdapter(adapter)`,
- `NewMCPAgentProfileManager(persistence, licenseSvc)`,
- `AI chat MCP tool providers wired`,
- `org-scoped MCP tool providers`,
- } {
- if strings.Contains(router, fragment) {
- t.Errorf("router must not describe native Assistant provider wiring as MCP adapter wiring; found %s", fragment)
- }
- }
-
- relaySource, err := os.ReadFile("router_routes_ai_relay.go")
- if err != nil {
- t.Fatalf("read internal/api/router_routes_ai_relay.go: %v", err)
- }
- relay := string(relaySource)
- for _, fragment := range []string{
- `toolAdapter := &assistantToolAdapter{handler: h}`,
- `AssistantToolExecutor: toolAdapter`,
- `type assistantToolAdapter struct`,
- `var _ aicontracts.ApprovedAssistantToolExecutor = (*assistantToolAdapter)(nil)`,
- `func (m *assistantToolAdapter) ExecuteApprovedAssistantTool(ctx context.Context, command, approvalID string) (string, int, error)`,
- } {
- if !strings.Contains(relay, fragment) {
- t.Errorf("approved Assistant tool adapter must expose native Assistant execution from the current runtime; missing %s", fragment)
- }
- }
- if !strings.Contains(relay, `chatService.ExecuteAssistantTool(ctx, params.Name, params.Arguments)`) {
- t.Error("approved Assistant tool adapter must delegate to the native Assistant tool executor")
- }
- if strings.Contains(relay, `type mcpToolAdapter struct`) || strings.Contains(relay, `&mcpToolAdapter{`) {
- t.Error("approved Assistant tool adapter must not be named as the MCP adapter surface")
- }
- for _, fragment := range []string{
- `MCPExecutor: toolAdapter`,
- `MCPExecutor: toolAdapter`,
- `var _ aicontracts.MCPToolExecutor = (*assistantToolAdapter)(nil)`,
- `func (m *assistantToolAdapter) ExecuteMCPTool(ctx context.Context, command, approvalID string) (string, int, error)`,
- `chatService.ExecuteMCPTool(`,
- } {
- if strings.Contains(relay, fragment) {
- t.Errorf("current runtime must not expose native Assistant execution through the legacy MCP executor seam; found %s", fragment)
- }
- }
-
- contractSource, err := os.ReadFile(filepath.Join("..", "..", "pkg", "aicontracts", "fix_execution.go"))
- if err != nil {
- t.Fatalf("read pkg/aicontracts/fix_execution.go: %v", err)
- }
- contracts := string(contractSource)
- for _, fragment := range []string{
- `type ApprovedAssistantToolExecutor interface`,
- `ExecuteApprovedAssistantTool(ctx context.Context, command, approvalID string) (output string, exitCode int, err error)`,
- } {
- if !strings.Contains(contracts, fragment) {
- t.Errorf("cross-repo approved tool contract must expose native Assistant executor only; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `type MCPToolExecutor interface`,
- `ExecuteMCPTool(ctx context.Context, command, approvalID string) (output string, exitCode int, err error)`,
- `Prefer ApprovedAssistantToolExecutor for new integrations`,
- } {
- if strings.Contains(contracts, fragment) {
- t.Errorf("cross-repo approved tool contract must not preserve legacy MCP executor compatibility; found %s", fragment)
- }
- }
-
- extensionSource, err := os.ReadFile(filepath.Join("..", "..", "pkg", "extensions", "ai_autofix.go"))
- if err != nil {
- t.Fatalf("read pkg/extensions/ai_autofix.go: %v", err)
- }
- extensionsSrc := string(extensionSource)
- for _, fragment := range []string{
- `AssistantToolExecutor aicontracts.ApprovedAssistantToolExecutor`,
- `func (d AIAutoFixHandlerDeps) ResolveApprovedAssistantToolExecutor() aicontracts.ApprovedAssistantToolExecutor`,
- `return d.AssistantToolExecutor`,
- } {
- if !strings.Contains(extensionsSrc, fragment) {
- t.Errorf("auto-fix extension deps must expose native Assistant tool execution without MCP compatibility; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `MCPExecutor`,
- `MCPToolExecutor`,
- `legacyMCPApprovedAssistantToolExecutor`,
- `ExecuteMCPTool`,
- `compatibility fallback for enterprise binders`,
- } {
- if strings.Contains(extensionsSrc, fragment) {
- t.Errorf("auto-fix extension deps must not expose legacy MCP executor compatibility; found %s", fragment)
- }
- }
-
- findingsAdapterSource, err := os.ReadFile(filepath.Join("..", "ai", "findings_tools_adapter.go"))
- if err != nil {
- t.Fatalf("read internal/ai/findings_tools_adapter.go: %v", err)
- }
- findingsAdapter := string(findingsAdapterSource)
- if !strings.Contains(findingsAdapter, `type FindingsToolAdapter struct`) ||
- !strings.Contains(findingsAdapter, `func NewFindingsToolAdapter(store *FindingsStore) *FindingsToolAdapter`) {
- t.Error("findings store adapter must be named for the native tool registry")
- }
- if strings.Contains(findingsAdapter, `FindingsMCPAdapter`) || strings.Contains(findingsAdapter, `NewFindingsMCPAdapter`) {
- t.Error("findings store adapter must not be named as an MCP adapter")
- }
-
- toolAdaptersSource, err := os.ReadFile(filepath.Join("..", "ai", "tools", "adapters.go"))
- if err != nil {
- t.Fatalf("read internal/ai/tools/adapters.go: %v", err)
- }
- toolAdapters := string(toolAdaptersSource)
- for _, fragment := range []string{
- `type AlertManagerToolAdapter struct`,
- `func NewAlertManagerToolAdapter(manager AlertManager) *AlertManagerToolAdapter`,
- `type RecoveryPointsToolAdapter struct`,
- `func NewRecoveryPointsToolAdapter(manager *recoverymanager.Manager, orgID string) *RecoveryPointsToolAdapter`,
- } {
- if !strings.Contains(toolAdapters, fragment) {
- t.Errorf("Assistant runtime adapters must be named for the native tool registry; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `MCPAdapter`,
- `NewAlertManagerMCPAdapter`,
- `NewRecoveryPointsMCPAdapter`,
- `NewDiscoveryMCPAdapter`,
- `MCP tools`,
- `mcp.`,
- } {
- if strings.Contains(toolAdapters, fragment) {
- t.Errorf("Assistant runtime adapters must not be named as MCP adapters; found %s", fragment)
- }
- }
-
- intelligenceAdaptersSource, err := os.ReadFile(filepath.Join("..", "ai", "adapters", "adapters.go"))
- if err != nil {
- t.Fatalf("read internal/ai/adapters/adapters.go: %v", err)
- }
- intelligenceAdapters := string(intelligenceAdaptersSource)
- for _, fragment := range []string{
- `type EventCorrelatorToolAdapter struct`,
- `func NewEventCorrelatorToolAdapter(correlator EventCorrelatorSource) *EventCorrelatorToolAdapter`,
- } {
- if !strings.Contains(intelligenceAdapters, fragment) {
- t.Errorf("Assistant intelligence adapters must be named for the native tool registry; missing %s", fragment)
- }
- }
- if strings.Contains(intelligenceAdapters, `MCPAdapter`) || strings.Contains(intelligenceAdapters, `NewIncidentRecorderMCPAdapter`) || strings.Contains(intelligenceAdapters, `NewEventCorrelatorMCPAdapter`) {
- t.Error("Assistant intelligence adapters must not be named as MCP adapters")
- }
-
- agentProfilesSource, err := os.ReadFile("agent_profiles_tools.go")
- if err != nil {
- t.Fatalf("read internal/api/agent_profiles_tools.go: %v", err)
- }
- agentProfiles := string(agentProfilesSource)
- if !strings.Contains(agentProfiles, `type AssistantAgentProfileManager struct`) ||
- !strings.Contains(agentProfiles, `func NewAssistantAgentProfileManager(persistence *config.ConfigPersistence, licenseService licenseFeatureChecker) *AssistantAgentProfileManager`) {
- t.Error("agent profile manager must be named for the native Assistant tool registry")
- }
- if strings.Contains(agentProfiles, `MCPAgentProfileManager`) || strings.Contains(agentProfiles, `NewMCPAgentProfileManager`) || strings.Contains(agentProfiles, `MCP tools`) {
- t.Error("agent profile manager must not be named as an MCP adapter")
- }
-}
-
-// TestContract_PulseMCPAdapterProjectsAgentCapabilitiesManifest pins the
-// external-agent adapter boundary: pulse-mcp must stay a projection of the
-// canonical capabilities manifest, not a second action registry.
-func TestContract_PulseMCPAdapterProjectsAgentCapabilitiesManifest(t *testing.T) {
- source, err := os.ReadFile(filepath.Join("..", "..", "cmd", "pulse-mcp", "main.go"))
- if err != nil {
- t.Fatalf("read cmd/pulse-mcp/main.go: %v", err)
- }
- src := string(source)
- required := []string{
- `internal/agentcapabilities`,
- `type agentCapability = agentcapabilities.Capability`,
- `type agentCapabilitiesManifest = agentcapabilities.Manifest`,
- `type jsonRPCRequest = agentcapabilities.JSONRPCRequest`,
- `agentcapabilities.ServeJSONRPCLines(`,
- `agentcapabilities.WriteJSONRPCMessage(out, v)`,
- `agentcapabilities.DispatchMCPToolServerRequest(ctx, *req, s.manifestToolServer().Handlers(func()`,
- `agentcapabilities.MCPManifestToolServer{`,
- `ServerName: pulseMCPServerName`,
- `SurfaceID: agentcapabilities.SurfaceIDPulseMCP`,
- `Manifest: manifest`,
- `agentcapabilities.FetchManifest(context.Background(), manifestClient, *baseURL)`,
- `agentcapabilities.StreamMCPEventNotifications(ctx, pulseMCPAgentSurfaceHTTPDoer{}, s.baseURL, path, s.token, func(notification agentcapabilities.JSONRPCRequest) error`,
- `agentcapabilities.DoAgentHTTPRequest(d.next, req)`,
- }
- for _, fragment := range required {
- if !strings.Contains(src, fragment) {
- t.Errorf("pulse-mcp must project the canonical agent capabilities manifest; missing %s", fragment)
- }
- }
- forbidden := []string{
- `type jsonRPCRequest struct`,
- `type jsonRPCResponse struct`,
- `type jsonRPCError struct`,
- `type jsonRPCResponse = agentcapabilities.JSONRPCResponse`,
- `type jsonRPCError = agentcapabilities.JSONRPCError`,
- `bufio.NewScanner(in)`,
- `scanner.Scan()`,
- `agentcapabilities.DecodeJSONRPCRequest(`,
- `agentcapabilities.NewJSONRPCParseErrorResponse(`,
- `agentcapabilities.JSONRPCRequestExpectsResponse(`,
- `json.Unmarshal([]byte(line)`,
- `agentcapabilities.JSONRPCErrorParse`,
- `len(req.ID) == 0`,
- `string(req.ID) == "null"`,
- `switch req.Method`,
- `agentcapabilities.NewJSONRPCResponse(req.ID, nil)`,
- `agentcapabilities.JSONRPCErrorInternal`,
- `agentcapabilities.JSONRPCErrorMethodNotFound`,
- `agentcapabilities.MCPToolServerHandlers{`,
- `agentcapabilities.MCPMethodToolsList`,
- `agentcapabilities.MCPMethodToolsCall`,
- `agentcapabilities.MCPMethodResourcesList`,
- `agentcapabilities.MCPMethodResourcesRead`,
- `agentcapabilities.MCPMethodPromptsList`,
- `agentcapabilities.MCPMethodPromptsGet`,
- `agentcapabilities.MCPMethodPing`,
- `func (s *mcpServer) handleInitialize(`,
- `func (s *mcpServer) handleToolsList(`,
- `func (s *mcpServer) handleToolsCall(`,
- `func (s *mcpServer) handleResourcesList(`,
- `func (s *mcpServer) handleResourcesRead(`,
- `func (s *mcpServer) handlePromptsList(`,
- `func (s *mcpServer) handlePromptsGet(`,
- `agentcapabilities.NewMCPToolServerInitializeResult(pulseMCPServerName`,
- `agentcapabilities.ProjectTools(s.manifest.Capabilities)`,
- `agentcapabilities.ProjectMCPPrompts(s.manifest.Capabilities)`,
- `agentcapabilities.GetMCPPrompt(s.manifest.Capabilities`,
- `agentcapabilities.BuildMCPPrompt(s.manifest.Capabilities`,
- `agentcapabilities.ExecuteMCPToolHTTP(`,
- `agentcapabilities.ExecuteMCPManifestSurfaceToolHTTP(ctx, s.http, s.baseURL, s.token, s.manifest, agentcapabilities.SurfaceIDPulseMCP, raw)`,
- `"protocolVersion": "2024-11-05"`,
- `"protocolVersion": "2025-06-18"`,
- `"isError": isError`,
- `NewMCPHTTPTextResult(resp.Body, resp.StatusCode)`,
- `agentcapabilities.MCPCapabilities{`,
- `agentcapabilities.MCPToolsCapability{}`,
- `agentcapabilities.MCPPulseNotificationsCapability{`,
- `json.Unmarshal(raw, &params)`,
- `fmt.Errorf("unknown tool: %s", params.Name)`,
- `agentcapabilities.FindCapability(s.manifest.Capabilities, params.Name)`,
- `agentcapabilities.CallCapabilityHTTP(ctx, s.http, s.baseURL, s.token, cap, params.Arguments)`,
- `agentcapabilities.NewMCPCapabilityHTTPResult(resp)`,
- `http.NewRequestWithContext(ctx, cap.Method`,
- `httpReq.Header.Set("X-API-Token"`,
- `baseURL+"/api/agent/capabilities"`,
- `req.Header.Set("Accept", "text/event-stream")`,
- `http.DefaultClient.Do(req)`,
- `scanner := bufio.NewScanner(resp.Body)`,
- `strings.HasPrefix(line, "event: ")`,
- `strings.HasPrefix(line, "data: ")`,
- `agentcapabilities.StreamAgentSSERecords(ctx, nil, s.baseURL, path, s.token`,
- `agentcapabilities.IsTransportEventKind(event)`,
- `agentcapabilities.NewMCPEventNotification(event, []byte(data))`,
- `agentcapabilities.NewJSONRPCNotification(agentcapabilities.MCPNotificationMethod(event), params)`,
- }
- for _, fragment := range forbidden {
- if strings.Contains(src, fragment) {
- t.Errorf("pulse-mcp must not preserve local MCP wire/result envelope logic; found %s", fragment)
- }
- }
-
- projectionSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "projection.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/projection.go: %v", err)
- }
- projection := string(projectionSource)
- sharedRequired := []string{
- `type ProjectedTool struct`,
- `Title string`,
- `OutputSchema json.RawMessage`,
- `Annotations *ToolBehaviorHints`,
- `Meta map[string]any`,
- `type ToolBehaviorHints struct`,
- `ToolMetaPulseCapabilityKey = "pulse.capability"`,
- `ReadOnlyHint`,
- `DestructiveHint`,
- `IdempotentHint`,
- `OpenWorldHint`,
- `func ProjectTools(capabilities []Capability) []ProjectedTool`,
- `func ProjectManifestSurfaceTools(manifest Manifest, surfaceID string) []ProjectedTool`,
- `func ManifestSurfaceToolCapabilities(manifest Manifest, surfaceID string) []Capability`,
- `func FindManifestSurfaceToolContract(manifest Manifest, surfaceID string) (SurfaceToolContract, bool)`,
- `func ProjectTool(cap Capability) (ProjectedTool, bool)`,
- `func CapabilityTitle(cap Capability) string`,
- `func ToolAnnotations(cap Capability) *ToolBehaviorHints`,
- `func ToolGovernanceBehaviorHints(governance ToolGovernanceDescriptor) *ToolBehaviorHints`,
- `func CloneToolBehaviorHints(hints *ToolBehaviorHints) *ToolBehaviorHints`,
- `func ToolMeta(cap Capability) map[string]any`,
- `NormalizeCapabilityGovernance(cap)`,
- `func FindCapability(capabilities []Capability, name string) (Capability, bool)`,
- `type CapabilityLookupError struct`,
- `func ResolveCapability(capabilities []Capability, name string) (Capability, error)`,
- `func ResolveRequestResponseCapability(capabilities []Capability, name string) (Capability, error)`,
- `return CloneCapability(cap), true`,
- `IsRequestResponseCapability(cap)`,
- `ResolutionNoteArgumentName = "resolution_note"`,
- `NoteArgumentName = "note"`,
- `Title: CapabilityTitle(cap)`,
- `Description: ToolDescription(cap)`,
- `InputSchema: ToolInputSchema(cap)`,
- `OutputSchema: ToolOutputSchema(cap)`,
- `Annotations: ToolAnnotations(cap)`,
- `Meta: ToolMeta(cap)`,
- `ToolMetaPulseCapabilityKey: capability`,
- `return CloneRawMessage(cap.InputSchema)`,
- `return CloneRawMessage(cap.OutputSchema)`,
- }
- for _, fragment := range sharedRequired {
- if !strings.Contains(projection, fragment) {
- t.Errorf("agentcapabilities must own the external-agent tool projection; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `Annotations *MCPToolAnnotations`,
- `type MCPToolAnnotations struct`,
- `func ToolAnnotations(cap Capability) *MCPToolAnnotations`,
- } {
- if strings.Contains(projection, fragment) {
- t.Errorf("external-agent tool projection must not make MCP the owner of shared behavior hints; found %s", fragment)
- }
- }
-
- mcpAliasSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "mcp.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/mcp.go: %v", err)
- }
- mcp := string(mcpAliasSource)
- if !strings.Contains(mcp, `type MCPToolAnnotations = ToolBehaviorHints`) {
- t.Error("MCP adapter edge must keep the protocol-facing tool annotations alias over shared behavior hints")
- }
-
- schemaSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "schema.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/schema.go: %v", err)
- }
- schema := string(schemaSource)
- for _, fragment := range []string{
- `type ProviderTool struct`,
- `type ProviderToolCall struct`,
- `type ProviderToolResult struct`,
- `func (t Tool) NormalizeCollections() Tool`,
- `func (s InputSchema) NormalizeCollections() InputSchema`,
- `func ClonePropertySchemas(properties map[string]PropertySchema) map[string]PropertySchema`,
- `func CloneProviderInputSchema(schema map[string]interface{}) map[string]interface{}`,
- `func CloneRawMessage(raw json.RawMessage) json.RawMessage`,
- `func EmptyProviderTool() ProviderTool`,
- `func (t ProviderTool) NormalizeCollections() ProviderTool`,
- `t.InputSchema = CloneProviderInputSchema(t.InputSchema)`,
- `t.BehaviorHints = CloneToolBehaviorHints(t.BehaviorHints)`,
- `BehaviorHints *ToolBehaviorHints`,
- `PulseGovernance *ToolGovernanceDescriptor`,
- `func EmptyProviderToolCall() ProviderToolCall`,
- `func (t ProviderToolCall) NormalizeCollections() ProviderToolCall`,
- `t.Input = CloneToolArguments(t.Input)`,
- `t.ThoughtSignature = CloneRawMessage(t.ThoughtSignature)`,
- `type ProviderToolResultContextOptions struct`,
- `type ProviderToolResultTruncation struct`,
- `type ProviderToolResultContextProjection struct`,
- `func NewProviderToolResult(toolUseID, content string, isError bool) ProviderToolResult`,
- `func NewProviderToolErrorResult(toolUseID, content string) ProviderToolResult`,
- `func NewProviderToolResultFromToolResult(toolUseID string, result ToolResult) ProviderToolResult`,
- `func NewProviderToolResultContextProjection(toolUseID, content string, isError bool, opts ProviderToolResultContextOptions) ProviderToolResultContextProjection`,
- `func NewProviderToolResultContextProjectionFromToolResult(toolUseID string, result ToolResult, opts ProviderToolResultContextOptions) ProviderToolResultContextProjection`,
- `func ProviderToolResultModelContent(content string, opts ProviderToolResultContextOptions) (string, ProviderToolResultTruncation)`,
- `func ProviderInputSchemaFromRaw(raw json.RawMessage) map[string]interface{}`,
- `func ProjectProviderTool(tool Tool) ProviderTool`,
- `func ProjectProviderToolWithGovernance(tool Tool, governance ToolGovernanceDescriptor) ProviderTool`,
- `func ProjectProviderTools(tools []Tool) []ProviderTool`,
- `func ProjectProviderToolsWithGovernance(tools []Tool, governance []ToolGovernanceDescriptor) []ProviderTool`,
- `type AssistantProviderToolOptions struct`,
- `func ProjectAssistantProviderTools(tools []Tool, governance []ToolGovernanceDescriptor, opts AssistantProviderToolOptions) []ProviderTool`,
- `func ProjectPulseAssistantProviderTools(manifest Manifest, tools []Tool, governance []ToolGovernanceDescriptor, opts AssistantProviderToolOptions) []ProviderTool`,
- `func ProviderToolGovernanceDescriptors(tools []ProviderTool) ([]ToolGovernanceDescriptor, bool)`,
- `func AssistantNativeProviderTools() []ProviderTool`,
- `func AssistantNativeProviderToolNames() []string`,
- `func LegacyAssistantUtilityProviderTools() []ProviderTool`,
- `LegacyAssistantRunCommandToolName = "run_command"`,
- `LegacyAssistantFetchURLToolName = "fetch_url"`,
- `LegacyAssistantSetResourceURLToolName = "set_resource_url"`,
- `func ProviderToolNames(tools []ProviderTool) []string`,
- `type ProviderToolNameCatalog struct`,
- `func NewProviderToolNameCatalog(nameGroups ...[]string) ProviderToolNameCatalog`,
- `func NewAssistantProviderToolNameCatalog(registryToolNames []string) ProviderToolNameCatalog`,
- `func (c ProviderToolNameCatalog) Names() []string`,
- `func (c ProviderToolNameCatalog) Has(name string) bool`,
- `func (c ProviderToolNameCatalog) HasPrefix(prefix string) bool`,
- `func ProviderToolDescriptionWithGovernance(description string, governance ToolGovernanceDescriptor) string`,
- `func ProjectProviderToolCallToToolCall(tc ProviderToolCall) ToolCallParams`,
- `func NormalizeProviderToolCallForExecution(tc ProviderToolCall) ProviderToolCall`,
- `func NormalizeProviderToolCallsForExecution(calls []ProviderToolCall) []ProviderToolCall`,
- `func NewPulseQuestionProviderTool() ProviderTool`,
- `func PulseQuestionProviderInputSchema() map[string]interface{}`,
- `func ParseProviderToolInput(raw string) (map[string]interface{}, bool)`,
- `func ProviderToolInputOrRaw(raw string) map[string]interface{}`,
- `schema = schema.NormalizeCollections()`,
- `projected := CloneProviderInputSchema(schema)`,
- `property = property.NormalizeCollections()`,
- `tool = tool.NormalizeCollections()`,
- `InputSchema: ProviderInputSchema(tool.InputSchema)`,
- `ToolGovernancePromptDescription(governance)`,
- `Pulse governance: `,
- `projected.BehaviorHints = ToolGovernanceBehaviorHints(governance)`,
- `projected.PulseGovernance = &governance`,
- `return NewProviderToolResult(toolUseID, interpreted.Text, interpreted.IsError)`,
- `ProviderToolResultModelContent(content, opts)`,
- `return NormalizeToolCallParams(ToolCallParams{`,
- `Arguments: tc.Input,`,
- `params := ProjectProviderToolCallToToolCall(tc)`,
- `normalized.Name = params.Name`,
- `normalized.Input = params.Arguments`,
- `projected = append(projected, AssistantNativeProviderTools()...)`,
- `ManifestSurfaceAffordances(manifest, SurfaceIDPulseAssistant)`,
- `if !affordances.Tools`,
- `if !affordances.InteractiveQuestions`,
- `return ProviderToolNames(AssistantNativeProviderTools())`,
- `Name: PulseQuestionToolName`,
- `InputSchema: PulseQuestionProviderInputSchema(),`,
- `Name: LegacyAssistantFetchURLToolName`,
- `Name: LegacyAssistantSetResourceURLToolName`,
- `type PulseQuestionToolType string`,
- `PulseQuestionToolTypeText PulseQuestionToolType = "text"`,
- `PulseQuestionToolTypeSelect PulseQuestionToolType = "select"`,
- `func PulseQuestionToolTypeValues() []string`,
- `func NormalizePulseQuestionToolType(rawType string, hasOptions bool) (PulseQuestionToolType, error)`,
- `type PulseQuestionToolQuestion struct`,
- `type PulseQuestionToolOption struct`,
- `func ParsePulseQuestionToolInput(input map[string]interface{}) ([]PulseQuestionToolQuestion, error)`,
- `func parsePulseQuestionToolOptions(rawOptions json.RawMessage) ([]PulseQuestionToolOption, error)`,
- `"enum": PulseQuestionToolTypeValues(),`,
- `return map[string]interface{}{"raw": raw}`,
- } {
- if !strings.Contains(schema, fragment) {
- t.Errorf("agentcapabilities must own the Assistant provider tool projection; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func ProjectProviderToolCallToMCP(tc ProviderToolCall) MCPCallToolParams`,
- } {
- if strings.Contains(schema, fragment) {
- t.Errorf("neutral provider schema must not own MCP compatibility aliases; found %s", fragment)
- }
- }
-
- providerArtifactSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "provider_tool_artifacts.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/provider_tool_artifacts.go: %v", err)
- }
- providerArtifacts := string(providerArtifactSource)
- for _, fragment := range []string{
- `func ProviderToolCallArtifactIndex(content string, catalog ProviderToolNameCatalog) int`,
- `func SplitTrailingProviderToolNamePrefix(content string, catalog ProviderToolNameCatalog) (visible string, held string)`,
- `providerJSONToolCallLeakIndex(content, catalog)`,
- `providerPlainFunctionToolCallLeakIndex(content, catalog)`,
- `catalog.Has(name)`,
- `catalog.HasPrefix(token)`,
- } {
- if !strings.Contains(providerArtifacts, fragment) {
- t.Errorf("agentcapabilities must own provider tool-call artifact detection; missing %s", fragment)
- }
- }
-
- mcpSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "mcp.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/mcp.go: %v", err)
- }
- mcpWire := string(mcpSource)
- toolCallSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_call.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/tool_call.go: %v", err)
- }
- toolNameSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_names.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/tool_names.go: %v", err)
- }
- toolResultSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_result.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/tool_result.go: %v", err)
- }
- toolExecutionSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_execution.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/tool_execution.go: %v", err)
- }
- toolCore := string(toolNameSource) + "\n" + string(toolCallSource) + "\n" + string(toolResultSource) + "\n" + string(toolExecutionSource) + "\n" + projection
- mcpWireContract := mcpWire + "\n" + toolCore
- toolCallSrc := string(toolCallSource)
- toolNameSrc := string(toolNameSource)
- for _, pair := range []struct {
- name string
- value string
- }{
- {`PulseQueryToolName`, `"pulse_query"`},
- {`PulseControlToolName`, `"pulse_control"`},
- {`PulseReadToolName`, `"pulse_read"`},
- {`PulseSummarizeToolName`, `"pulse_summarize"`},
- {`PulseRunCommandToolName`, `"pulse_run_command"`},
- {`PatrolGetFindingsToolName`, `"patrol_get_findings"`},
- {`PatrolReportFindingToolName`, `"patrol_report_finding"`},
- {`PatrolResolveFindingToolName`, `"patrol_resolve_finding"`},
- } {
- if !strings.Contains(toolNameSrc, pair.name) || !strings.Contains(toolNameSrc, pair.value) {
- t.Errorf("agentcapabilities must own stable Pulse Intelligence tool identity %s=%s", pair.name, pair.value)
- }
- }
- for _, fragment := range []string{
- `type ToolCallKind int`,
- `ToolCallKindResolve`,
- `ToolCallKindRead`,
- `ToolCallKindWrite`,
- `ToolCallKindUserInput`,
- `func (k ToolCallKind) String() string`,
- `func ClassifyToolCall(toolName string, args map[string]interface{}) ToolCallKind`,
- // Registry tools classify through the canonical invocation
- // descriptors; the switch keeps only non-registry names.
- `if descriptor, ok := InvocationDescriptorFor(toolName); ok {`,
- `return descriptor.Classify(args).Kind`,
- `case PulseQuestionToolName:`,
- `case LegacyAssistantFetchURLToolName:`,
- `LegacyAssistantRunCommandToolName, LegacyAssistantSetResourceURLToolName`,
- `return ToolCallKindWrite`,
- } {
- if !strings.Contains(toolCallSrc, fragment) {
- t.Errorf("agentcapabilities must own shared tool-call safety classification; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `type JSONRPCRequest struct`,
- `type JSONRPCResponse struct`,
- `type JSONRPCError struct`,
- `type MCPInitializeResult struct`,
- `type ToolCallParams struct`,
- `type MCPCallToolParams = ToolCallParams`,
- `func NormalizeToolCallParams(params ToolCallParams) ToolCallParams`,
- `func ValidateToolCallParams(params ToolCallParams) error`,
- `type MCPProjectedToolsResult struct`,
- `type MCPResource struct`,
- `type MCPListResourcesResult struct`,
- `type MCPReadResourceParams struct`,
- `type MCPReadResourceResult struct`,
- `type MCPResourceContent struct`,
- `type MCPPrompt struct`,
- `Title string`,
- `type MCPPromptArgument struct`,
- `type MCPListPromptsResult struct`,
- `type MCPGetPromptParams struct`,
- `type MCPGetPromptResult struct`,
- `type MCPPromptMessage struct`,
- `type MCPCapabilities struct`,
- `Instructions string`,
- `Resources *MCPResourcesCapability`,
- `Prompts *MCPPromptsCapability`,
- `type MCPResourcesCapability struct`,
- `type MCPPromptsCapability struct`,
- `type ProjectedTool struct`,
- `OutputSchema json.RawMessage`,
- `Meta map[string]any`,
- `type ToolResult struct`,
- `StructuredContent map[string]any`,
- `type MCPToolResult = ToolResult`,
- `type ToolContent struct`,
- `type MCPContent = ToolContent`,
- `func (r MCPListResourcesResult) NormalizeCollections() MCPListResourcesResult`,
- `func (r MCPReadResourceResult) NormalizeCollections() MCPReadResourceResult`,
- `func (r MCPListPromptsResult) NormalizeCollections() MCPListPromptsResult`,
- `func (r MCPGetPromptResult) NormalizeCollections() MCPGetPromptResult`,
- `func EmptyToolResult() ToolResult`,
- `func (r ToolResult) NormalizeCollections() ToolResult`,
- `MCPPulseNotificationsExperimentalKey = "pulseNotifications"`,
- `func NewMCPToolServerInitializeResult(`,
- `func NewMCPManifestToolServerInitializeResult(`,
- `func NewMCPManifestSurfaceToolServerInitializeResult(`,
- `ManifestSurfaceAffordances(manifest, surfaceID)`,
- `ResolveManifestSurfaceToolContract(manifest, surfaceID)`,
- `affordances.Tools && hasSurfaceToolContract`,
- `MCPManifestSurfacePromptProjectionSupported(manifest, surfaceID)`,
- `Instructions: BuildPulseMCPOperatingInstructions(PulseMCPOperatingInstructionOptions{`,
- `SupportsTools: exposeTools`,
- `func MCPManifestResourceProjectionSupported(manifest Manifest, surfaceID string) bool`,
- `func ManifestSurfaceResourceCapabilities(manifest Manifest, surfaceID string) []Capability`,
- `func MCPManifestPromptProjectionSupported(manifest Manifest) bool`,
- `func MCPManifestSurfacePromptProjectionSupported(manifest Manifest, surfaceID string) bool`,
- `func ProjectMCPWorkflowPrompts(workflowPrompts []PulseWorkflowPrompt) []MCPPrompt`,
- `func DecodeMCPGetPromptParams(raw json.RawMessage) (MCPGetPromptParams, error)`,
- `func GetMCPPromptFromManifest(manifest Manifest, raw json.RawMessage) (MCPGetPromptResult, error)`,
- `func GetMCPPromptFromManifestSurface(manifest Manifest, surfaceID string, raw json.RawMessage) (MCPGetPromptResult, error)`,
- `func BuildMCPPromptFromManifest(manifest Manifest, params MCPGetPromptParams) (MCPGetPromptResult, error)`,
- `ManifestPulseWorkflowPrompts(manifest)`,
- `func MCPResourceURI(resourceID string) string`,
- `func ResourceIDFromMCPResourceURI(rawURI string) (string, error)`,
- `func DecodeMCPReadResourceParams(raw json.RawMessage) (MCPReadResourceParams, error)`,
- `func ListMCPManifestSurfaceResourcesHTTP(`,
- `func ReadMCPManifestSurfaceResourceHTTP(`,
- `func resolveMCPManifestSurfaceResourceCapabilities(`,
- `CallRequestResponseCapabilityHTTPBodyByName(ctx, client, baseURL, token, capabilities, FleetContextCapabilityName, map[string]any{})`,
- `CallRequestResponseCapabilityHTTPBodyByName(ctx, client, baseURL, token, capabilities, ResourceContextCapabilityName, map[string]any{`,
- `ResourceIDArgumentName: resourceID`,
- `caps.Tools = &MCPToolsCapability{}`,
- `MCPPulseNotificationsExperimentalKey: MCPPulseNotificationsCapability`,
- `type MCPToolServerHandlers struct`,
- `func DecodeJSONRPCRequest(`,
- `fmt.Errorf("malformed JSON-RPC request: %w", err)`,
- `func NewJSONRPCParseErrorResponse(`,
- `func JSONRPCRequestExpectsResponse(`,
- `type JSONRPCLineDispatcher func(context.Context, JSONRPCRequest) JSONRPCResponse`,
- `type JSONRPCResponseWriter func(JSONRPCResponse) error`,
- `func ServeJSONRPCLines(`,
- `scanner.Buffer(make([]byte, 64*1024), 1<<22)`,
- `DecodeJSONRPCRequest([]byte(line))`,
- `NewJSONRPCParseErrorResponse(err)`,
- `JSONRPCRequestExpectsResponse(req)`,
- `func WriteJSONRPCMessage(`,
- `enc.SetEscapeHTML(false)`,
- `type MCPManifestToolServer struct`,
- `SurfaceID string`,
- `func (s MCPManifestToolServer) Handlers(`,
- `func (s MCPManifestToolServer) Initialize() MCPInitializeResult`,
- `func (s MCPManifestToolServer) ToolsList() MCPProjectedToolsResult`,
- `func (s MCPManifestToolServer) ToolsCall(ctx context.Context, raw json.RawMessage) (MCPToolResult, error)`,
- `func (s MCPManifestToolServer) ResourcesList(ctx context.Context) (MCPListResourcesResult, error)`,
- `func (s MCPManifestToolServer) ResourcesRead(ctx context.Context, raw json.RawMessage) (MCPReadResourceResult, error)`,
- `func (s MCPManifestToolServer) PromptsList() MCPListPromptsResult`,
- `func (s MCPManifestToolServer) PromptsGet(ctx context.Context, raw json.RawMessage) (MCPGetPromptResult, error)`,
- `return NewMCPManifestSurfaceToolServerInitializeResult(s.ServerName, s.ServerVersion, s.EmitPulseNotifications, s.Manifest, s.surfaceID())`,
- `if !s.surfaceAffordances().Tools`,
- `return MCPProjectedToolsResult{Tools: ProjectManifestSurfaceTools(s.Manifest, s.surfaceID())}`,
- `return ExecuteMCPManifestSurfaceToolHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID(), raw)`,
- `return ListMCPManifestSurfaceResourcesHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID())`,
- `return ReadMCPManifestSurfaceResourceHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest, s.surfaceID(), raw)`,
- `if !affordances.Resources`,
- `fmt.Errorf("MCP resources are not enabled for surface %s", surfaceID)`,
- `return (MCPListPromptsResult{Prompts: ProjectMCPWorkflowPrompts(ManifestPulseWorkflowPrompts(s.Manifest))}).NormalizeCollections()`,
- `result, err := GetMCPPromptFromManifestSurface(s.Manifest, s.surfaceID(), raw)`,
- `func (s MCPManifestToolServer) surfaceAffordances() SurfaceAffordanceContract`,
- `func (s MCPManifestToolServer) surfaceID() string`,
- `func normalizeMCPManifestSurfaceID(surfaceID string) string`,
- `func DispatchMCPToolServerRequest(`,
- `case MCPMethodInitialize:`,
- `case MCPMethodToolsList:`,
- `case MCPMethodToolsCall:`,
- `case MCPMethodResourcesList:`,
- `case MCPMethodResourcesRead:`,
- `case MCPMethodPromptsList:`,
- `case MCPMethodPromptsGet:`,
- `return NewJSONRPCResponse(req.ID, result.NormalizeCollections())`,
- `NewJSONRPCErrorResponse(req.ID, JSONRPCErrorInternal, err.Error(), nil)`,
- `NewJSONRPCErrorResponse(req.ID, JSONRPCErrorMethodNotFound, fmt.Sprintf("method not found: %s", req.Method), nil)`,
- `func DecodeMCPCallToolParams(`,
- `params = NormalizeToolCallParams(params)`,
- `ValidateToolCallParams(params)`,
- `func PrepareToolRegistryExecution(name string, args map[string]any) (ToolCallParams, ToolResult, bool)`,
- `func NewInvalidToolCallParamsResult(err error) ToolResult`,
- `func NewUnknownToolResult(name string) ToolResult`,
- `func NewControlToolsDisabledToolResult() ToolResult`,
- `func ExecuteMCPManifestSurfaceToolHTTP(`,
- `DecodeMCPCallToolParams(raw)`,
- `ManifestSurfaceAffordances(manifest, surfaceID)`,
- `ManifestSurfaceToolCapabilities(manifest, surfaceID)`,
- `return ExecuteCapabilityToolHTTP(ctx, client, baseURL, token, ManifestSurfaceToolCapabilities(manifest, surfaceID), params)`,
- `OutputSchema: ToolOutputSchema(cap)`,
- `func ToolOutputSchema(cap Capability) json.RawMessage`,
- `func ExecuteCapabilityToolHTTP(`,
- `params = NormalizeToolCallParams(params)`,
- `ValidateToolCallParams(params)`,
- `CallRequestResponseCapabilityHTTPByName(ctx, client, baseURL, token, capabilities, params.Name, params.Arguments)`,
- `var lookupErr CapabilityLookupError`,
- `errors.As(err, &lookupErr)`,
- `return NewCapabilityHTTPToolResult(resp), nil`,
- `func NewToolTextContent(text string) ToolContent`,
- `func NewToolTextResult(text string) ToolResult`,
- `func NewToolErrorResult(err error) ToolResult`,
- `func NewToolJSONResult(data any) ToolResult`,
- `func NewToolJSONResultWithIsError(data any, isError bool) ToolResult`,
- `func NewToolHTTPTextResult(`,
- `func NewCapabilityHTTPToolResult(`,
- `func ToolStructuredContentFromJSON(`,
- `func CloneToolStructuredContent(`,
- `func ToolResultText(result ToolResult) string`,
- `type ToolResultInterpretation struct`,
- `func InterpretToolResult(result ToolResult) ToolResultInterpretation`,
- `ApprovalRequired: HasApprovalRequiredToolMarker(text)`,
- `PolicyBlocked: HasPolicyBlockedToolMarker(text)`,
- `type DirectToolExecutionOptions struct`,
- `type DirectToolExecutionOutcome struct`,
- `func InterpretDirectToolExecution(result ToolResult, opts DirectToolExecutionOptions) (DirectToolExecutionOutcome, error)`,
- `resp.OK()`,
- `func NewJSONRPCNotification(`,
- `func NewMCPEventNotification(`,
- `const (`,
- `MCPProtocolVersion = "2025-06-18"`,
- `MCPMethodResourcesList = "resources/list"`,
- `MCPMethodResourcesRead = "resources/read"`,
- `MCPMethodPromptsList = "prompts/list"`,
- `MCPMethodPromptsGet = "prompts/get"`,
- `MCPResourceContextURIHost = "resource"`,
- `MCPResourceContextMIMEType = "application/json"`,
- } {
- if !strings.Contains(mcpWireContract, fragment) {
- t.Errorf("agentcapabilities must own the shared MCP wire/result envelope; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func MCPResourceProjectionSupported(capabilities []Capability) bool`,
- `func ListMCPResourcesHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, capabilities []Capability)`,
- `func ReadMCPResourceHTTP(ctx context.Context, client HTTPDoer, baseURL, token string, capabilities []Capability`,
- `return ListMCPResourcesHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest.Capabilities)`,
- `return ReadMCPResourceHTTP(ctx, s.Client, s.BaseURL, s.Token, s.Manifest.Capabilities, raw)`,
- } {
- if strings.Contains(mcpWireContract, fragment) {
- t.Errorf("shared MCP resource projection must be manifest-surface-owned, not raw-capability-owned; found %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func MCPPromptProjectionSupported(capabilities []Capability) bool`,
- `func ProjectMCPPrompts(capabilities []Capability) []MCPPrompt`,
- `func GetMCPPrompt(capabilities []Capability, raw json.RawMessage)`,
- `func BuildMCPPrompt(capabilities []Capability, params MCPGetPromptParams)`,
- `return GetMCPPromptFromManifest(s.Manifest, raw)`,
- } {
- if strings.Contains(mcpWireContract, fragment) {
- t.Errorf("shared MCP prompt projection must be manifest-owned, not raw-capability-owned; found %s", fragment)
- }
- }
- for _, fragment := range []string{
- `type ToolCallParams struct`,
- `func NormalizeToolCallParams(params ToolCallParams) ToolCallParams`,
- `func ValidateToolCallParams(params ToolCallParams) error`,
- `func PrepareToolRegistryExecution(name string, args map[string]any) (ToolCallParams, ToolResult, bool)`,
- `func NewInvalidToolCallParamsResult(err error) ToolResult`,
- `func NewUnknownToolResult(name string) ToolResult`,
- `func NewControlToolsDisabledToolResult() ToolResult`,
- `type ProjectedTool struct`,
- `OutputSchema json.RawMessage`,
- `Meta map[string]any`,
- `type ToolContent struct`,
- `type ToolResult struct`,
- `StructuredContent map[string]any`,
- `func EmptyToolResult() ToolResult`,
- `func (r ToolResult) NormalizeCollections() ToolResult`,
- `func NewToolTextContent(text string) ToolContent`,
- `func NewToolTextResult(text string) ToolResult`,
- `func NewToolErrorResult(err error) ToolResult`,
- `func NewToolJSONResult(data any) ToolResult`,
- `func NewToolHTTPTextResult(`,
- `func NewCapabilityHTTPToolResult(`,
- `func ToolOutputSchema(cap Capability) json.RawMessage`,
- `func ToolStructuredContentFromJSON(`,
- `func CloneToolStructuredContent(`,
- `func ToolResultText(result ToolResult) string`,
- `type ToolResultInterpretation struct`,
- `func InterpretToolResult(result ToolResult) ToolResultInterpretation`,
- `func ExecuteCapabilityToolHTTP(`,
- `type DirectToolExecutionOptions struct`,
- `type DirectToolExecutionOutcome struct`,
- `func InterpretDirectToolExecution(result ToolResult, opts DirectToolExecutionOptions) (DirectToolExecutionOutcome, error)`,
- } {
- if strings.Contains(mcpWire, fragment) {
- t.Errorf("neutral Pulse Intelligence tool primitive must not be implemented in mcp.go; found %s", fragment)
- }
- if !strings.Contains(toolCore, fragment) {
- t.Errorf("neutral Pulse Intelligence tool primitive must live outside mcp.go; missing %s", fragment)
- }
- }
-
- workflowPromptSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "workflow_prompt.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/workflow_prompt.go: %v", err)
- }
- workflowPromptCore := string(workflowPromptSource)
- for _, fragment := range []string{
- `PulseWorkflowPromptTriageFleet = "pulse_triage_fleet"`,
- `PulseWorkflowPromptOperationsLoop`,
- `MCPPromptTriageFleet = PulseWorkflowPromptTriageFleet`,
- `MCPPromptOperationsLoop`,
- `type PulseWorkflowPrompt struct`,
- `type PulseWorkflowPromptArgument struct`,
- `type PulseWorkflowPromptParams struct`,
- `type PulseWorkflowPromptResult struct`,
- `type PulseWorkflowPromptRenderOptions struct`,
- `func ManifestPulseWorkflowPrompts(manifest Manifest) []PulseWorkflowPrompt`,
- `func ProjectPulseWorkflowPrompts(capabilities []Capability) []PulseWorkflowPrompt`,
- `func BuildPulseWorkflowPrompt(capabilities []Capability, params PulseWorkflowPromptParams) (PulseWorkflowPromptResult, error)`,
- `func BuildPulseWorkflowPromptWithOptions(capabilities []Capability, params PulseWorkflowPromptParams, opts PulseWorkflowPromptRenderOptions) (PulseWorkflowPromptResult, error)`,
- `func BuildPulseWorkflowPromptFromManifest(manifest Manifest, params PulseWorkflowPromptParams) (PulseWorkflowPromptResult, error)`,
- `func BuildPulseWorkflowPromptFromManifestWithOptions(manifest Manifest, params PulseWorkflowPromptParams, opts PulseWorkflowPromptRenderOptions) (PulseWorkflowPromptResult, error)`,
- `func RequiredPulseWorkflowPromptArgument(args map[string]string, name string) (string, error)`,
- `Name: ResourceIDArgumentName`,
- `RequiredPulseWorkflowPromptArgument(params.Arguments, ResourceIDArgumentName)`,
- `ResourceIDArgumentName, resourceID`,
- `Name: FindingIDArgumentName`,
- `FindCapability(capabilities, ListFindingsCapabilityName)`,
- `RequiredPulseWorkflowPromptArgument(params.Arguments, FindingIDArgumentName)`,
- `ListFindingsCapabilityName`,
- `PlanActionCapabilityName`,
- `DecideActionCapabilityName`,
- `ExecuteActionCapabilityName`,
- `ResolveFindingCapabilityName`,
- `Triage the Pulse fleet using the canonical fleet context capability`,
- `Review one Patrol finding and propose the safest governed next step`,
- `Patrol issue handling`,
- `Do not execute write tools unless the operator explicitly asks for a governed action`,
- } {
- if !strings.Contains(workflowPromptCore, fragment) {
- t.Errorf("neutral Pulse Intelligence workflow prompt contract must live outside mcp.go; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func PulseWorkflowPromptProjectionSupported(capabilities []Capability) bool`,
- } {
- if strings.Contains(workflowPromptCore, fragment) {
- t.Errorf("shared workflow prompt projection must be manifest-owned, not raw-capability-owned; found %s", fragment)
- }
- }
- for _, fragment := range []string{
- `Pulse fleet triage`,
- `Triage the Pulse fleet using the canonical fleet context capability`,
- `Review one Patrol finding and propose the safest governed next step`,
- `prompt argument %s is required`,
- `func RequiredPulseWorkflowPromptArgument`,
- } {
- if strings.Contains(mcpWire, fragment) {
- t.Errorf("MCP edge must not own neutral Pulse Intelligence workflow prompt behavior; found %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func NormalizeMCPCallToolParams(`,
- `func ValidateMCPCallToolParams(`,
- `func ProjectProviderToolCallToMCP(`,
- `func PrepareMCPToolRegistryExecution(`,
- `func NewInvalidMCPToolCallParamsResult(`,
- `func NewUnknownMCPToolResult(`,
- `func NewControlToolsDisabledMCPToolResult(`,
- `func EmptyMCPToolResult(`,
- `func NewMCPTextContent(`,
- `func NewMCPTextResult(`,
- `func NewMCPErrorResult(`,
- `func NewProviderToolResultFromMCP(`,
- `func NewMCPToolResponseResult(`,
- `func NewMCPJSONResult(`,
- `func NewMCPJSONResultWithIsError(`,
- `func NewMCPHTTPTextResult(`,
- `func NewMCPCapabilityHTTPResult(`,
- `func MCPToolResultText(`,
- `type MCPToolResultInterpretation`,
- `func InterpretMCPToolResult(`,
- `type DirectMCPToolExecutionOptions`,
- `type DirectMCPToolExecutionOutcome`,
- `func InterpretDirectMCPToolExecution(`,
- } {
- if strings.Contains(mcpWire, fragment) {
- t.Errorf("MCP edge must not preserve compatibility wrappers around neutral tool helpers; found %s", fragment)
- }
- }
-
- sseSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "sse.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/sse.go: %v", err)
- }
- sse := string(sseSource)
- for _, fragment := range []string{
- `type SSERecord struct`,
- `const AgentSSEAccept = "text/event-stream"`,
- `func ScanSSERecords(`,
- `scanner.Buffer(make([]byte, 64*1024), 1<<22)`,
- `case "event":`,
- `case "data":`,
- `strings.Join(dataLines, "\n")`,
- `func StreamAgentSSERecords(`,
- `NewAgentHTTPRequest(ctx, http.MethodGet, baseURL, path, token, nil)`,
- `req.Header.Set("Accept", AgentSSEAccept)`,
- // SSE must use the same redirect-origin boundary as manifest and tool reads.
- `DoAgentHTTPRequest(client, req)`,
- `ScanSSERecords(resp.Body, handle)`,
- `func IsActionableSSERecord(`,
- `func StreamAgentActionableSSERecords(`,
- `type MCPEventNotificationWriter func(JSONRPCRequest) error`,
- `func StreamMCPEventNotifications(`,
- `StreamAgentActionableSSERecords(ctx, client, baseURL, path, token, func(record SSERecord) bool`,
- `NewMCPEventNotification(record.Event, []byte(record.Data))`,
- } {
- if !strings.Contains(sse, fragment) {
- t.Errorf("agentcapabilities must own the shared agent SSE parser, subscription transport, and MCP notification bridge; missing %s", fragment)
- }
- }
-
- textInvocationSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "text_tool_invocation.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/text_tool_invocation.go: %v", err)
- }
- textInvocation := string(textInvocationSource)
- for _, fragment := range []string{
- `func IsTextToolInvocation(command string) bool`,
- `func ParseTextToolInvocation(command string) (ToolCallParams, error)`,
- `const ApprovalArgumentKey = "_approval_id"`,
- `func ApprovalArgument(args map[string]any) string`,
- `func IsInternalToolArgument(name string) bool`,
- `func CloneToolArguments(args map[string]any) map[string]any`,
- `func PublicToolArguments(args map[string]any) map[string]any`,
- `func WithApprovalArgument(args map[string]any, approvalID string) map[string]any`,
- `cloned[k] = cloneSchemaValue(v)`,
- `public[k] = cloneSchemaValue(v)`,
- `strings.TrimPrefix(command, "default_api:")`,
- `args := make(map[string]any)`,
- `ToolCallParams{Name: toolName, Arguments: args}`,
- `ValidateToolCallParams(params)`,
- `func splitTextToolArguments(argsStr string) []string`,
- } {
- if !strings.Contains(textInvocation, fragment) {
- t.Errorf("agentcapabilities must own the shared text tool invocation parser; missing %s", fragment)
- }
- }
-
- aiRelaySource, err := os.ReadFile("router_routes_ai_relay.go")
- if err != nil {
- t.Fatalf("read internal/api/router_routes_ai_relay.go: %v", err)
- }
- aiRelay := string(aiRelaySource)
- for _, fragment := range []string{
- `agentcapabilities.ParseTextToolInvocation(command)`,
- `params.Arguments = agentcapabilities.WithApprovalArgument(params.Arguments, approvalID)`,
- `chatService.ExecuteAssistantTool(ctx, params.Name, params.Arguments)`,
- } {
- if !strings.Contains(aiRelay, fragment) {
- t.Errorf("AI relay MCP executor must consume the shared text tool invocation parser; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func parseMCPToolCall(`,
- `func splitToolArgs(`,
- `func isMCPToolCall(`,
- `params.Arguments["_approval_id"]`,
- } {
- if strings.Contains(aiRelay, fragment) {
- t.Errorf("AI relay must not preserve local text tool invocation parsing; found %s", fragment)
- }
- }
-
- assistantToolFiles := []string{
- filepath.Join("..", "ai", "chat", "agentic.go"),
- filepath.Join("..", "ai", "tools", "tools_control.go"),
- filepath.Join("..", "ai", "tools", "tools_docker.go"),
- filepath.Join("..", "ai", "tools", "tools_file.go"),
- filepath.Join("..", "ai", "tools", "tools_kubernetes.go"),
- }
- for _, path := range assistantToolFiles {
- source, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("read %s: %v", path, err)
- }
- if strings.Contains(string(source), `["_approval_id"]`) {
- t.Errorf("%s must consume shared approved-action argument helpers instead of local key indexing", path)
- }
- }
-
- httpSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "http.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/http.go: %v", err)
- }
- agentHTTP := string(httpSource)
- for _, fragment := range []string{
- `const (`,
- `AgentCapabilitiesPath = "/api/agent/capabilities"`,
- `AgentAPITokenHeader = "X-API-Token"`,
- `type HTTPCallResponse struct`,
- `func NewAgentHTTPRequest(`,
- `func FetchManifest(`,
- `func BuildCapabilityHTTPRequest(`,
- `func CallCapabilityHTTP(`,
- `func DoAgentHTTPRequest(`,
- `DoAgentHTTPRequest(client, req)`,
- `func CallCapabilityHTTPByName(`,
- `func CallRequestResponseCapabilityHTTPByName(`,
- `func (r HTTPCallResponse) FailureError() error`,
- `ProjectCapabilityCall(cap, args)`,
- `ResolveRequestResponseCapability(capabilities, name)`,
- `ResolveCapability(capabilities, name)`,
- `DecodeErrorEnvelope(r.Body)`,
- } {
- if !strings.Contains(agentHTTP, fragment) {
- t.Errorf("agentcapabilities must own the shared agent HTTP substrate; missing %s", fragment)
- }
- }
- if !strings.Contains(projection, `for k, v := range PublicToolArguments(args)`) {
- t.Error("manifest-backed HTTP projection must strip internal tool-call arguments before building public request bodies")
- }
-
- toolResponseSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_response.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/tool_response.go: %v", err)
- }
- toolResponse := string(toolResponseSource)
- for _, fragment := range []string{
- `type ToolResponse struct`,
- `type ToolError struct`,
- `ErrCodeFSMBlocked`,
- `ErrCodeStrictResolution`,
- `ErrCodeRoutingMismatch`,
- `ErrCodeExecutionContextUnavailable`,
- `func NewToolBlockedError(`,
- `func NewToolResponseResult(resp ToolResponse) ToolResult`,
- `func ToolResultErrorCode(resultText string) (string, bool)`,
- `func ToolResultHasErrorCode(resultText, code string) bool`,
- `func ToolResultHasVerificationOK(resultText string) bool`,
- } {
- if !strings.Contains(toolResponse, fragment) {
- t.Errorf("agentcapabilities must own the shared tool response envelope; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func NewMCPToolResponseResult(`,
- } {
- if strings.Contains(toolResponse, fragment) {
- t.Errorf("neutral tool response envelope must not own MCP compatibility wrappers; found %s", fragment)
- }
- }
-
- toolMarkerSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "tool_marker.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/tool_marker.go: %v", err)
- }
- toolMarker := string(toolMarkerSource)
- for _, fragment := range []string{
- `ToolMarkerApprovalRequiredPrefix = ErrCodeApprovalRequired + ":"`,
- `ToolMarkerPolicyBlockedPrefix = ErrCodePolicyBlocked + ":"`,
- `ToolMarkerApprovalRequiredType = "approval_required"`,
- `ToolMarkerPolicyBlockedType = "policy_blocked"`,
- `type ApprovalRequiredToolMarkerData struct`,
- `func (d ApprovalRequiredToolMarkerData) TargetHint() string`,
- `func (d ApprovalRequiredToolMarkerData) DescriptionText() string`,
- `func ApprovalRequiredToolMarker(`,
- `func PolicyBlockedToolMarker(`,
- `func FormatApprovalRequiredToolMarker(`,
- `func FormatPolicyBlockedToolMarker(`,
- `func HasApprovalRequiredToolMarker(`,
- `func HasPolicyBlockedToolMarker(`,
- `func ApprovalRequiredToolMarkerPayloadJSON(`,
- `func ParseApprovalRequiredToolMarkerPayload(`,
- `func ParseApprovalRequiredToolMarkerData(`,
- } {
- if !strings.Contains(toolMarker, fragment) {
- t.Errorf("agentcapabilities must own the shared Assistant tool marker vocabulary; missing %s", fragment)
- }
- }
-
- controlLevelSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "control_level.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/control_level.go: %v", err)
- }
- controlLevel := string(controlLevelSource)
- for _, fragment := range []string{
- `type ControlLevel string`,
- `ControlLevelReadOnly`,
- `ControlLevelControlled`,
- `ControlLevelAutonomous`,
- `func NormalizeControlLevel(`,
- `func IsValidControlLevel(`,
- `func ControlLevelAllowsControlTools(`,
- } {
- if !strings.Contains(controlLevel, fragment) {
- t.Errorf("agentcapabilities must own the shared control-level contract; missing %s", fragment)
- }
- }
-
- typesSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "types.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/types.go: %v", err)
- }
- typesSrc := string(typesSource)
- for _, fragment := range []string{
- `const ControlToolsDisabledMessage = "Control tools are disabled.`,
- `func NormalizeToolGovernance(`,
- `func NormalizeCapabilityGovernance(cap Capability) ToolGovernance`,
- `func CapabilityActionMode(cap Capability) ActionMode`,
- `func NewToolGovernanceDescriptor(`,
- `func NormalizeToolGovernanceDescriptor(descriptor ToolGovernanceDescriptor) ToolGovernanceDescriptor`,
- `governance.ActionMode = ActionModeWrite`,
- `CapabilityActionMode(cap)`,
- `governance.ApprovalPolicy = ApprovalPolicyActionPlan`,
- `DefaultApprovalPolicyDescription(governance.ApprovalPolicy)`,
- `ToolGovernanceDescriptor{`,
- } {
- if !strings.Contains(typesSrc, fragment) {
- t.Errorf("agentcapabilities must own shared tool-governance defaults; missing %s", fragment)
- }
- }
- governancePromptSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "governance_prompt.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/governance_prompt.go: %v", err)
- }
- governancePromptSrc := string(governancePromptSource)
- for _, fragment := range []string{
- `type ToolGovernancePromptOptions struct`,
- `type PulseIntelligenceOperatingInstructionOptions struct`,
- `func BuildToolGovernancePromptSection(`,
- `func BuildAssistantToolGovernancePromptSection(`,
- `func BuildPulseIntelligenceOperatingInstructions() string`,
- `func BuildPulseAssistantOperatingInstructions() string`,
- `type PulseMCPOperatingInstructionOptions struct`,
- `func BuildPulseMCPOperatingInstructions(`,
- `func BuildPulseIntelligenceOperatingInstructionsForSurface(`,
- `ResolveSurfaceAffordanceContract(`,
- `func ToolGovernancePromptLine(`,
- `func ToolGovernancePromptDescription(`,
- `func AssistantGovernanceOfferedToolNames(`,
- `AdditionalToolGovernanceLines []string`,
- `const PulseQuestionToolName = "pulse_question"`,
- `func PulseQuestionToolGovernancePromptLine() string`,
- `SupportsInteractiveQuestions bool`,
- `SurfaceAffordanceLabels(surfaceAffordancesFromOptions(opts))`,
- `## PULSE INTELLIGENCE OPERATING MODEL`,
- `No Pulse tools are offered for this turn.`,
- `This manifest is generated from Pulse's governed tool registry.`,
- `ApprovalPolicyScopeOnly`,
- `ActionModeRead`,
- } {
- if !strings.Contains(governancePromptSrc, fragment) {
- t.Errorf("agentcapabilities must own shared tool-governance prompt projection; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func CloneCapability(cap Capability) Capability`,
- `func CloneCapabilities(capabilities []Capability) []Capability`,
- `cap.InputSchema = CloneRawMessage(cap.InputSchema)`,
- } {
- if !strings.Contains(typesSrc, fragment) {
- t.Errorf("agentcapabilities must own detached capability projection helpers; missing %s", fragment)
- }
- }
-
- textToolInvocationSource, err := os.ReadFile(filepath.Join("..", "agentcapabilities", "text_tool_invocation.go"))
- if err != nil {
- t.Fatalf("read internal/agentcapabilities/text_tool_invocation.go: %v", err)
- }
- textToolInvocation := string(textToolInvocationSource)
- for _, fragment := range []string{
- `const CurrentResourceHandle = "current_resource"`,
- `func IsCurrentResourceReference(value string) bool`,
- `func ToolInputContainsCurrentResourceReference(value any) bool`,
- `currentResourceReferenceAliases`,
- `"redacted by policy"`,
- } {
- if !strings.Contains(textToolInvocation, fragment) {
- t.Errorf("agentcapabilities must own shared current_resource tool-argument semantics; missing %s", fragment)
- }
- }
-
- configSource, err := os.ReadFile(filepath.Join("..", "config", "ai.go"))
- if err != nil {
- t.Fatalf("read internal/config/ai.go: %v", err)
- }
- configAI := string(configSource)
- for _, fragment := range []string{
- `ControlLevelReadOnly = string(agentcapabilities.ControlLevelReadOnly)`,
- `ControlLevelControlled = string(agentcapabilities.ControlLevelControlled)`,
- `ControlLevelAutonomous = string(agentcapabilities.ControlLevelAutonomous)`,
- `return string(agentcapabilities.NormalizeControlLevel(c.ControlLevel))`,
- `return agentcapabilities.ControlLevelAllowsControlTools(agentcapabilities.ControlLevel(c.GetControlLevel()))`,
- `return agentcapabilities.IsValidControlLevel(level)`,
- } {
- if !strings.Contains(configAI, fragment) {
- t.Errorf("AI config must alias shared control-level vocabulary; missing %s", fragment)
- }
- }
-
- assistantProtocol, err := os.ReadFile(filepath.Join("..", "ai", "tools", "protocol.go"))
- if err != nil {
- t.Fatalf("read internal/ai/tools/protocol.go: %v", err)
- }
- assistantSrc := string(assistantProtocol)
- for _, fragment := range []string{
- `type Tool = agentcapabilities.Tool`,
- `type CallToolResult = agentcapabilities.ToolResult`,
- `type Content = agentcapabilities.ToolContent`,
- `type CallToolParams = agentcapabilities.ToolCallParams`,
- `type ToolResponse = agentcapabilities.ToolResponse`,
- `type ToolError = agentcapabilities.ToolError`,
- `ErrCodeStrictResolution`,
- `agentcapabilities.ErrCodeStrictResolution`,
- `ErrCodeRoutingMismatch`,
- `agentcapabilities.ErrCodeRoutingMismatch`,
- `return agentcapabilities.NewToolTextResult(text)`,
- `return agentcapabilities.NewToolJSONResultWithIsError(data, isError)`,
- `return agentcapabilities.NewToolResponseResult(resp)`,
- } {
- if !strings.Contains(assistantSrc, fragment) {
- t.Errorf("Assistant tool protocol must wrap the shared tool result envelope; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `type Request = agentcapabilities.JSONRPCRequest`,
- `type Response = agentcapabilities.JSONRPCResponse`,
- `type Error = agentcapabilities.JSONRPCError`,
- `type InitializeResult = agentcapabilities.MCPInitializeResult`,
- `type ServerInfo = agentcapabilities.MCPServerInfo`,
- `type ListToolsResult = agentcapabilities.MCPListToolsResult`,
- `type Resource = agentcapabilities.MCPResource`,
- `type Prompt = agentcapabilities.MCPPrompt`,
- } {
- if strings.Contains(assistantSrc, fragment) {
- t.Errorf("native Assistant tool protocol must not expose MCP/JSON-RPC wire aliases; found %s", fragment)
- }
- }
-
- providerSource, err := os.ReadFile(filepath.Join("..", "ai", "providers", "provider.go"))
- if err != nil {
- t.Fatalf("read internal/ai/providers/provider.go: %v", err)
- }
- providerSrc := string(providerSource)
- for _, fragment := range []string{
- `type Tool = agentcapabilities.ProviderTool`,
- `type ToolCall = agentcapabilities.ProviderToolCall`,
- `type ToolResult = agentcapabilities.ProviderToolResult`,
- `return agentcapabilities.EmptyProviderTool()`,
- `return agentcapabilities.EmptyProviderToolCall()`,
- } {
- if !strings.Contains(providerSrc, fragment) {
- t.Errorf("Assistant providers must alias the shared provider tool shape; missing %s", fragment)
- }
- }
-
- for _, path := range []string{
- filepath.Join("..", "ai", "chat", "tools.go"),
- filepath.Join("..", "ai", "tools", "schema_projection.go"),
- } {
- if _, err := os.Stat(path); err == nil {
- t.Errorf("%s must not keep provider projection compatibility wrappers; use internal/agentcapabilities directly", path)
- } else if !os.IsNotExist(err) {
- t.Fatalf("stat %s: %v", path, err)
- }
- }
-
- assistantQuestionToolSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic_question_tool.go"))
- if err != nil {
- t.Fatalf("read internal/ai/chat/agentic_question_tool.go: %v", err)
- }
- assistantQuestionToolSrc := string(assistantQuestionToolSource)
- for _, fragment := range []string{
- `const pulseQuestionToolName = agentcapabilities.PulseQuestionToolName`,
- } {
- if !strings.Contains(assistantQuestionToolSrc, fragment) {
- t.Errorf("Assistant question tool must use shared provider declaration; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `InputSchema: map[string]interface{}{`,
- `Name: pulseQuestionToolName`,
- `Description: "Ask the user for missing information using a structured prompt.`,
- `func userQuestionTool()`,
- `type questionToolInputPayload struct`,
- `type questionToolInputQuestion struct`,
- `type questionToolInputOption struct`,
- `func parseQuestionToolOptions(`,
- `type questionToolType string`,
- `questionToolTypeText`,
- `questionToolTypeSelect`,
- `func normalizeQuestionToolType(`,
- `agentcapabilities.NormalizePulseQuestionToolType(parsedQuestion.Type, len(opts) > 0)`,
- } {
- if strings.Contains(assistantQuestionToolSrc, fragment) {
- t.Errorf("Assistant question tool must not keep a chat-local provider declaration; found %s", fragment)
- }
- }
-
- assistantToolKindSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "tool_kind.go"))
- if err != nil {
- t.Fatalf("read internal/ai/chat/tool_kind.go: %v", err)
- }
- assistantToolKindSrc := string(assistantToolKindSource)
- for _, fragment := range []string{
- `type ToolKind = agentcapabilities.ToolCallKind`,
- `ToolKindResolve = agentcapabilities.ToolCallKindResolve`,
- `ToolKindRead = agentcapabilities.ToolCallKindRead`,
- `ToolKindWrite = agentcapabilities.ToolCallKindWrite`,
- `ToolKindUserInput = agentcapabilities.ToolCallKindUserInput`,
- `return agentcapabilities.ClassifyToolCall(toolName, args)`,
- } {
- if !strings.Contains(assistantToolKindSrc, fragment) {
- t.Errorf("Assistant must consume shared tool-call safety classification; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `case agentcapabilities.PulseQuestionToolName:`,
- `case "pulse_question":`,
- `case "pulse_control":`,
- `case "pulse_read":`,
- `writeActions := map[string]bool`,
- `readActions := map[string]bool`,
- `actionLower := strings.ToLower(action)`,
- } {
- if strings.Contains(assistantToolKindSrc, fragment) {
- t.Errorf("Assistant must not keep local tool-call safety classification; found %s", fragment)
- }
- }
-
- chatTypesSource, err := os.ReadFile(filepath.Join("..", "ai", "chat", "types.go"))
- if err != nil {
- t.Fatalf("read internal/ai/chat/types.go: %v", err)
- }
- chatTypesSrc := string(chatTypesSource)
- for _, fragment := range []string{
- `func ToolCallFromProvider(tc agentcapabilities.ProviderToolCall) ToolCall`,
- `type ToolCall = agentcapabilities.TranscriptToolCall`,
- `type ToolResult = agentcapabilities.ProviderToolResult`,
- } {
- if !strings.Contains(chatTypesSrc, fragment) {
- t.Errorf("Assistant chat transcript must project through shared provider tool shapes; missing %s", fragment)
- }
- }
-
- aiServiceSource, err := os.ReadFile(filepath.Join("..", "ai", "service.go"))
- if err != nil {
- t.Fatalf("read internal/ai/service.go: %v", err)
- }
- aiServiceSrc := string(aiServiceSource)
- for _, fragment := range []string{
- `type ChatToolCall = agentcapabilities.TranscriptToolCall`,
- `return ChatToolCall{}.NormalizeCollections()`,
- `type ChatToolResult = agentcapabilities.ProviderToolResult`,
- `return agentcapabilities.ApprovalRequiredToolMarker(`,
- `return agentcapabilities.PolicyBlockedToolMarker(command, reason)`,
- `agentcapabilities.ParseApprovalRequiredToolMarkerData(result)`,
- `agentcapabilities.HasApprovalRequiredToolMarker(result)`,
- `agentcapabilities.LegacyAssistantUtilityProviderTools()`,
- `agentcapabilities.LegacyAssistantRunCommandToolName`,
- `agentcapabilities.LegacyAssistantCommandArgumentName`,
- `agentcapabilities.LegacyAssistantURLArgumentName`,
- `agentcapabilities.LegacyAssistantResourceTypeArgumentName`,
- `agentcapabilities.LegacyAssistantResourceIDArgumentName`,
- `projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, !execution.Success)`,
- `projection := newLegacyServiceProviderToolResultContextProjection(tc.ID, result, true)`,
- `agentcapabilities.NewProviderToolResultContextProjection(toolUseID, content, isError, legacyServiceProviderToolResultContextOptions())`,
- `ToolResult: &projection.Model`,
- } {
- if !strings.Contains(aiServiceSrc, fragment) {
- t.Errorf("AI service chat messages and tool markers must use shared provider/tool shapes; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `ToolResult: &providers.ToolResult{`,
- `resultForContext`,
- `maxResultSize`,
- `output truncated (`,
- } {
- if strings.Contains(aiServiceSrc, fragment) {
- t.Errorf("AI service must not preserve local provider-result context shaping; found %s", fragment)
- }
- }
- for _, fragment := range []string{
- `Name: "run_command"`,
- `Name: "fetch_url"`,
- `Name: "set_resource_url"`,
- `case "run_command":`,
- `case "fetch_url":`,
- `case "set_resource_url":`,
- `tc.Input["command"]`,
- `tc.Input["run_on_host"]`,
- `tc.Input["target_host"]`,
- `tc.Input["url"]`,
- `tc.Input["resource_type"]`,
- `tc.Input["resource_id"]`,
- } {
- if strings.Contains(aiServiceSrc, fragment) {
- t.Errorf("legacy Assistant utility tool schemas and input keys must stay in agentcapabilities; AI service found %s", fragment)
- }
- }
- if strings.Contains(aiServiceSrc, `func parseApprovalNeededMarker(`) {
- t.Error("AI service approval marker handling must call the shared marker parser directly")
- }
-
- assistantChatAgentic, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic.go"))
- if err != nil {
- t.Fatalf("read internal/ai/chat/agentic.go: %v", err)
- }
- agenticSrc := string(assistantChatAgentic)
- if strings.Contains(agenticSrc, "IncludeQuestionTool: true") {
- t.Error("agentic loop must not offer pulse_question: no Pulse client can answer it since the web chat was retired")
- }
- for _, fragment := range []string{
- `providerTools := executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{`,
- `a.tools = a.executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{`,
- `agentcapabilities.HasApprovalRequiredToolMarker(resultText)`,
- `agentcapabilities.ParseApprovalRequiredToolMarkerData(resultText)`,
- `inputWithApproval = agentcapabilities.WithApprovalArgument(inputWithApproval, approvalData.ApprovalID)`,
- `agentcapabilities.NewProviderToolResultFromToolResult(tc.ID, result)`,
- `projection := newProviderToolResultContextProjection(tc.ID, resultText, isError)`,
- `ToolResult: &projection.Transcript`,
- `ToolResult: &projection.Model`,
- `toolCalls = agentcapabilities.NormalizeProviderToolCallsForExecution(data.ToolCalls)`,
- `agentcapabilities.ToolInputContainsCurrentResourceReference(tc.Input)`,
- } {
- if !strings.Contains(agenticSrc, fragment) {
- t.Errorf("Assistant agentic loop must use shared provider-result and marker vocabulary; missing %s", fragment)
- }
- }
- if strings.Contains(agenticSrc, `ProjectAssistantProviderTools(`) || strings.Contains(agenticSrc, `ListToolGovernance()`) {
- t.Error("Assistant agentic loop must request provider-tool projection from the shared executor entrypoint")
- }
- if strings.Contains(agenticSrc, `resultText = FormatToolResult(result)`) {
- t.Error("Assistant agentic loop must project MCP tool results through shared provider-result construction, not local result text assignment")
- }
- for _, fragment := range []string{
- `agentcapabilities.ApprovalRequiredToolMarkerPayloadJSON(resultText)`,
- `var approvalData struct`,
- "\n\t\t\t\t\t\t\tagentcapabilities.WithApprovalArgument(inputWithApproval, approvalData.ApprovalID)",
- `ToolResult: &providers.ToolResult{`,
- `ToolResult: &ToolResult{`,
- `modelResultText := truncateToolResultForModel(resultText)`,
- `func toolInputContainsCurrentResourceReference`,
- `append(providerTools, userQuestionTool())`,
- `userQuestionTool()`,
- `toolCalls = NormalizeProviderToolCallsForExecution(data.ToolCalls)`,
- `func ConvertPulseToolsToProvider`,
- `func ConvertPulseToolsToProviderWithGovernance`,
- `func ConvertProviderToolCallToMCP`,
- `func NormalizeProviderToolCallForExecution`,
- `func NormalizeProviderToolCallsForExecution`,
- } {
- if strings.Contains(agenticSrc, fragment) {
- t.Errorf("Assistant agentic loop must not assemble provider tool-result structs locally; found %s", fragment)
- }
- }
-
- currentResourceSource, err := os.ReadFile(filepath.Join("..", "ai", "tools", "current_resource.go"))
- if err != nil {
- t.Fatalf("read internal/ai/tools/current_resource.go: %v", err)
- }
- currentResourceSrc := string(currentResourceSource)
- for _, fragment := range []string{
- `const currentResourceHandle = agentcapabilities.CurrentResourceHandle`,
- `return agentcapabilities.IsCurrentResourceReference(value)`,
- } {
- if !strings.Contains(currentResourceSrc, fragment) {
- t.Errorf("Assistant current_resource executor must use shared handle semantics; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `"attached_resource"`,
- `"selected_resource"`,
- `"this_resource"`,
- `"redacted by policy"`,
- } {
- if strings.Contains(currentResourceSrc, fragment) {
- t.Errorf("Assistant current_resource executor must not keep local handle aliases; found %s", fragment)
- }
- }
-
- assistantChatContext, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic_context.go"))
- if err != nil {
- t.Fatalf("read internal/ai/chat/agentic_context.go: %v", err)
- }
- agenticContextSrc := string(assistantChatContext)
- for _, fragment := range []string{
- `agentcapabilities.ProviderToolResultModelContent(text, providerToolResultContextOptions())`,
- `agentcapabilities.NewProviderToolResultContextProjection(toolUseID, content, isError, providerToolResultContextOptions())`,
- `pm.ToolResult = &projection.Model`,
- `agentcapabilities.NewProviderToolErrorResult(`,
- } {
- if !strings.Contains(agenticContextSrc, fragment) {
- t.Errorf("Assistant provider message conversion must use shared provider-result construction; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `func newProviderToolResult(`,
- `func newProviderToolErrorResult(`,
- `ToolResult: &providers.ToolResult{`,
- } {
- if strings.Contains(agenticContextSrc, fragment) {
- t.Errorf("Assistant provider message conversion must not preserve local provider-result wrappers or structs; found %s", fragment)
- }
- }
-
- assistantChatService, err := os.ReadFile(filepath.Join("..", "ai", "chat", "service.go"))
- if err != nil {
- t.Fatalf("read internal/ai/chat/service.go: %v", err)
- }
- chatServiceSrc := string(assistantChatService)
- if strings.Contains(chatServiceSrc, "IncludeQuestionTool:") {
- t.Error("chat service must not offer pulse_question: no Pulse client can answer it since the web chat was retired")
- }
- for _, fragment := range []string{
- `manifest = s.executor.ListToolGovernance()`,
- `agentcapabilities.ProviderToolNames(offeredTools)`,
- `agentcapabilities.ProviderToolGovernanceDescriptors(offeredTools)`,
- `agentcapabilities.BuildAssistantToolGovernancePromptSection(manifest, orderedOfferedNames)`,
- `tools.CanonicalToolGovernanceForManifestSurface(`,
- `agentcapabilities.SurfaceIDPulseAssistant`,
- `fallbackAssistantToolGovernanceOfferedNames(manifest)`,
- `agentcapabilities.ManifestSurfaceAffordances(`,
- `providerTools := executor.AssistantProviderTools(agentcapabilities.AssistantProviderToolOptions{`,
- `agentcapabilities.BuildPulseAssistantOperatingInstructions()`,
- `func (s *Service) executeAssistantRegistryToolDirect(ctx context.Context, toolName string, args map[string]interface{}, opts agentcapabilities.DirectToolExecutionOptions) (agentcapabilities.DirectToolExecutionOutcome, error)`,
- `outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, agentcapabilities.PulseRunCommandToolName, args, agentcapabilities.DirectToolExecutionOptions{`,
- `outcome, executionErr := s.executeAssistantRegistryToolDirect(ctx, toolName, args, agentcapabilities.DirectToolExecutionOptions{`,
- `result, toolErr := executor.ExecuteTool(ctx, toolName, args)`,
- `agentcapabilities.InterpretDirectToolExecution(result`,
- `FailurePrefix: "command execution failed"`,
- `ApprovalRequiredMessage: "command requires approval (unexpected in autonomous mode)"`,
- `PolicyBlockedMessage: "command blocked by security policy"`,
- `FailurePrefix: "tool execution failed"`,
- `ApprovalRequiredMessage: "tool requires approval (unexpected in fix execution)"`,
- `PolicyBlockedMessage: "tool blocked by security policy"`,
- } {
- if !strings.Contains(chatServiceSrc, fragment) {
- t.Errorf("Assistant chat service must use shared direct result execution mapping; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `agentcapabilities.DirectMCPToolExecutionOptions`,
- `agentcapabilities.DirectMCPToolExecutionOutcome`,
- `agentcapabilities.InterpretDirectMCPToolExecution`,
- } {
- if strings.Contains(chatServiceSrc, fragment) {
- t.Errorf("Assistant chat service must use neutral direct tool execution helpers, found %s", fragment)
- }
- }
- if strings.Contains(chatServiceSrc, `ProjectAssistantProviderTools(`) {
- t.Error("Assistant chat service must request provider-tool projection from the shared executor entrypoint")
- }
- if strings.Contains(chatServiceSrc, `tools.CanonicalToolGovernanceForSurface(`) ||
- strings.Contains(chatServiceSrc, `tools.ToolGovernanceSurfacePulseAssistant`) {
- t.Error("Assistant chat service fallback governance must enter through manifest surface affordances")
- }
- for _, fragment := range []string{
- `b.WriteString("## AVAILABLE TOOL GOVERNANCE`,
- `agentcapabilities.ToolGovernancePromptOptions{`,
- `agentcapabilities.PulseQuestionToolGovernancePromptLine()`,
- `assistantGovernanceOfferedToolNames`,
- `userQuestionTool()`,
- `mode := tool.ActionMode`,
- `approvalSummary := strings.TrimSpace(tool.ApprovalSummary)`,
- `fmt.Sprintf("- %s: mode=%s; approval=%s`,
- `for _, content := range result.Content`,
- `resultText += content.Text`,
- `agentcapabilities.HasApprovalRequiredToolMarker(resultText)`,
- `agentcapabilities.HasPolicyBlockedToolMarker(resultText)`,
- `interpreted := agentcapabilities.InterpretToolResult(result)`,
- `if interpreted.IsError`,
- `if interpreted.ApprovalRequired`,
- `if interpreted.PolicyBlocked`,
- `func assistantQuestionToolGovernancePromptLine() string`,
- } {
- if strings.Contains(chatServiceSrc, fragment) {
- t.Errorf("Assistant chat service must not flatten or interpret direct MCP result outcomes locally; found %s", fragment)
- }
- }
-
- chatServiceAdapterSource, err := os.ReadFile(filepath.Join("..", "api", "chat_service_adapter.go"))
- if err != nil {
- t.Fatalf("read internal/api/chat_service_adapter.go: %v", err)
- }
- chatServiceAdapterSrc := string(chatServiceAdapterSource)
- for _, fragment := range []string{
- `func adaptChatMessage(m chat.Message) ai.ChatMessage`,
- `msg.ToolCalls = append(msg.ToolCalls, tc.NormalizeCollections())`,
- `toolResult := *m.ToolResult`,
- } {
- if !strings.Contains(chatServiceAdapterSrc, fragment) {
- t.Errorf("chat service adapter must retain result-bearing transcript calls; missing %s", fragment)
- }
- }
-
- orchestratorDepsSource, err := os.ReadFile(filepath.Join("..", "..", "pkg", "aicontracts", "orchestrator_deps.go"))
- if err != nil {
- t.Fatalf("read pkg/aicontracts/orchestrator_deps.go: %v", err)
- }
- orchestratorDepsSrc := string(orchestratorDepsSource)
- for _, fragment := range []string{
- `func OrchestratorToolCallInfoFromProvider(tc agentcapabilities.ProviderToolCall) OrchestratorToolCallInfo`,
- `func (t OrchestratorToolCallInfo) ProviderToolCall() agentcapabilities.ProviderToolCall`,
- `func OrchestratorToolResultInfoFromProvider(result agentcapabilities.ProviderToolResult) OrchestratorToolResultInfo`,
- `func (r OrchestratorToolResultInfo) ProviderToolResult() agentcapabilities.ProviderToolResult`,
- `return agentcapabilities.NewProviderToolResult(r.ToolUseID, r.Content, r.IsError)`,
- } {
- if !strings.Contains(orchestratorDepsSrc, fragment) {
- t.Errorf("orchestrator dependency contract must bridge messages through shared provider tool shapes; missing %s", fragment)
- }
- }
-
- aiHandlersSource, err := os.ReadFile(filepath.Join("..", "api", "ai_handlers.go"))
- if err != nil {
- t.Fatalf("read internal/api/ai_handlers.go: %v", err)
- }
- aiHandlersSrc := string(aiHandlersSource)
- for _, fragment := range []string{
- `aicontracts.OrchestratorToolCallInfoFromProvider(tc.ProviderToolCall())`,
- `toolResult := aicontracts.OrchestratorToolResultInfoFromProvider(*msg.ToolResult)`,
- } {
- if !strings.Contains(aiHandlersSrc, fragment) {
- t.Errorf("orchestrator chat adapter must bridge messages through shared provider tool shapes; missing %s", fragment)
- }
- }
-
- patrolRuntime, err := os.ReadFile(filepath.Join("..", "ai", "patrol_ai.go"))
- if err != nil {
- t.Fatalf("read internal/ai/patrol_ai.go: %v", err)
- }
- patrolSrc := string(patrolRuntime)
- if strings.Contains(patrolSrc, "func formatToolResult(") {
- t.Error("Patrol runtime must not keep a local result-text wrapper; call agentcapabilities.ToolResultText at the execution site")
- }
-
- patrolFindings, err := os.ReadFile(filepath.Join("..", "ai", "patrol_findings.go"))
- if err != nil {
- t.Fatalf("read internal/ai/patrol_findings.go: %v", err)
- }
- patrolFindingsSrc := string(patrolFindings)
- for _, fragment := range []string{
- `agentcapabilities.InterpretToolResult(result)`,
- `if interpreted.IsError`,
- `if interpreted.ApprovalRequired`,
- `if interpreted.PolicyBlocked`,
- } {
- if !strings.Contains(patrolFindingsSrc, fragment) {
- t.Errorf("Patrol tool-call records must use shared tool result interpretation; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `output = agentcapabilities.MCPToolResultText(result)`,
- `agentcapabilities.InterpretMCPToolResult(result)`,
- `agentcapabilities.MCPToolResultInterpretation`,
- `success = !result.IsError`,
- `if result.IsError`,
- `formatToolResult(result)`,
- } {
- if strings.Contains(patrolFindingsSrc, fragment) {
- t.Errorf("Patrol tool-call records must not duplicate shared result interpretation locally; found %s", fragment)
- }
- }
-
- assistantRegistry, err := os.ReadFile(filepath.Join("..", "ai", "tools", "registry.go"))
- if err != nil {
- t.Fatalf("read internal/ai/tools/registry.go: %v", err)
- }
- registrySrc := string(assistantRegistry)
- for _, fragment := range []string{
- `type ControlLevel = agentcapabilities.ControlLevel`,
- `ControlLevelReadOnly ControlLevel = agentcapabilities.ControlLevelReadOnly`,
- `ControlLevelControlled ControlLevel = agentcapabilities.ControlLevelControlled`,
- `ControlLevelAutonomous ControlLevel = agentcapabilities.ControlLevelAutonomous`,
- `!agentcapabilities.ControlLevelAllowsControlTools(policy.ControlLevel)`,
- `!agentcapabilities.ControlLevelAllowsControlTools(e.controlLevel)`,
- `agentcapabilities.NewToolGovernanceDescriptor(`,
- `tool.Definition = tool.Definition.NormalizeCollections()`,
- `result = append(result, projected.Definition.NormalizeCollections())`,
- `params, invalidResult, ok := agentcapabilities.PrepareToolRegistryExecution(name, args)`,
- `agentcapabilities.NewUnknownToolResult(name)`,
- `agentcapabilities.NewControlToolsDisabledToolResult()`,
- `return result.NormalizeCollections(), err`,
- // Registration authority is split: builtin registration is
- // construction-only, extensions can never claim or replace a
- // canonical name, and entries are append-only.
- `func (r *ToolRegistry) registerBuiltin(tool RegisteredTool)`,
- `func (r *ToolRegistry) RegisterExtension(tool RegisteredTool)`,
- `registry entries are append-only`,
- // Invocation-level enforcement runs before the handler and
- // consumes the same descriptor the projection filters with.
- `class = tool.Invocation.Classify(args)`,
- `if !policy.Allows(name, class) {`,
- `!agentcapabilities.ControlLevelAllowsControlTools(policy.ControlLevel)`,
- `agentcapabilities.NewInvocationBlockedToolResult(name, class)`,
- `descriptor.Validate(name, discriminatorEnum(tool.Definition, descriptor.Discriminator))`,
- `func projectToolForPolicy(tool RegisteredTool, policy InvocationPolicy) (RegisteredTool, bool)`,
- } {
- if !strings.Contains(registrySrc, fragment) {
- t.Errorf("Assistant tool registry must use shared agentcapabilities contracts; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `assistantControlToolsDisabledMessage`,
- `func normalizeToolGovernance(`,
- `DefaultApprovalPolicyDescription(governance.ApprovalPolicy)`,
- `governance.ActionMode = ToolActionWrite`,
- `governance.ApprovalPolicy = ToolApprovalActionPlan`,
- `invalid tools/call params:`,
- `unknown tool: %s`,
- `agentcapabilities.ControlToolsDisabledMessage`,
- } {
- if strings.Contains(registrySrc, fragment) {
- t.Errorf("Assistant tool registry must not preserve local governance defaults; found %s", fragment)
- }
- }
-
- assistantRegistryToolFiles := []string{
- filepath.Join("..", "ai", "tools", "tools_alerts.go"),
- filepath.Join("..", "ai", "tools", "tools_control.go"),
- filepath.Join("..", "ai", "tools", "tools_docker.go"),
- filepath.Join("..", "ai", "tools", "tools_file.go"),
- filepath.Join("..", "ai", "tools", "tools_kubernetes.go"),
- filepath.Join("..", "ai", "tools", "tools_knowledge.go"),
- filepath.Join("..", "ai", "tools", "tools_metrics.go"),
- filepath.Join("..", "ai", "tools", "tools_patrol.go"),
- filepath.Join("..", "ai", "tools", "tools_pmg.go"),
- filepath.Join("..", "ai", "tools", "tools_query.go"),
- filepath.Join("..", "ai", "tools", "tools_read.go"),
- filepath.Join("..", "ai", "tools", "tools_storage.go"),
- filepath.Join("..", "ai", "tools", "tools_summarize.go"),
- }
- assistantRegistryToolSrc := strings.Builder{}
- for _, path := range assistantRegistryToolFiles {
- source, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("read %s: %v", path, err)
- }
- assistantRegistryToolSrc.Write(source)
- assistantRegistryToolSrc.WriteString("\n")
- }
- registryToolDeclarations := assistantRegistryToolSrc.String()
- for _, fragment := range []string{
- `Name: agentcapabilities.PulseAlertsToolName`,
- `Name: agentcapabilities.PulseControlToolName`,
- `Name: agentcapabilities.PulseDockerToolName`,
- `Name: agentcapabilities.PulseKubernetesToolName`,
- `Name: agentcapabilities.PulseKnowledgeToolName`,
- `Name: agentcapabilities.PulseMetricsToolName`,
- `Name: agentcapabilities.PatrolReportFindingToolName`,
- `Name: agentcapabilities.PatrolResolveFindingToolName`,
- `Name: agentcapabilities.PatrolGetFindingsToolName`,
- `Name: agentcapabilities.PulsePMGToolName`,
- `Name: agentcapabilities.PulseQueryToolName`,
- `Name: agentcapabilities.PulseReadToolName`,
- `Name: agentcapabilities.PulseStorageToolName`,
- `Name: agentcapabilities.PulseSummarizeToolName`,
- } {
- if !strings.Contains(registryToolDeclarations, fragment) {
- t.Errorf("Assistant registry tool declarations must use shared tool identities; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `Name: "pulse_`,
- `Name: "pulse_`,
- `Name: "patrol_`,
- `Name: "patrol_`,
- } {
- if strings.Contains(registryToolDeclarations, fragment) {
- t.Errorf("Assistant registry tool declarations must not own local Pulse tool-name strings; found %s", fragment)
- }
- }
-
- assistantPatrolTools, err := os.ReadFile(filepath.Join("..", "ai", "tools", "tools_patrol.go"))
- if err != nil {
- t.Fatalf("read internal/ai/tools/tools_patrol.go: %v", err)
- }
- assistantPatrolToolsSrc := string(assistantPatrolTools)
- for _, fragment := range []string{
- `agentcapabilities.FindingIDArgumentName`,
- `agentcapabilities.ReasonArgumentName`,
- `return NewJSONResult(result), nil`,
- } {
- if !strings.Contains(assistantPatrolToolsSrc, fragment) {
- t.Errorf("Assistant Patrol tools must use shared finding vocabulary and JSON result envelope; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `json.Marshal(result)`,
- `NewTextResult(string(b))`,
- } {
- if strings.Contains(assistantPatrolToolsSrc, fragment) {
- t.Errorf("Assistant Patrol tools must not manually marshal JSON text results; found %s", fragment)
- }
- }
-
- assistantProjection, err := os.ReadFile(filepath.Join("..", "ai", "tools", "provider_projection.go"))
- if err != nil {
- t.Fatalf("read internal/ai/tools/provider_projection.go: %v", err)
- }
- assistantProjectionSrc := string(assistantProjection)
- for _, fragment := range []string{
- `func (e *PulseToolExecutor) AssistantProviderTools(opts agentcapabilities.AssistantProviderToolOptions) []agentcapabilities.ProviderTool`,
- `return agentcapabilities.ProjectPulseAssistantProviderTools(agentcapabilities.CanonicalManifest(), e.ListTools(), e.ListToolGovernance(), opts)`,
- `return agentcapabilities.ProjectPulseAssistantProviderTools(agentcapabilities.CanonicalManifest(), nil, nil, opts)`,
- } {
- if !strings.Contains(assistantProjectionSrc, fragment) {
- t.Errorf("Assistant provider-tool projection must stay centralized on the shared executor; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `return agentcapabilities.ProjectAssistantProviderTools(e.ListTools(), e.ListToolGovernance(), opts)`,
- `return agentcapabilities.ProjectAssistantProviderTools(nil, nil, opts)`,
- } {
- if strings.Contains(assistantProjectionSrc, fragment) {
- t.Errorf("Assistant provider-tool projection must enter through manifest surface affordances; found %s", fragment)
- }
- }
-
- assistantToolNames, err := os.ReadFile(filepath.Join("..", "ai", "tools", "names.go"))
- if err != nil {
- t.Fatalf("read internal/ai/tools/names.go: %v", err)
- }
- assistantToolNamesSrc := string(assistantToolNames)
- for _, fragment := range []string{
- `agentcapabilities.ProviderToolNameCatalog`,
- `func AssistantProviderToolNameCatalog() agentcapabilities.ProviderToolNameCatalog`,
- `return AssistantProviderToolNameCatalog().Has(name)`,
- `return AssistantProviderToolNameCatalog().HasPrefix(prefix)`,
- `return knownToolNameCatalog`,
- `agentcapabilities.NewAssistantProviderToolNameCatalog(e.registry.allNames())`,
- } {
- if !strings.Contains(assistantToolNamesSrc, fragment) {
- t.Errorf("Assistant tool-name allowlist must adapt the shared provider-tool catalog; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `agentcapabilities.AssistantNativeProviderToolNames()`,
- `knownToolNamesList`,
- `knownToolNamesSet`,
- `strings.HasPrefix(name, prefix)`,
- } {
- if strings.Contains(assistantToolNamesSrc, fragment) {
- t.Errorf("Assistant tool-name allowlist must not keep local provider-tool catalog logic; found %s", fragment)
- }
- }
- if strings.Contains(assistantToolNamesSrc, `"pulse_question"`) {
- t.Error("Assistant tool-name allowlist must not hard-code native Assistant provider tool names")
- }
-
- assistantSanitize, err := os.ReadFile(filepath.Join("..", "ai", "chat", "agentic_sanitize.go"))
- if err != nil {
- t.Fatalf("read internal/ai/chat/agentic_sanitize.go: %v", err)
- }
- assistantSanitizeSrc := string(assistantSanitize)
- for _, fragment := range []string{
- `agentcapabilities.ProviderToolCallArtifactIndex(content, tools.AssistantProviderToolNameCatalog())`,
- `agentcapabilities.SplitTrailingProviderToolNamePrefix(content, tools.AssistantProviderToolNameCatalog())`,
- } {
- if !strings.Contains(assistantSanitizeSrc, fragment) {
- t.Errorf("Assistant chat sanitizer must use shared provider tool-call artifact detection; missing %s", fragment)
- }
- }
- for _, fragment := range []string{
- `dsmlMarkers`,
- `xmlToolCallRe`,
- `pipeMarkerRe`,
- `minimaxMarkerRe`,
- `jsonToolCallRe`,
- `plainFunctionToolCallRe`,
- `findJSONToolCallLeak`,
- `findPlainFunctionToolCallLeak`,
- } {
- if strings.Contains(assistantSanitizeSrc, fragment) {
- t.Errorf("Assistant chat sanitizer must not preserve local provider artifact detection; found %s", fragment)
- }
- }
-}
-
-// TestContract_AgentProbeUsesSharedAgentCapabilityProjection pins the reference
-// client boundary: the probe may demonstrate transport mechanics, but manifest
-// lookup and route projection must use the same shared helpers as MCP.
-func TestContract_AgentProbeUsesSharedAgentCapabilityProjection(t *testing.T) {
- source, err := os.ReadFile(filepath.Join("..", "..", "cmd", "agent-probe", "main.go"))
- if err != nil {
- t.Fatalf("read cmd/agent-probe/main.go: %v", err)
- }
- src := string(source)
- required := []string{
- `internal/agentcapabilities`,
- `agentcapabilities.FleetContextCapabilityName`,
- `agentcapabilities.ResourceContextCapabilityName`,
- `agentcapabilities.FindCapability(manifest.Capabilities, agentcapabilities.EventSubscriptionCapabilityName)`,
- `agentcapabilities.FetchManifest(context.Background(), client, *baseURL)`,
- `agentcapabilities.CallRequestResponseCapabilityHTTPBodyByName(`,
- `agentcapabilities.StreamAgentActionableSSERecords(ctx, nil, baseURL, path, token, func(record agentcapabilities.SSERecord) bool`,
- }
- for _, fragment := range required {
- if !strings.Contains(src, fragment) {
- t.Errorf("agent-probe must use the shared agent capability projection helpers; missing %s", fragment)
- }
- }
- forbidden := []string{
- `agentcapabilities.FindCapability(manifest.Capabilities, "get_fleet_context")`,
- `agentcapabilities.FindCapability(manifest.Capabilities, "get_resource_context")`,
- `agentcapabilities.CallCapabilityHTTPByName(`,
- `agentcapabilities.CallCapabilityHTTP(ctx, client, baseURL, token, cap, args)`,
- `resp.FailureError()`,
- `strings.Replace(contextCap.Path`,
- `byName := map[string]agentCapability`,
- `type errorEnvelope struct`,
- `baseURL + "/api/agent/capabilities"`,
- `req.Header.Set("X-API-Token", token)`,
- `agentcapabilities.DecodeErrorEnvelope(body)`,
- `req.Header.Set("Accept", "text/event-stream")`,
- `http.DefaultClient.Do(req)`,
- `scanner := bufio.NewScanner(resp.Body)`,
- `strings.HasPrefix(line, "event: ")`,
- `strings.HasPrefix(line, "data: ")`,
- `agentcapabilities.StreamAgentSSERecords(ctx, nil, baseURL, path, token`,
- `agentcapabilities.IsTransportEventKind(record.Event)`,
- }
- for _, fragment := range forbidden {
- if strings.Contains(src, fragment) {
- t.Errorf("agent-probe must not preserve local manifest projection logic; found %s", fragment)
- }
- }
-}
-
// TestContract_AgentSurfaceErrorEnvelopeUsesSharedAgentCapabilitiesType pins
// the stable agent error envelope as part of the shared agent capabilities
// contract instead of an API-local map or probe-local struct.
diff --git a/internal/api/license_runtime_test.go b/internal/api/license_runtime_test.go
new file mode 100644
index 0000000000..e93ef29b52
--- /dev/null
+++ b/internal/api/license_runtime_test.go
@@ -0,0 +1,146 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/license"
+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
+ licensetestsupport "github.com/rcourtman/pulse-go-rewrite/pkg/licensing/testsupport"
+)
+
+// activateAndCaptureRuntime activates a key through the handler against a fake
+// license server and returns the runtime identity the server received.
+func activateAndCaptureRuntime(t *testing.T, handler *LicenseHandlers, server *captureActivationServer) *pkglicensing.RuntimeIdentity {
+ t.Helper()
+ t.Cleanup(handler.StopAllBackgroundLoops)
+
+ body, _ := json.Marshal(map[string]string{"license_key": "ppk_live_runtime_identity"})
+ req := httptest.NewRequest(http.MethodPost, "/api/license/activate", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleActivateLicense(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, rec.Code, rec.Body.String())
+ }
+ return server.capturedRuntime(t)
+}
+
+type captureActivationServer struct {
+ mu sync.Mutex
+ request *pkglicensing.ActivateInstallationRequest
+}
+
+func (s *captureActivationServer) capturedRuntime(t *testing.T) *pkglicensing.RuntimeIdentity {
+ t.Helper()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.request == nil {
+ t.Fatal("license server never received an activation request")
+ }
+ return s.request.Runtime
+}
+
+func newCaptureActivationServer(t *testing.T) *captureActivationServer {
+ t.Helper()
+ t.Setenv("PULSE_LICENSE_DEV_MODE", "false")
+
+ grantJWT, grantPublicKey, err := licensetestsupport.GenerateGrantJWTForTesting(pkglicensing.GrantClaims{
+ LicenseID: "lic_v6_runtime",
+ LicenseVersion: 1,
+ Tier: "pro",
+ State: "active",
+ Features: []string{"relay"},
+ IssuedAt: time.Now().Unix(),
+ ExpiresAt: time.Now().Add(72 * time.Hour).Unix(),
+ Email: "[email protected]",
+ })
+ if err != nil {
+ t.Fatalf("generate grant jwt: %v", err)
+ }
+ license.SetPublicKey(grantPublicKey)
+ t.Cleanup(func() { license.SetPublicKey(nil) })
+
+ captured := &captureActivationServer{}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if handleTestInstallationStatus(w, r, 1) {
+ return
+ }
+ if r.URL.Path != "/v1/activate" {
+ t.Errorf("path = %q, want /v1/activate", r.URL.Path)
+ http.NotFound(w, r)
+ return
+ }
+ var activation pkglicensing.ActivateInstallationRequest
+ if err := json.NewDecoder(r.Body).Decode(&activation); err != nil {
+ t.Errorf("decode activation request: %v", err)
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ captured.mu.Lock()
+ captured.request = &activation
+ captured.mu.Unlock()
+
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "license": map[string]any{
+ "license_id": "lic_v6_runtime",
+ "state": "active",
+ "tier": "pro",
+ "features": []string{"relay"},
+ "max_monitored_systems": 10,
+ },
+ "installation": map[string]any{
+ "installation_id": "inst_v6_runtime",
+ "installation_token": "pit_live_runtime",
+ "status": "active",
+ },
+ "grant": map[string]any{
+ "jwt": grantJWT,
+ "jti": "grant_v6_runtime",
+ "expires_at": time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339),
+ },
+ })
+ }))
+ t.Cleanup(server.Close)
+ t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
+ return captured
+}
+
+// A Pro build must tell the license server it is a Pro runtime when it
+// activates a key, whether the tenant's license service is created by the
+// activation itself or was already cached by an earlier request.
+func TestHandleActivateLicense_ReportsRuntimeIdentityToLicenseServer(t *testing.T) {
+ t.Run("new tenant service", func(t *testing.T) {
+ server := newCaptureActivationServer(t)
+ handler := createTestHandler(t)
+ handler.SetRuntimeIdentity(pkglicensing.ProRuntimeIdentity())
+
+ runtime := activateAndCaptureRuntime(t, handler, server)
+ if runtime == nil || runtime.Build != pkglicensing.RuntimeBuildPro {
+ t.Fatalf("activation runtime = %+v, want %q build", runtime, pkglicensing.RuntimeBuildPro)
+ }
+ })
+
+ t.Run("cached tenant service", func(t *testing.T) {
+ server := newCaptureActivationServer(t)
+ handler := createTestHandler(t)
+
+ // An earlier request caches the tenant service while the handler still
+ // reports the community runtime.
+ probe := httptest.NewRequest(http.MethodGet, "/api/license/status", nil)
+ if _, _, err := handler.getTenantComponents(probe.Context()); err != nil {
+ t.Fatalf("getTenantComponents: %v", err)
+ }
+ handler.SetRuntimeIdentity(pkglicensing.ProRuntimeIdentity())
+
+ runtime := activateAndCaptureRuntime(t, handler, server)
+ if runtime == nil || runtime.Build != pkglicensing.RuntimeBuildPro {
+ t.Fatalf("activation runtime = %+v, want %q build", runtime, pkglicensing.RuntimeBuildPro)
+ }
+ })
+}
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index ee784c4222..6ef111f047 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -180,30 +180,6 @@ func TestVMwareManualConnectionTestPreservesDegradedDiagnostics(t *testing.T) {
}
}
-func TestPVETagStyleRefreshStaysPerInstance(t *testing.T) {
- data, err := os.ReadFile("monitor_pve.go")
- if err != nil {
- t.Fatalf("failed to read monitor_pve.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "func (m *Monitor) refreshPVETagColors(ctx context.Context, instanceName string, client PVEClientInterface)",
- "tagStyle := proxmox.ParseTagStyle(opts.TagStyle)",
- "m.state.MergePVETagStyle(instanceName, models.PVETagStyle{",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor_pve.go must contain %q", snippet)
- }
- }
- if strings.Contains(source, "ParseTagColorMap(opts.TagStyle)") {
- t.Fatal("PVE tag refresh must preserve case-sensitive style metadata, not only the legacy color map")
- }
- if strings.Contains(source, "m.state.MergeTagColors(") {
- t.Fatal("PVE tag refresh must merge style by instance so cleared color maps do not leave stale aggregate colors")
- }
-}
-
func TestProxmoxActionObserverUsesDirectControlPlaneClient(t *testing.T) {
data, err := os.ReadFile("proxmox_action_observer.go")
if err != nil {
@@ -447,60 +423,6 @@ func TestGuestSnapshotPollingStaysBoundedConcurrent(t *testing.T) {
testSnapshotPollWorkersBoundWaitingAndActiveWork(t)
}
-func TestGetStateRefreshesLiveAlertSnapshots(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "currentState := m.state",
- "state := currentState.GetSnapshot()",
- "state.ActiveAlerts = m.activeAlertsSnapshot()",
- "state.RecentlyResolved = m.recentlyResolvedAlertsSnapshot()",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
-func TestAlertStateSyncDoesNotLogNormalResolvedStateAtInfo(t *testing.T) {
- data, err := os.ReadFile("monitor_alert_sync.go")
- if err != nil {
- t.Fatalf("failed to read monitor_alert_sync.go: %v", err)
- }
- source := string(data)
-
- if !strings.Contains(source, `log.Debug().Int("count", len(recentlyResolved)).Msg("syncing recently resolved alerts")`) {
- t.Fatal("recently resolved alert sync must stay at debug level to avoid info-log churn")
- }
- if strings.Contains(source, `log.Info().Int("count", len(recentlyResolved)).Msg("syncing recently resolved alerts")`) {
- t.Fatal("recently resolved alert sync must not log normal polling state at info level")
- }
-}
-
-func TestUnifiedResourceAlertSyncEvaluatesMetricsBeforeIncidents(t *testing.T) {
- data, err := os.ReadFile("monitor_alert_sync.go")
- if err != nil {
- t.Fatalf("failed to read monitor_alert_sync.go: %v", err)
- }
- source := string(data)
-
- metricIndex := strings.Index(source, "CheckUnifiedResourceWithCapacityTrend(input, capacityTrends[input.ID])")
- incidentIndex := strings.Index(source, "SyncUnifiedResourceIncidents(resources)")
- if metricIndex < 0 {
- t.Fatalf("monitor alert sync must run unified resource metric evaluation")
- }
- if incidentIndex < 0 {
- t.Fatalf("monitor alert sync must preserve unified resource incident sync")
- }
- if metricIndex > incidentIndex {
- t.Fatalf("unified resource metric evaluation must run before incident sync")
- }
-}
-
// Monitor state and live snapshots switch to the fixture graph in mock mode,
// so a store refresh must take its mock-mode scope before it reads them.
// Go evaluates call arguments left to right: a scope begun in the argument
@@ -542,51 +464,6 @@ func TestStoreRefreshTakesItsMockModeScopeBeforeReadingState(t *testing.T) {
}
}
-func TestStateBroadcastTreatsTypedNilHubAsAbsent(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "func isNilStateBroadcaster(hub stateBroadcaster) bool {",
- "if isNilStateBroadcaster(hub) {",
- "value := reflect.ValueOf(hub)",
- "case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:",
- "return value.IsNil()",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
-func TestBroadcastResourceProjectionPreservesCanonicalHealthContext(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "if resource.DiscoveryTarget == nil {",
- "if resource.MetricsTarget == nil {",
- "unifiedresources.RefreshCanonicalMetadata(&resource)",
- "IncidentSummary: resource.IncidentSummary",
- "Canonical: monitorRawJSON(resource.Canonical)",
- "DiscoveryTarget: monitorRawJSON(resource.DiscoveryTarget)",
- "MetricsTarget: monitorRawJSON(resource.MetricsTarget)",
- "Storage: monitorRawJSON(resource.Storage)",
- "Agent: monitorRawJSON(resource.Agent)",
- "Incidents: monitorRawJSON(resource.Incidents)",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
func TestHostUnraidReadStateProjectionPreservesNativeDiskFields(t *testing.T) {
projected := hostUnraidFromReadStateView(&unifiedresources.HostUnraidMeta{
ArrayStarted: true,
@@ -724,202 +601,6 @@ func TestMetricsStoreRuntimeOverridesStayOnMonitorBoundary(t *testing.T) {
}
}
-func TestEscalationDeliveryDefersToCanonicalAlertSuppression(t *testing.T) {
- requiredSnippets := map[string][]string{
- "monitor.go": {
- "m.alertManager.SetEscalateCallback(func(alert *alerts.Alert, level int) {",
- "m.handleAlertEscalated(wsHub, alert, level)",
- },
- "monitor_alerts.go": {
- "func (m *Monitor) handleAlertEscalated(hub *websocket.Hub, alert *alerts.Alert, level int) {",
- "if m.alertManager.ShouldSuppressNotification(alert) {",
- "m.notificationMgr.SendEscalatedAlert(alert, escalationLevel.Notify)",
- "m.broadcastEscalatedAlert(hub, alert)",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestAvailabilityProviderStaysOnCanonicalMonitoringPath(t *testing.T) {
- requiredSnippets := map[string][]string{
- "scheduler.go": {
- `InstanceTypeAvailability InstanceType = "availability"`,
- },
- "monitor.go": {
- "availabilityStatuses",
- "map[string]AvailabilityProbeStatus",
- "availabilityByLocation",
- "map[string]map[string]AvailabilityProbeStatus",
- "availabilityStatuses:",
- "make(map[string]AvailabilityProbeStatus)",
- "availabilityByLocation:",
- "make(map[string]map[string]AvailabilityProbeStatus)",
- },
- "poll_providers.go": {
- "_ = m.RegisterPollProvider(newAvailabilityPollProvider())",
- "newAvailabilityPollProvider(),",
- "case InstanceTypeAvailability:",
- "return newAvailabilityPollProvider()",
- },
- "availability_poller.go": {
- "func newAvailabilityPollProvider() PollProvider {",
- "func (availabilityPollProvider) SupplementalSource() unifiedresources.DataSource {",
- "return unifiedresources.SourceAvailability",
- "func (availabilityPollProvider) SupplementalRecords(m *Monitor, orgID string) []unifiedresources.IngestRecord {",
- "Type: unifiedresources.ResourceTypeNetworkEndpoint,",
- "Sources: []unifiedresources.DataSource{unifiedresources.SourceAvailability},",
- "Availability: data,",
- "m.recordTaskResult(InstanceTypeAvailability, target.ID, nil)",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestMonitoredSystemUsageReadinessGuardrailsRemainCanonical(t *testing.T) {
- requiredSnippets := map[string][]string{
- "monitor.go": {
- "type MonitorSupplementalInventoryReadinessProvider interface {",
- "SupplementalInventoryReadyAt(m *Monitor, orgID string) (time.Time, bool)",
- "hostContinuityStore",
- "*config.HostContinuityStore",
- "hostContinuityStore := config.NewHostContinuityStore(cfg.DataPath, nil)",
- "hostContinuityStore:",
- "hostContinuityStore,",
- "func (m *Monitor) HostsSnapshot() []models.Host {",
- "readState = m.readStateWithStandaloneHostContinuity(readState)",
- "func (m *Monitor) unifiedStateViewWithStandaloneHostContinuity(view monitorUnifiedStateView) monitorUnifiedStateView {",
- "view.readState = readState",
- "view.resources = resources",
- "func latestUnifiedResourceLastSeen(resources []unifiedresources.Resource) time.Time {",
- "return m.unifiedStateViewWithStandaloneHostContinuity(monitorUnifiedStateView{",
- },
- "monitored_system_usage.go": {
- "MonitoredSystemUsageUnavailableMonitorState",
- "MonitoredSystemUsageUnavailableSupplementalInventoryUnsettled",
- "MonitoredSystemUsageUnavailableSupplementalInventoryRebuildPending",
- "func (m *Monitor) MonitoredSystemUsage() MonitoredSystemUsageSnapshot {",
- "readyAt, settled := m.supplementalInventoryReadyAt(orgID)",
- "if !settled {",
- "UnavailableReason: MonitoredSystemUsageUnavailableSupplementalInventoryUnsettled,",
- "if freshness.IsZero() || freshness.Before(readyAt) {",
- "UnavailableReason: MonitoredSystemUsageUnavailableSupplementalInventoryRebuildPending,",
- "readState = m.readStateWithStandaloneHostContinuity(readState)",
- "Count: unifiedresources.MonitoredSystemCount(readState),",
- "Available: true,",
- "func (m *Monitor) readStateWithStandaloneHostContinuity(",
- "return unifiedresources.ReadStateWithHostContinuity(readState, records)",
- },
- "truenas_poller.go": {
- "func (p *TrueNASPoller) SupplementalInventoryReadyAt(_ *Monitor, orgID string) (time.Time, bool) {",
- "configs := p.activeConnectionConfigsForOrg(orgID)",
- "if status == nil || status.lastAttemptAt.IsZero() {",
- },
- "vmware_poller.go": {
- "func (p *VMwarePoller) SupplementalInventoryReadyAt(_ *Monitor, orgID string) (time.Time, bool) {",
- "configs := p.activeConnectionConfigsForOrg(orgID)",
- "if status == nil || status.lastAttemptAt.IsZero() {",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestInstallTelemetrySnapshotCountsStayOnMonitoringBoundary(t *testing.T) {
- data, err := os.ReadFile("reload.go")
- if err != nil {
- t.Fatalf("failed to read reload.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "AgentHosts",
- "DockerContainers",
- "KubernetesPods",
- "TrueNASSystems",
- "VMwareDatastores",
- "AvailabilityTargets",
- "resources, _ := monitor.UnifiedResourceSnapshot()",
- "accumulateInstallSnapshotUnifiedResourceCounts(counts, resources)",
- "case unifiedresources.ResourceTypeNetworkShare:",
- "resource.Availability != nil && resource.Availability.Enabled",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("reload.go must contain %q", snippet)
- }
- }
-}
-
-func TestMonitoredSystemUsageStaysInventoryOnly(t *testing.T) {
- data, err := os.ReadFile("monitored_system_usage.go")
- if err != nil {
- t.Fatalf("failed to read monitored_system_usage.go: %v", err)
- }
- source := string(data)
-
- for _, forbidden := range []string{
- "max_monitored_systems",
- "license_limit",
- "would_exceed_limit",
- "monitored_system_capacity",
- "admission",
- } {
- if strings.Contains(source, forbidden) {
- t.Fatalf("monitored_system_usage.go must not contain retired cap/admission token %q", forbidden)
- }
- }
-}
-
-func TestDockerHostIdentityUsesCanonicalHostnameEquivalence(t *testing.T) {
- data, err := os.ReadFile("docker_host_identity.go")
- if err != nil {
- t.Fatalf("failed to read docker_host_identity.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "unifiedresources.HostnamesEquivalent(host.Hostname(), hostname)",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("docker_host_identity.go must contain %q", snippet)
- }
- }
-}
-
func TestDockerTokenBindingUsesCanonicalHostIdentity(t *testing.T) {
requiredSnippets := map[string][]string{
"docker_host_identity.go": {
@@ -952,106 +633,6 @@ func TestDockerTokenBindingUsesCanonicalHostIdentity(t *testing.T) {
}
}
-func TestGuestMemoryFallbackUsesCanonicalLowTrustSelector(t *testing.T) {
- data, err := os.ReadFile("guest_memory_sources.go")
- if err != nil {
- t.Fatalf("failed to read guest_memory_sources.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "func effectiveGuestFreeMemTotal(memTotal uint64, status *proxmox.VMStatus) uint64 {",
- "func guestStatusFreeMem(status *proxmox.VMStatus) uint64 {",
- "if status.BalloonInfo != nil {",
- "if status.Balloon > 0 && status.Balloon <= memTotal && freeMem <= status.Balloon {",
- "func selectGuestLowTrustUsedMemory(memTotal uint64, status *proxmox.VMStatus) (uint64, string) {",
- "if statusMemPlusFree > freeMemTotal+guestStatusMemoryMismatchTolerance {",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("guest_memory_sources.go must contain %q", snippet)
- }
- }
-}
-
-func TestProxmoxGuestMemoryFallbackUsesInstanceScopedCachesAndAgentMeminfo(t *testing.T) {
- requiredSnippets := map[string][]string{
- "guest_memory_agent.go": {
- "func guestMemoryCacheKey(instanceName, node string, vmid int) string {",
- "return fmt.Sprintf(\"%s/%s/%d\", instanceName, node, vmid)",
- "func (m *Monitor) getVMAgentMemAvailable(ctx context.Context, client PVEClientInterface, instanceName, node string, vmid int) (uint64, error) {",
- "requestCtx, cancel := context.WithTimeout(ctx, vmAgentMemRequestTTL)",
- "ttl := vmAgentMemCacheTTL",
- "ttl = m.vmAgentMemNegativeCacheTTL(instanceName, node, vmid)",
- "vmAgentMemNegativeKnownGuestTTL = 30 * time.Second",
- },
- "guest_memory_sources.go": {
- "func shouldPreferGuestAgentMemAvailable(status *proxmox.VMStatus, memTotal uint64) bool {",
- "func (m *Monitor) tryGuestAgentMemAvailable(",
- "if !hasMemAvailable && shouldPreferGuestAgentMemAvailable(status, memTotal) {",
- // Guest rrddata carries no cache-aware memory columns (#1634):
- // the resolver must not consult guest RRD between the preferred
- // guest-agent pass and the retry pass.
- "// No RRD fallback here: PVE guest rrddata carries only cache-inclusive",
- "agentAvailable, agentSource, ok, deferred := m.tryGuestAgentMemAvailable(ctx, client, instanceName, guestName, node, vmid, memTotal, guestRaw)",
- "memorySource = agentSource",
- "guestRaw.GuestAgentMemAvailable = agentAvailable",
- `memorySource = "unavailable"`,
- },
- "monitor.go": {
- "vmAgentMemCache",
- "map[string]agentMemCacheEntry",
- },
- "monitor_agents.go": {
- "for key, entry := range m.vmAgentMemCache {",
- "if now.Sub(entry.fetchedAt) > vmAgentMemCleanupMaxAge {",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestLXCStatusCountersStayOnCanonicalMergePath(t *testing.T) {
- requiredSnippets := map[string][]string{
- "monitor_pve.go": {
- "func mergeContainerRuntimeCounters(current IOMetrics, status *proxmox.Container) IOMetrics {",
- "func (m *Monitor) enrichContainerMetadata(ctx context.Context, client PVEClientInterface, instanceName, nodeName string, container *models.Container, prefetchedStatus ...*proxmox.Container) {",
- },
- "monitor_pve_guest_lxc.go": {
- "currentMetrics = mergeContainerRuntimeCounters(currentMetrics, statusSnapshot)",
- "m.enrichContainerMetadata(ctx, client, instanceName, res.Node, &container, statusSnapshot)",
- },
- "monitor_polling_containers.go": {
- "currentMetrics = mergeContainerRuntimeCounters(currentMetrics, statusSnapshot)",
- "m.enrichContainerMetadata(",
- "statusSnapshot,",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
func TestDockerMutatingCommandsRespectCanonicalSecurityPosture(t *testing.T) {
monitor := newTestMonitorForCommands(t)
host := models.DockerHost{
@@ -1093,140 +674,37 @@ func TestDockerMutatingCommandsRespectCanonicalSecurityPosture(t *testing.T) {
}
}
-func TestProxmoxGuestMemoryCarryForwardUsesCanonicalSnapshotStability(t *testing.T) {
+func TestGuestDiskObservationContract(t *testing.T) {
+ t.Run("legacy-origin-admission", testGuestDiskLegacyObservationAge)
+ t.Run("original-source-age", testGuestDiskOriginalObservationAge)
+ t.Run("repeated-canonical-polls", testGuestDiskRepeatedPollsAndCanonicalOrigin)
+ t.Run("ordinary-deferral-expiry-recovery", testGuestDiskOrdinaryDeferralExpiryAndRecovery)
+}
+
+func TestGuestAgentAdmissionEvidenceContract(t *testing.T) {
+ t.Run("retained-identity-cannot-renew", testGuestAgentRetainedIdentityCannotRenewAdmission)
+ t.Run("original-age", testGuestAgentEvidenceOriginalAge)
+ t.Run("canonical-continuity", testGuestAgentEvidenceCanonicalContinuity)
+ t.Run("accepted-read-origins", testGuestAgentEvidenceAcceptedReadOrigins)
+ t.Run("config-flag-cannot-renew", testGuestAgentConfigFlagCannotRenewAdmission)
+}
+
+func TestProxmoxGuestDockerInventoryUsesCanonicalReportIngestPath(t *testing.T) {
requiredSnippets := map[string][]string{
- "guest_memory_stability.go": {
- "func (m *Monitor) previousGuestSnapshot(instance, guestType, node string, vmid int) *GuestMemorySnapshot {",
- "func stabilizeGuestLowTrustMemory(",
- "switch CanonicalMemorySource(source) {",
- `"preserved-previous-memory-after-repeated-low-trust-pattern"`,
- `"preserved-previous-memory-for-healthy-guest-low-trust-full-usage"`,
- },
- "monitor_pve_guest_builders.go": {
- `prevSnapshot := m.previousGuestSnapshot(instanceName, "qemu", res.Node, res.VMID)`,
- "state.memUsed, state.memorySource, snapshotNotes = stabilizeGuestLowTrustMemory(",
- },
- "monitor_pve_guest_poll.go": {
- "Notes: snapshotNotes,",
- },
- "monitor_polling_vm.go": {
- "prevVMByID := prevGuests.vmsByID",
- "m.pollNodeVMsWithClusterResourceBuilder(ctx, instanceName, n.Node, vms, client, prevVMByID, vmIDToHostAgent)",
- },
- "monitor_pve_node_vm_builder.go": {
- "return m.collectClusterVMResources(ctx, instanceName, resources, client, prevVMByID, vmIDToHostAgent), templateSubjects",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestProxmoxGuestDiskCarryForwardUsesCanonicalStabilityHelper(t *testing.T) {
- requiredSnippets := map[string][]string{
- "guest_disk_stability.go": {
- "func stabilizeGuestLowTrustDisk(",
- "func classifyGuestAgentDiskStatusError(err error) string {",
- `return total, used, free, prev.Disk.Usage, cloneGuestDisks(prev.Disks), "prev-" + diskStatusReason`,
- },
- "monitor_pve_guest_builders.go": {
- "state.diskTotal, state.diskUsed, state.diskFree, state.diskUsage, state.individualDisks, state.diskStatusReason = stabilizeGuestLowTrustDisk(",
- "DiskStatusReason: state.diskStatusReason,",
- "GuestAgentStatus: state.guestAgentStatus,",
- "GuestAgentExpected: state.guestAgentExpected,",
- "return nil, classifyGuestAgentDiskStatusError(err), false",
- },
- "monitor_polling_vm.go": {
- "m.pollNodeVMsWithClusterResourceBuilder(ctx, instanceName, n.Node, vms, client, prevVMByID, vmIDToHostAgent)",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestGuestDiskObservationContract(t *testing.T) {
- t.Run("legacy-origin-admission", testGuestDiskLegacyObservationAge)
- t.Run("original-source-age", testGuestDiskOriginalObservationAge)
- t.Run("repeated-canonical-polls", testGuestDiskRepeatedPollsAndCanonicalOrigin)
- t.Run("ordinary-deferral-expiry-recovery", testGuestDiskOrdinaryDeferralExpiryAndRecovery)
-}
-
-func TestGuestAgentAdmissionEvidenceContract(t *testing.T) {
- t.Run("retained-identity-cannot-renew", testGuestAgentRetainedIdentityCannotRenewAdmission)
- t.Run("original-age", testGuestAgentEvidenceOriginalAge)
- t.Run("canonical-continuity", testGuestAgentEvidenceCanonicalContinuity)
- t.Run("accepted-read-origins", testGuestAgentEvidenceAcceptedReadOrigins)
- t.Run("config-flag-cannot-renew", testGuestAgentConfigFlagCannotRenewAdmission)
-}
-
-func TestProxmoxGuestDiskInventoryPrefersCanonicalLinkedHostAgentSource(t *testing.T) {
- requiredSnippets := map[string][]string{
- "guest_host_agent_fallback.go": {
- "func resolveGuestDiskFromLinkedHostAgent(guestID string, vmIDToHostAgent map[string]models.Host) (models.Disk, []models.Disk, bool) {",
- "summary, ok := models.AggregateDisk(host.Disks)",
- "func preferLinkedHostAgentDiskInventory(",
- },
- "monitor_pve_guest_builders.go": {
- "preferLinkedHostAgentDiskInventory(",
- `Msg("QEMU disk: preferring linked Pulse host agent disk inventory")`,
- },
- "monitor_polling_vm.go": {
- "vmIDToHostAgent := prevGuests.hostAgentsByVMID",
- "m.pollNodeVMsWithClusterResourceBuilder(ctx, instanceName, n.Node, vms, client, prevVMByID, vmIDToHostAgent)",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestProxmoxGuestDockerInventoryUsesCanonicalReportIngestPath(t *testing.T) {
- requiredSnippets := map[string][]string{
- "docker_detection.go": {
- "type DockerInventoryCollector interface {",
- "proxmoxGuestDockerSocketMarker",
- "proxmoxGuestDockerNegativeRecheckAfter",
- "dockerCheckerConfiguredAt",
- "checker_reconfigured",
- "func (m *Monitor) CollectProxmoxGuestDockerInventory(ctx context.Context, containers []models.Container) {",
- "m.hasOnlineHostAgentForContainer(ct.ID)",
- "m.ApplyDockerReport(report, nil)",
- "pct exec %d -- sh -c",
- "container docker socket probe failed",
- `docker ps -a --no-trunc --format 'CONTAINER\\t{{json .ID}}`,
- `docker stats --no-stream --no-trunc --format 'STAT\\t{{json .ID}}`,
- "ParseProxmoxGuestDockerInventoryVMIDs",
+ "docker_detection.go": {
+ "type DockerInventoryCollector interface {",
+ "proxmoxGuestDockerSocketMarker",
+ "proxmoxGuestDockerNegativeRecheckAfter",
+ "dockerCheckerConfiguredAt",
+ "checker_reconfigured",
+ "func (m *Monitor) CollectProxmoxGuestDockerInventory(ctx context.Context, containers []models.Container) {",
+ "m.hasOnlineHostAgentForContainer(ct.ID)",
+ "m.ApplyDockerReport(report, nil)",
+ "pct exec %d -- sh -c",
+ "container docker socket probe failed",
+ `docker ps -a --no-trunc --format 'CONTAINER\\t{{json .ID}}`,
+ `docker stats --no-stream --no-trunc --format 'STAT\\t{{json .ID}}`,
+ "ParseProxmoxGuestDockerInventoryVMIDs",
},
"monitor_pve_guest_poll.go": {
"m.CollectProxmoxGuestDockerInventory(enrichmentCtx, allContainers)",
@@ -1349,146 +827,12 @@ func TestProxmoxGuestDockerLXCProbingRequiresExplicitOptIn(t *testing.T) {
}
func TestBackupOrphanDetectionUsesCanonicalInventoryReadinessScope(t *testing.T) {
- requiredSnippets := map[string][]string{
- "monitor.go": {
- "pveBackupInventoryReady",
- "map[string]map[string]bool",
- "pveBackupTemplateSubjects",
- "map[string]map[string]struct{}",
- },
- "monitor_backups.go": {
- "func (m *Monitor) updatePVEBackupTemplateSubjectsForType(instanceName, guestType string, subjects map[string]struct{}) {",
- "func (m *Monitor) updatePVEBackupTemplateSubjectsFromClusterResources(instanceName string, resources []proxmox.ClusterResource) {",
- "func (m *Monitor) backupInventoryScopeForAlerts() *alerts.BackupInventoryScope {",
- "m.checkBackupAlerts(ctx)",
- },
- "recovery_rollups.go": {
- "m.alertManager.CheckBackupsWithInventory(rollups, guestsByKey, guestsByVMID, m.backupInventoryScopeForAlerts())",
- },
- "monitor_pve_guest_poll.go": {
- "m.updatePVEBackupTemplateSubjectsFromClusterResources(instanceName, resources)",
- },
- "monitor_pve_node_vm_builder.go": {
- `pveBackupTemplateSubjectKey(instanceName, "qemu", node, vm.VMID)`,
- },
- "monitor_polling_vm.go": {
- `m.updatePVEBackupTemplateSubjectsForType(instanceName, "qemu", qemuTemplateSubjects)`,
- },
- "monitor_polling_containers.go": {
- `pveBackupTemplateSubjectKey(instanceName, "lxc", n.Node, int(container.VMID))`,
- `m.updatePVEBackupTemplateSubjectsForType(instanceName, "lxc", lxcTemplateSubjects)`,
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
// Inventory-readiness scope still owns orphan detection. The old spelling
// check also required an unbounded PBS alert read; exercise its actual
// expiry/ordinary-recovery behaviour instead of preserving that choice.
exercisePBSBudgetExpiredAlertEvaluation(t)
}
-func TestStoragePollingUsesCanonicalPoolMetadataForZFSAttachment(t *testing.T) {
- data, err := os.ReadFile("monitor_polling_storage.go")
- if err != nil {
- t.Fatalf("failed to read monitor_polling_storage.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "func matchZFSPoolForStorage(storage models.Storage, zfsPoolMap map[string]*models.ZFSPool) *models.ZFSPool {",
- "storage.Pool,",
- "Pool: storage.Pool,",
- "if modelStorage.Pool == \"\" && clusterConfig.Pool != \"\" {",
- "if pool := matchZFSPoolForStorage(modelStorage, zfsPoolMap); pool != nil {",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor_polling_storage.go must contain %q", snippet)
- }
- }
-}
-
-func TestStoragePollingKeepsSharedStorageClusterStatusCanonical(t *testing.T) {
- data, err := os.ReadFile("monitor_polling_storage.go")
- if err != nil {
- t.Fatalf("failed to read monitor_polling_storage.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "storage.Status = normalizeSharedStorageStatus(storage)",
- "entry.storage.Status = mergeSharedStorageStatus(entry.storage.Status, storage.Status)",
- "entry.storage.Enabled = entry.storage.Enabled || storage.Enabled",
- "entry.storage.Active = entry.storage.Active || storage.Active",
- "func normalizeSharedStorageStatus(storage models.Storage) string {",
- "func mergeSharedStorageStatus(current, candidate string) string {",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor_polling_storage.go must contain %q", snippet)
- }
- }
-}
-
-func TestMonitoringProxmoxClusterNodeDisplayNamesUsePersistedPresentationIdentity(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "func getNodeDisplayName(instance *config.PVEInstance, nodeName string) string {",
- "config.PVEClusterNodePresentation(instance, baseName)",
- "return baseName",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
-func TestMonitoringTemperatureFallbackPrefersRecentAgentTelemetry(t *testing.T) {
- requiredSnippets := map[string][]string{
- "host_agent_temps.go": {
- "func shouldSkipTemperatureSSHCollection(hostAgentTemp *models.Temperature) bool {",
- "return hasUsableTemperatureReading(hostAgentTemp)",
- "func hasUsableTemperatureReading(temp *models.Temperature) bool {",
- "temp.CPUPackage > 0 || temp.CPUMax > 0",
- "core.Temp > 0",
- "device.Temp > 0",
- "gpu.Edge > 0 || gpu.Junction > 0 || gpu.Mem > 0",
- "func hasUsableSMARTTemperature(temp *models.Temperature) bool {",
- "disk.Temperature > 0 && !disk.StandbySkipped",
- },
- "monitor_polling_node_helpers.go": {
- "skipSSHCollection := shouldSkipTemperatureSSHCollection(hostAgentTemp)",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
func TestMonitoringRuntimeAvoidsLegacyMockPartialHelpers(t *testing.T) {
forbiddenSnippets := []string{
"mock.GetMockState(",
@@ -1505,22 +849,6 @@ func TestMonitoringRuntimeAvoidsLegacyMockPartialHelpers(t *testing.T) {
}
}
-func TestBroadcastTickerRefreshesMockAlertsBeforeSubscriberEarlyExit(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("read monitor.go: %v", err)
- }
- source := string(data)
- mockRefresh := strings.Index(source, "if mock.IsMockEnabled() {\n\t\t\t\t_ = m.GetState()")
- subscriberGate := strings.Index(source, "if !currentStateBroadcasterHasSubscribers(wsHub, m.GetOrgID())")
- if mockRefresh < 0 {
- t.Fatal("broadcast ticker must preserve GetState's lazy mock alert snapshot refresh")
- }
- if subscriberGate < 0 || mockRefresh > subscriberGate {
- t.Fatal("mock alert snapshot refresh must run before the no-subscriber early exit")
- }
-}
-
func TestMockOwnedUnifiedMetricSyncDefersToCanonicalSamplerInMockMode(t *testing.T) {
previous := mock.IsMockEnabled()
mustSetMockEnabled(t, true)
@@ -1736,108 +1064,6 @@ func TestMonitorSetMockModeAuthorizesBeforeResettingRuntimeState(t *testing.T) {
}
}
-func TestConnectedInfrastructureUsesSharedTopLevelSystemResolver(t *testing.T) {
- data, err := os.ReadFile("connected_infrastructure.go")
- if err != nil {
- t.Fatalf("failed to read connected_infrastructure.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "resolver := unifiedresources.ResolveTopLevelSystems(resources)",
- "key := resolver.GroupIDForResource(resource)",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("connected_infrastructure.go must contain %q", snippet)
- }
- }
-}
-
-func TestConnectedInfrastructureKeepsPlatformConnectionsAndProjectsTrueNAS(t *testing.T) {
- data, err := os.ReadFile("connected_infrastructure.go")
- if err != nil {
- t.Fatalf("failed to read connected_infrastructure.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- `if agentSurface, ok := group.surfaces["agent"]; ok {`,
- `if dockerSurface, ok := group.surfaces["docker"]; ok {`,
- `if kubernetesSurface, ok := group.surfaces["kubernetes"]; ok {`,
- `if surface, ok := connectedInfrastructureTrueNASSurface(resource); ok {`,
- `Kind: "truenas",`,
- `case "truenas":`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("connected_infrastructure.go must contain %q", snippet)
- }
- }
-
- for _, forbidden := range []string{
- `delete(group.surfaces, "proxmox")`,
- `delete(group.surfaces, "pbs")`,
- `delete(group.surfaces, "pmg")`,
- `delete(group.surfaces, "truenas")`,
- } {
- if strings.Contains(source, forbidden) {
- t.Fatalf("connected_infrastructure.go must not remove platform-managed surfaces with %q", forbidden)
- }
- }
-}
-
-func TestConnectedInfrastructureSkipsChildPlatformResourceTypes(t *testing.T) {
- data, err := os.ReadFile("connected_infrastructure.go")
- if err != nil {
- t.Fatalf("failed to read connected_infrastructure.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "func connectedInfrastructureExplicitType(resource unifiedresources.Resource) unifiedresources.ResourceType {",
- "explicitType := connectedInfrastructureExplicitType(resource)",
- `if explicitType != "" && explicitType != unifiedresources.ResourceTypeAgent {`,
- `if explicitType != "" && explicitType != unifiedresources.ResourceTypePBS {`,
- `if explicitType != "" && explicitType != unifiedresources.ResourceTypePMG {`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("connected_infrastructure.go must contain %q", snippet)
- }
- }
-}
-
-func TestVMwarePollerUsesCanonicalSupplementalIngestOwnership(t *testing.T) {
- data, err := os.ReadFile("vmware_poller.go")
- if err != nil {
- t.Fatalf("failed to read vmware_poller.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "func (p *VMwarePoller) SupplementalRecords(_ *Monitor, orgID string) []unifiedresources.IngestRecord {",
- "func (p *VMwarePoller) SnapshotOwnedSources() []unifiedresources.DataSource {",
- "return []unifiedresources.DataSource{unifiedresources.SourceVMware}",
- "return vmware.NewAPIProvider(vmware.ProviderMetadata{",
- "func (p *VMwarePoller) ConnectionSummaries(orgID string, instances []config.VMwareVCenterInstance) map[string]VMwareConnectionSummary {",
- "func (p *VMwarePoller) RecordConnectionTestSuccess(orgID, connID string, summary *vmware.InventorySummary, at time.Time) {",
- "func (p *VMwarePoller) RecordConnectionTestFailure(orgID, connID string, err error, at time.Time) {",
- "summary.Degraded = true",
- "summary.IssueCount = len(snapshot.EnrichmentIssues)",
- "summary.Issues = summarizeVMwareObservedIssues(snapshot.EnrichmentIssues)",
- "observedIssueKey string",
- "transition := p.recordConnectionSuccessLocked(entry.orgID, entry.connectionID, at, snapshot)",
- "classifyVMwareObservedTransition(status.observed, status.observedIssueKey, nextObserved, nextIssueKey)",
- "status.observedIssueKey = nextIssueKey",
- `strings.HasPrefix(transition.action, "refresh_partial")`,
- `action: "refresh_partial_changed",`,
- `action: "refresh_recovered",`,
- "func summarizeVMwareObservedIssueKey(issues []vmware.InventoryEnrichmentIssue) string {",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("vmware_poller.go must contain %q", snippet)
- }
- }
-}
-
func TestMonitorAlertTimelineWritesCanonicalAlertMetadata(t *testing.T) {
data, err := os.ReadFile("monitor_alerts.go")
if err != nil {
@@ -1886,25 +1112,6 @@ func TestLegacyMemorySourceAliasesRemainCanonicalized(t *testing.T) {
}
}
-func TestProxmoxNodeDiskUsesCanonicalResolver(t *testing.T) {
- data, err := os.ReadFile("monitor_polling_node.go")
- if err != nil {
- t.Fatalf("failed to read monitor_polling_node.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "var nodeDiskSource string",
- "modelNode.Disk, nodeDiskSource = m.resolveNodeDisk(",
- "if resolvedDisk, diskSource := m.resolveNodeDisk(",
- "return modelNode, effectiveStatus, nodeDiskSource, nil",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor_polling_node.go must contain %q", snippet)
- }
- }
-}
-
func TestDockerReportPreservesMetadataAcrossObservedContainerRecreation(t *testing.T) {
migrationData, err := os.ReadFile("docker_metadata_migration.go")
if err != nil {
@@ -1934,136 +1141,10 @@ func TestDockerReportPreservesMetadataAcrossObservedContainerRecreation(t *testi
}
}
-func TestProxmoxNodeDiskFallbackPrefersCanonicalSystemStorage(t *testing.T) {
- requiredSnippets := map[string][]string{
- "node_disk_sources.go": {
- "func preferredNodeDiskFallbackRank(storage proxmox.Storage) (int, bool) {",
- `case "local-zfs":`,
- `case "local-lvm":`,
- `case "local":`,
- `supportsGuestRoots := storageContentIncludes(storage.Content, "images") || storageContentIncludes(storage.Content, "rootdir")`,
- "if storage.Shared != 0 {",
- },
- "monitor_pve.go": {
- "modelNodes, nodeEffectiveStatus, nodeDiskSources := m.pollPVENodesParallel(",
- "modelNodes = m.applyStorageFallbackAndRecordNodeMetrics(instanceName, client, modelNodes, nodeDiskSources, localStorageByNode)",
- },
- "monitor_pve_storage.go": {
- "rank, ok := preferredNodeDiskFallbackRank(storage)",
- `(modelNodes[i].Disk.Total == 0 || currentDiskSource == "")`,
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestProxmoxGuestPollersCarryPoolIntoCanonicalModels(t *testing.T) {
- requiredSnippets := map[string][]string{
- "monitor_pve_guest_builders.go": {"Pool: strings.TrimSpace(res.Pool)"},
- "monitor_pve_guest_lxc.go": {"Pool: strings.TrimSpace(res.Pool)"},
- "monitor_pve_node_vm_builder.go": {"Pool: vm.Pool"},
- "monitor_polling_containers.go": {"Pool: strings.TrimSpace(container.Pool)"},
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestProxmoxGuestAgentContinuityUsesCanonicalEvidenceAndRetryPaths(t *testing.T) {
- requiredSnippets := map[string][]string{
- "guest_agent_evidence.go": {
- "func hasRecentGuestAgentEvidence(prev *models.VM, now time.Time) bool {",
- `if prev == nil || prev.Type != "qemu" {`,
- "func shouldQueryGuestAgent(vmStatus *proxmox.VMStatus, prev *models.VM, now time.Time) bool {",
- "return hasRecentGuestAgentEvidence(prev, now)",
- },
- "guest_metadata.go": {
- "guestMetadataEmptyTTL = 30 * time.Second",
- "func guestMetadataCacheEntryTTL(entry guestMetadataCacheEntry) time.Duration {",
- "if guestMetadataCacheHasCompleteNetworkData(entry) {",
- "return guestMetadataEmptyTTL",
- "func (m *Monitor) hasRecentGuestMetadataEvidence(instanceName, nodeName string, vmid int, now time.Time) bool {",
- "func (m *Monitor) scheduleGuestMetadataFetchForEntry(key string, now time.Time, entry guestMetadataCacheEntry) {",
- },
- "monitor_previous_state.go": {
- "vmsByID map[string]models.VM",
- "ctx.vmsByID[modelVM.ID] = modelVM",
- "guestID := makeGuestID(modelVM.Instance, modelVM.Node, modelVM.VMID)",
- "ctx.vmsByID[guestID] = modelVM",
- },
- "monitor_pve_guest_builders.go": {
- "guestAgentAvailable := shouldQueryGuestAgent(state.detailedStatus, prevVM, now) ||",
- "m.hasRecentGuestMetadataEvidence(instanceName, res.Node, res.VMID, now)",
- `if guestAgentAvailable && res.Lock == "" && state.detailedStatus == nil {`,
- },
- "monitor_polling_vm.go": {
- "prevVMByID := prevGuests.vmsByID",
- "vmIDToHostAgent := prevGuests.hostAgentsByVMID",
- "m.pollNodeVMsWithClusterResourceBuilder(ctx, instanceName, n.Node, vms, client, prevVMByID, vmIDToHostAgent)",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-}
-
-func TestUnifiedAppContainerMetricsUseCanonicalGuestHistoryPath(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "m.syncUnifiedAppContainerMetrics(store)",
- `if target == nil || target.ResourceType != "app-container" || strings.TrimSpace(target.ResourceID) == "" {`,
- `metricKey := fmt.Sprintf("docker:%s", targetID)`,
- `storeWrites := make([]metrics.WriteMetric, 0)`,
- `appendStoreWrite("dockerContainer", targetID, "cpu", value, observedAt)`,
- `appendStoreWrite("dockerContainer", targetID, "diskwrite", metric.Value, observedAt)`,
- `m.metricsStore.WriteBatchBounded(storeWrites)`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
-func TestMockUnifiedStateViewUsesCanonicalMockFixtureGraph(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
+func TestMockUnifiedStateViewUsesCanonicalMockFixtureGraph(t *testing.T) {
+ data, err := os.ReadFile("monitor.go")
+ if err != nil {
+ t.Fatalf("failed to read monitor.go: %v", err)
}
source := string(data)
requiredSnippets := []string{
@@ -2082,234 +1163,6 @@ func TestMockUnifiedStateViewUsesCanonicalMockFixtureGraph(t *testing.T) {
}
}
-func TestUnifiedAgentMetricsUseCanonicalHostHistoryPath(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "m.syncUnifiedAgentMetrics(store)",
- `if target == nil || target.ResourceType != "agent" || strings.TrimSpace(target.ResourceID) == "" {`,
- `metricKey := fmt.Sprintf("agent:%s", targetID)`,
- `storeWrites := make([]metrics.WriteMetric, 0)`,
- `appendStoreWrite("agent", targetID, "cpu", value, observedAt)`,
- `appendStoreWrite("agent", targetID, "diskwrite", metric.Value, observedAt)`,
- `m.metricsStore.WriteBatchBounded(storeWrites)`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
-func TestUnifiedVMMetricsUseCanonicalVMHistoryPath(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "m.syncUnifiedVMMetrics(store)",
- `if target == nil || target.ResourceType != "vm" || strings.TrimSpace(target.ResourceID) == "" {`,
- `if source == unifiedresources.SourceProxmox {`,
- `storeWrites := make([]metrics.WriteMetric, 0)`,
- `appendStoreWrite("vm", targetID, "cpu", value, observedAt)`,
- `appendStoreWrite("vm", targetID, "diskwrite", metric.Value, observedAt)`,
- `m.metricsStore.WriteBatchBounded(storeWrites)`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
-func TestHostPhysicalDiskIOMetricsUseCanonicalDiskHistoryPath(t *testing.T) {
- data, err := os.ReadFile("monitor_agents.go")
- if err != nil {
- t.Fatalf("failed to read monitor_agents.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "m.writeHostPhysicalDiskIOMetrics(host, now, counterSampled)",
- "func (m *Monitor) writeHostPhysicalDiskIOMetrics(host models.Host, now time.Time, sampled counterSampleTime) {",
- "readRate, writeRate, busyPct, _, _ := m.rateTracker.calculateSampledRates(trackerKey, current, sampled)",
- `resourceID := unifiedresources.HostSMARTDiskMetricID(host, disk)`,
- `m.metricsHistory.AddDiskMetric(resourceID, "diskread", readRate, now)`,
- `m.metricsStore.Write("disk", resourceID, "diskwrite", writeRate, now)`,
- `m.metricsStore.Write("disk", resourceID, "disk", busyPct, now)`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor_agents.go must contain %q", snippet)
- }
- }
-}
-
-func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {
- cases := []struct {
- file string
- snippets []string
- }{
- {
- file: "monitor.go",
- snippets: []string{
- "func shouldSkipNativeMockStateMetricWrites() bool {",
- "return mock.IsMockEnabled()",
- },
- },
- {
- file: "monitor.go",
- snippets: []string{
- "func keepRealPollingInMockMode() bool {",
- "case \"\", \"0\", \"false\", \"no\", \"off\":",
- "return false",
- },
- },
- {
- file: "monitor.go",
- snippets: []string{
- "func shouldSkipMockOwnedUnifiedMetricSync(resource unifiedresources.Resource) bool {",
- "if !mock.IsMockEnabled() {",
- "return true",
- },
- },
- {
- file: "monitor_polling_vm.go",
- snippets: []string{
- "if !shouldSkipNativeMockStateMetricWrites() {",
- "guestHistoryRates(",
- "m.recordGuestMetric(",
- },
- },
- {
- file: "monitor_polling_containers.go",
- snippets: []string{
- "if !shouldSkipNativeMockStateMetricWrites() {",
- "guestHistoryRates(",
- "m.recordGuestMetric(",
- },
- },
- {
- file: "monitor_pve_guest_helpers.go",
- snippets: []string{
- "func (m *Monitor) recordGuestMetric(",
- "if m == nil || shouldSkipNativeMockStateMetricWrites() {",
- `m.metricsStore.Write(resourceType, resourceID, "memory", memory, now)`,
- },
- },
- {
- file: "kubernetes_agents.go",
- snippets: []string{
- "if shouldSkipNativeMockStateMetricWrites() {",
- `m.metricsStore.Write("k8s", metricID, "cpu", pod.UsageCPUPercent, timestamp)`,
- },
- },
- {
- file: "monitor_polling_storage.go",
- snippets: []string{
- "if m.metricsHistory != nil && !shouldSkipNativeMockStateMetricWrites() {",
- `m.metricsStore.Write("storage", storage.ID, "usage", storage.Usage, timestamp)`,
- },
- },
- {
- file: "monitor_metrics.go",
- snippets: []string{
- "func (m *Monitor) nativePhysicalDiskTemperatureHistory(duration time.Duration) map[string][]MetricPoint {",
- "if mock.IsMockEnabled() {",
- "return nil",
- "func (m *Monitor) prewarmMockDashboardChartCaches() {",
- },
- },
- {
- file: "mock_chart_history.go",
- snippets: []string{
- "func mockCanonicalMetricSeries(resourceType, resourceID, metricType string, timestamps []time.Time) []MetricPoint {",
- "values := canonicalMetricSeries(resourceType, resourceID, metricType, timestamps)",
- "func sampleMetricSeriesOnMockChartGrid(points []MetricPoint, interval time.Duration) []MetricPoint {",
- `usageValues := canonicalMetricSeries("storage", storageID, "usage", timestamps)`,
- },
- },
- {
- file: "mock_metrics_history.go",
- snippets: []string{
- "sampler := mock.NewMetricSampler(graph)",
- `cpu := sampler.SampleMetric("k8s", metricID, "cpu", ts)`,
- `memory := sampler.SampleMetric("k8s", metricID, "memory", ts)`,
- `ms.Write("k8s", metricID, "memory", memory, ts)`,
- "m.prewarmMockDashboardChartCaches()",
- },
- },
- {
- file: "monitor_agents.go",
- snippets: []string{
- "if !shouldSkipNativeMockStateMetricWrites() {",
- `m.metricsStore.Write("dockerHost", host.ID, "cpu", host.CPUUsage, now)`,
- `m.metricsStore.Write("agent", host.ID, "cpu", host.CPUUsage, now)`,
- },
- },
- {
- file: "monitor.go",
- snippets: []string{
- "func (m *Monitor) writeSMARTMetrics(disk models.PhysicalDisk, now time.Time) {",
- "if shouldSkipNativeMockStateMetricWrites() {",
- "return",
- },
- },
- }
-
- for _, tc := range cases {
- data, err := os.ReadFile(tc.file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", tc.file, err)
- }
- source := string(data)
- for _, snippet := range tc.snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", tc.file, snippet)
- }
- }
- }
-}
-
-func TestMockChartCacheRemainsMonitorOwned(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
-
- for _, snippet := range []string{
- "mockChartCacheMu sync.RWMutex",
- "mockChartMapCache map[mockChartMetricMapCacheKey]map[string][]MetricPoint",
- } {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
-func TestUnifiedPhysicalDiskMetricsUseCanonicalDiskHistoryPath(t *testing.T) {
- data, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "m.syncUnifiedPhysicalDiskMetrics(store)",
- `if target == nil || target.ResourceType != "disk" || strings.TrimSpace(target.ResourceID) == "" {`,
- `if source == unifiedresources.SourceProxmox || source == unifiedresources.SourceAgent {`,
- `m.writeSMARTMetrics(disk, unifiedResourceObservedAt(resource, now))`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-}
-
func TestProxmoxDiskAlertsRunOnMergedDiskState(t *testing.T) {
cases := []struct {
file string
@@ -2350,73 +1203,6 @@ func TestProxmoxDiskAlertsRunOnMergedDiskState(t *testing.T) {
}
}
-func TestUnifiedPhysicalDiskMetricsAllowNativeHistoryProviders(t *testing.T) {
- monitorData, err := os.ReadFile("monitor.go")
- if err != nil {
- t.Fatalf("failed to read monitor.go: %v", err)
- }
- monitorSource := string(monitorData)
- monitorSnippets := []string{
- "type MonitorPhysicalDiskTemperatureHistoryProvider interface {",
- `PhysicalDiskTemperatureHistory(m *Monitor, orgID string, duration time.Duration) map[string][]MetricPoint`,
- }
- for _, snippet := range monitorSnippets {
- if !strings.Contains(monitorSource, snippet) {
- t.Fatalf("monitor.go must contain %q", snippet)
- }
- }
-
- pollerData, err := os.ReadFile("truenas_poller.go")
- if err != nil {
- t.Fatalf("failed to read truenas_poller.go: %v", err)
- }
- pollerSource := string(pollerData)
- pollerSnippets := []string{
- "func (p *TrueNASPoller) PhysicalDiskTemperatureHistory(_ *Monitor, orgID string, duration time.Duration) map[string][]MetricPoint {",
- "entry.provider.PhysicalDiskTemperatureHistory(ctx, duration)",
- }
- for _, snippet := range pollerSnippets {
- if !strings.Contains(pollerSource, snippet) {
- t.Fatalf("truenas_poller.go must contain %q", snippet)
- }
- }
-}
-
-func TestTrueNASSystemTelemetryUsesCanonicalHostTemperatureModel(t *testing.T) {
- clientData, err := os.ReadFile(filepath.Join("..", "truenas", "client.go"))
- if err != nil {
- t.Fatalf("failed to read ../truenas/client.go: %v", err)
- }
- clientSource := string(clientData)
- clientSnippets := []string{
- `"reporting.get_data"`,
- `telemetry.TemperatureCelsius = cloneTemperatureMap(temperatures)`,
- `return parseSystemTemperatures(response), nil`,
- }
- for _, snippet := range clientSnippets {
- if !strings.Contains(clientSource, snippet) {
- t.Fatalf("../truenas/client.go must contain %q", snippet)
- }
- }
-
- providerData, err := os.ReadFile(filepath.Join("..", "truenas", "provider.go"))
- if err != nil {
- t.Fatalf("failed to read ../truenas/provider.go: %v", err)
- }
- providerSource := string(providerData)
- providerSnippets := []string{
- `if temperature := maxTrueNASSystemTemperature(system); temperature != nil {`,
- `agent.Temperature = temperature`,
- `if sensors := sensorMetaFromTrueNASSystem(system, disks); sensors != nil {`,
- `agent.Sensors = sensors`,
- }
- for _, snippet := range providerSnippets {
- if !strings.Contains(providerSource, snippet) {
- t.Fatalf("../truenas/provider.go must contain %q", snippet)
- }
- }
-}
-
func TestHostAgentRemovalGuardUsesResolvedIdentifier(t *testing.T) {
data, err := os.ReadFile("monitor_agents.go")
if err != nil {
@@ -2578,64 +1364,6 @@ func TestTelemetrySnapshotAggregationUsesProvisionedTenantSet(t *testing.T) {
}
}
-func TestReloadAndRuntimeContextStayOnCanonicalMonitoringPath(t *testing.T) {
- requiredSnippets := map[string][]string{
- "reload.go": {
- "config.LoadWithoutLoggingInit()",
- },
- "monitor.go": {
- "func (m *Monitor) setRuntimeContext(ctx context.Context, hub *websocket.Hub) {",
- "func (m *Monitor) getRuntimeContext() context.Context {",
- "m.setRuntimeContext(ctx, wsHub)",
- },
- "monitor_backups.go": {
- "owner := m.beginPVEBackupPoll(instanceName, client, lastPoll, newLast)",
- "ctx := context.WithValue(owner.ctx, pveBackupPollContextKey{}, owner)",
- },
- "pve_backup_poll.go": {
- "parent := m.runtimeCtx",
- "ctx, cancel := context.WithCancel(parent)",
- },
- "monitor_pve.go": {
- "parentCtx := m.getRuntimeContext()",
- },
- "monitor_pve_storage.go": {
- "parentCtx := m.getRuntimeContext()",
- },
- "monitor_pbs_pmg.go": {
- "owner := m.beginPBSBackupPoll(instanceName, client, lastPoll, newLast)",
- "parentCtx := context.WithValue(owner.ctx, pbsBackupPollContextKey{}, owner)",
- },
- "pbs_backup_poll.go": {
- "parent := m.runtimeCtx",
- "ctx, cancel := context.WithCancel(parent)",
- },
- "../config/config.go": {
- "func LoadWithoutLoggingInit() (*Config, error) {",
- "return load(false)",
- },
- }
-
- for file, snippets := range requiredSnippets {
- data, err := os.ReadFile(file)
- if err != nil {
- t.Fatalf("failed to read %s: %v", file, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", file, snippet)
- }
- }
- }
-
- // PBS captures its runtime with the client and admission claim, rather
- // than reading it again after starting the goroutine. Check the inherited
- // context itself as well as the entry point so this remains a safety guard,
- // not a requirement to restore an obsolete implementation spelling.
- exercisePBSBackupRuntimeContext(t)
-}
-
func TestUnifiedStorageMetricsFallbackToResourceIDWhenResolverTargetMissing(t *testing.T) {
data, err := os.ReadFile("monitor.go")
if err != nil {
diff --git a/internal/monitoring/monitor_pve_tag_style_test.go b/internal/monitoring/monitor_pve_tag_style_test.go
new file mode 100644
index 0000000000..c9e8354983
--- /dev/null
+++ b/internal/monitoring/monitor_pve_tag_style_test.go
@@ -0,0 +1,51 @@
+package monitoring
+
+import (
+ "context"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+)
+
+type clusterOptionsPVEClient struct {
+ PVEClientInterface
+ tagStyle string
+}
+
+func (c clusterOptionsPVEClient) GetClusterOptions(context.Context) (*proxmox.ClusterOptions, error) {
+ return &proxmox.ClusterOptions{TagStyle: c.tagStyle}, nil
+}
+
+// Proxmox tag colours are per PVE instance and may be case-sensitive. A later
+// refresh that clears one instance's colour map must not leave that instance's
+// colours behind in the aggregate map shown to the UI.
+func TestRefreshPVETagColorsKeepsStylePerInstance(t *testing.T) {
+ m := &Monitor{state: models.NewState()}
+ ctx := context.Background()
+
+ m.refreshPVETagColors(ctx, "pve-a", clusterOptionsPVEClient{tagStyle: "case-sensitive=1,color-map=Production:00ff00"})
+ m.refreshPVETagColors(ctx, "pve-b", clusterOptionsPVEClient{tagStyle: "color-map=backup:112233"})
+
+ snapshot := m.state.GetSnapshot()
+ styleA := snapshot.PVETagStyles["pve-a"]
+ if !styleA.CaseSensitive || styleA.Colors["Production"] != "#00ff00" {
+ t.Fatalf("pve-a style = %+v, want case-sensitive Production=#00ff00", styleA)
+ }
+ if styleB := snapshot.PVETagStyles["pve-b"]; styleB.CaseSensitive || styleB.Colors["backup"] != "#112233" {
+ t.Fatalf("pve-b style = %+v, want case-insensitive backup=#112233", styleB)
+ }
+
+ m.refreshPVETagColors(ctx, "pve-a", clusterOptionsPVEClient{tagStyle: ""})
+
+ snapshot = m.state.GetSnapshot()
+ if len(snapshot.PVETagStyles["pve-a"].Colors) != 0 {
+ t.Fatalf("pve-a style = %+v, want cleared colours", snapshot.PVETagStyles["pve-a"])
+ }
+ if _, stale := snapshot.PVETagColors["Production"]; stale {
+ t.Fatalf("aggregate colours = %+v, want pve-a Production removed", snapshot.PVETagColors)
+ }
+ if got := snapshot.PVETagColors["backup"]; got != "#112233" {
+ t.Fatalf("aggregate colours = %+v, want pve-b backup kept", snapshot.PVETagColors)
+ }
+}
diff --git a/internal/monitoring/node_disk_sources_test.go b/internal/monitoring/node_disk_sources_test.go
new file mode 100644
index 0000000000..128213af46
--- /dev/null
+++ b/internal/monitoring/node_disk_sources_test.go
@@ -0,0 +1,129 @@
+package monitoring
+
+import (
+ "context"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+)
+
+// The node disk bar falls back to a storage when neither the host agent nor
+// Proxmox reports a node filesystem. The order below decides which storage the
+// operator sees: the canonical system storages first, then guest-root capable
+// storages by type, and never shared or content-less ones.
+func TestPreferredNodeDiskFallbackRank(t *testing.T) {
+ tests := []struct {
+ name string
+ storage proxmox.Storage
+ want int
+ wantOK bool
+ }{
+ {name: "local-zfs", storage: proxmox.Storage{Storage: "local-zfs", Type: "zfspool"}, want: 0, wantOK: true},
+ {name: "local-lvm", storage: proxmox.Storage{Storage: "local-lvm", Type: "lvmthin"}, want: 1, wantOK: true},
+ {name: "local", storage: proxmox.Storage{Storage: "local", Type: "dir", Path: "/var/lib/vz"}, want: 2, wantOK: true},
+ {name: "zfs pool with guest roots", storage: proxmox.Storage{Storage: "tank", Type: "zfspool", Content: "images,rootdir"}, want: 3, wantOK: true},
+ {name: "lvm with guest images", storage: proxmox.Storage{Storage: "vg0", Type: "lvmthin", Content: "images"}, want: 4, wantOK: true},
+ {name: "default dir path", storage: proxmox.Storage{Storage: "vmdata", Type: "dir", Path: "/var/lib/vz", Content: "rootdir"}, want: 5, wantOK: true},
+ {name: "local-prefixed dir", storage: proxmox.Storage{Storage: "local-ssd", Type: "dir", Path: "/mnt/ssd", Content: "images"}, want: 6, wantOK: true},
+ {name: "other guest storage", storage: proxmox.Storage{Storage: "fast", Type: "dir", Path: "/mnt/fast", Content: "rootdir"}, want: 7, wantOK: true},
+ {name: "shared storage with guest images", storage: proxmox.Storage{Storage: "nfs-vms", Type: "nfs", Content: "images,rootdir", Shared: 1}, wantOK: false},
+ {name: "backup-only storage", storage: proxmox.Storage{Storage: "backups", Type: "dir", Path: "/mnt/backups", Content: "backup"}, wantOK: false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, ok := preferredNodeDiskFallbackRank(tt.storage)
+ if ok != tt.wantOK {
+ t.Fatalf("eligible = %v, want %v", ok, tt.wantOK)
+ }
+ if ok && got != tt.want {
+ t.Fatalf("rank = %d, want %d", got, tt.want)
+ }
+ })
+ }
+}
+
+// With several storages on a node whose own disk is unreported, the node disk
+// bar shows local-zfs rather than a larger or shared storage.
+func TestPollPVEInstanceNodeDiskFallbackPrefersCanonicalSystemStorage(t *testing.T) {
+ t.Setenv("PULSE_DATA_DIR", t.TempDir())
+
+ const gib = uint64(1024 * 1024 * 1024)
+ client := &stubPVEClient{
+ nodes: []proxmox.Node{{
+ Node: "nuc",
+ Status: "online",
+ CPU: 0.12,
+ MaxCPU: 8,
+ Mem: 4 * gib,
+ MaxMem: 8 * gib,
+ Uptime: 3600,
+ }},
+ allStorage: []proxmox.Storage{{Storage: "local-zfs"}},
+ storageByNode: map[string][]proxmox.Storage{
+ "nuc": {
+ {Storage: "nfs-vms", Type: "nfs", Content: "images,rootdir", Shared: 1, Total: 5000 * gib, Used: 100 * gib, Available: 4900 * gib},
+ {Storage: "local", Type: "dir", Path: "/var/lib/vz", Content: "iso,vztmpl,backup", Total: 2000 * gib, Used: 200 * gib, Available: 1800 * gib},
+ {Storage: "local-lvm", Type: "lvmthin", Content: "images,rootdir", Total: 1500 * gib, Used: 150 * gib, Available: 1350 * gib},
+ {Storage: "local-zfs", Type: "zfspool", Content: "images,rootdir", Total: 944 * gib, Used: 313 * gib, Available: 631 * gib},
+ },
+ },
+ }
+
+ mon := newTestPVEMonitor("test")
+ defer mon.alertManager.Stop()
+ defer mon.notificationMgr.Stop()
+ mon.config.PVEInstances[0].MonitorStorage = true
+
+ mon.pollPVEInstance(context.Background(), "test", client)
+
+ snapshot := mon.state.GetSnapshot()
+ if len(snapshot.Nodes) != 1 {
+ t.Fatalf("expected one node in state, got %d", len(snapshot.Nodes))
+ }
+ disk := snapshot.Nodes[0].Disk
+ if disk.Total != int64(944*gib) || disk.Used != int64(313*gib) {
+ t.Fatalf("node disk = %+v, want local-zfs totals (944 GiB total, 313 GiB used)", disk)
+ }
+}
+
+// A shared storage is never a node's own disk, so when it is the only storage
+// that holds guest roots the node reports no fallback disk at all.
+func TestPollPVEInstanceNodeDiskFallbackIgnoresSharedStorage(t *testing.T) {
+ t.Setenv("PULSE_DATA_DIR", t.TempDir())
+
+ const gib = uint64(1024 * 1024 * 1024)
+ client := &stubPVEClient{
+ nodes: []proxmox.Node{{
+ Node: "nuc",
+ Status: "online",
+ CPU: 0.12,
+ MaxCPU: 8,
+ Mem: 4 * gib,
+ MaxMem: 8 * gib,
+ Uptime: 3600,
+ }},
+ allStorage: []proxmox.Storage{{Storage: "nfs-vms"}},
+ storageByNode: map[string][]proxmox.Storage{
+ "nuc": {
+ {Storage: "nfs-vms", Type: "nfs", Content: "images,rootdir", Shared: 1, Total: 5000 * gib, Used: 100 * gib, Available: 4900 * gib},
+ {Storage: "backups", Type: "dir", Path: "/mnt/backups", Content: "backup", Total: 700 * gib, Used: 100 * gib, Available: 600 * gib},
+ },
+ },
+ }
+
+ mon := newTestPVEMonitor("test")
+ defer mon.alertManager.Stop()
+ defer mon.notificationMgr.Stop()
+ mon.config.PVEInstances[0].MonitorStorage = true
+
+ mon.pollPVEInstance(context.Background(), "test", client)
+
+ snapshot := mon.state.GetSnapshot()
+ if len(snapshot.Nodes) != 1 {
+ t.Fatalf("expected one node in state, got %d", len(snapshot.Nodes))
+ }
+ if disk := snapshot.Nodes[0].Disk; disk.Total != 0 {
+ t.Fatalf("node disk = %+v, want no fallback from shared or backup-only storage", disk)
+ }
+}
diff --git a/internal/monitoring/pbs_backup_lifecycle_test.go b/internal/monitoring/pbs_backup_lifecycle_test.go
index a07cfc2f3b..a42127ecad 100644
--- a/internal/monitoring/pbs_backup_lifecycle_test.go
+++ b/internal/monitoring/pbs_backup_lifecycle_test.go
@@ -19,6 +19,13 @@ func waitPBSBudget(t *testing.T, ch <-chan struct{}, phase string) {
}
}
+// PBS captures its runtime with the client and admission claim, rather than
+// reading it again after starting the goroutine, so the inherited context
+// itself is what must stay correct.
+func TestPBSBackupWorkersInheritRuntimeContext(t *testing.T) {
+ exercisePBSBackupRuntimeContext(t)
+}
+
func exercisePBSBackupRuntimeContext(t *testing.T) {
t.Run("PBS inherits the canonical runtime", func(t *testing.T) {
type runtimeKey struct{}
diff --git a/internal/monitoring/temperature_test.go b/internal/monitoring/temperature_test.go
index 56fc844f34..2f3ab891ab 100644
--- a/internal/monitoring/temperature_test.go
+++ b/internal/monitoring/temperature_test.go
@@ -225,14 +225,6 @@ func TestTemperatureCollector_ParseSensorsJSON_FlagsLegacyFormat(t *testing.T) {
assert.False(t, temp.HasSMART)
}
-func TestTemperatureCollector_HelperMethods(t *testing.T) {
- // extractCoreNumber
- // Private methods are hard to test directly from separate package if using _test,
- // but since we are in `monitoring`, we can access if same package.
- // But usually tests are `monitoring_test` package.
- // I will assume same package for now based on file declaration.
-}
-
func TestDefaultCommandRunner_RejectsOversizedStdout(t *testing.T) {
runner := &defaultCommandRunner{}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
diff --git a/internal/truenas/integration_test.go b/internal/truenas/integration_test.go
index f96b90253e..c0057c19f9 100644
--- a/internal/truenas/integration_test.go
+++ b/internal/truenas/integration_test.go
@@ -219,10 +219,6 @@ func TestIntegrationHealthStateTransition(t *testing.T) {
}
}
-func TestIntegrationStaleRecovery(t *testing.T) {
- t.Skip("redundant with TestProviderRefreshPreservesLastSnapshotOnError in provider_test.go")
-}
-
type dynamicResponses struct {
mu sync.Mutex
responses map[string]apiResponse
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 925a3d3bbe..1a430b5499 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -617,47 +617,6 @@ func TestProxmoxWorkloadActionTargetsStayBackendAuthored(t *testing.T) {
}
}
-func TestDockerSwarmEvidenceGuardStaysInAdapter(t *testing.T) {
- data, err := os.ReadFile("adapters.go")
- if err != nil {
- t.Fatalf("failed to read adapters.go: %v", err)
- }
- source := string(data)
-
- requiredSnippets := []string{
- "func hasReportableDockerSwarmInfo(info *models.DockerSwarmInfo) bool",
- `state == "inactive"`,
- "func convertSwarm(info *models.DockerSwarmInfo) *DockerSwarmInfo",
- "if !hasReportableDockerSwarmInfo(info) {",
- "return nil",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("adapters.go must contain %q", snippet)
- }
- }
-}
-
-func TestAPIResourcesKeepsOwnedSupplementalGapFillAndVMwareAlias(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("..", "api", "resourceapi", "resources.go"))
- if err != nil {
- t.Fatalf("failed to read ../api/resourceapi/resources.go: %v", err)
- }
- source := string(data)
-
- requiredSnippets := []string{
- "seedSources := unifiedSeedSources(seed.resources)",
- "!sourceOwnedBySupplementalProvider(source, ownedSources)",
- "(source != unified.SourceAvailability && unifiedSeedIncludesSource(seedSources, source))",
- `case "vmware", "vmware-vsphere":`,
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("../api/resourceapi/resources.go must contain %q", snippet)
- }
- }
-}
-
func TestResourceAPIUsesCanonicalTenantUnifiedSeed(t *testing.T) {
data, err := os.ReadFile(filepath.Join("..", "api", "resourceapi", "resources.go"))
if err != nil {
@@ -850,40 +809,6 @@ func TestCanonicalStorageMetadataCarriesFullZFSPoolReport(t *testing.T) {
}
}
-func TestCephPoolsProjectThroughCanonicalStoragePath(t *testing.T) {
- requiredSnippets := map[string][]string{
- filepath.Join("..", "models", "models.go"): {
- "func CephPoolStorageID(instanceName, poolName string) string",
- "func StorageFromCephPool(cluster CephCluster, pool CephPool) Storage",
- `Type: "ceph",`,
- "ID: CephPoolStorageID(cluster.Instance, name),",
- },
- "registry.go": {
- "models.CephPoolStorage(cluster)",
- "rr.ingestStorage(storage)",
- },
- filepath.Join("..", "monitoring", "ceph.go"): {
- "m.checkCephPoolStorage(cluster)",
- "models.CephPoolStorage(cluster)",
- `m.metricsStore.Write("storage", storage.ID, "usage", storage.Usage, timestamp)`,
- "m.alertManager.CheckStorageWithCapacityTrend(storage, m.storageCapacityTrend(storage, timestamp))",
- },
- }
-
- for path, snippets := range requiredSnippets {
- data, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("failed to read %s: %v", path, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must keep Ceph pool storage on canonical storage identity via %q", path, snippet)
- }
- }
- }
-}
-
func TestResourceAPIExposesDedicatedFacetReads(t *testing.T) {
requiredSnippets := map[string][]string{
filepath.Join("..", "api", "resourceapi", "resources.go"): {
@@ -1087,31 +1012,6 @@ func TestResourcePolicySummaryContractOmitsRawSignals(t *testing.T) {
}
}
-func TestResourceChangeFilterParsingIsOwnedByUnifiedResources(t *testing.T) {
- requiredSnippets := map[string][]string{
- filepath.Join(".", "change_filters.go"): {
- "func ParseResourceChangeFilters(kinds, sourceTypes, sourceAdapters []string) (ResourceChangeFilters, error)",
- "func parseResourceChangeKinds(values []string) ([]ChangeKind, error)",
- "func parseResourceChangeSourceTypes(values []string) ([]ChangeSourceType, error)",
- "func parseResourceChangeSourceAdapters(values []string) ([]ChangeSourceAdapter, error)",
- },
- filepath.Join("..", "api", "resourceapi", "resources.go"): {
- "unified.ParseResourceChangeFilters(r.URL.Query()[\"kind\"], r.URL.Query()[\"sourceType\"], r.URL.Query()[\"sourceAdapter\"])",
- },
- }
- for name, snippets := range requiredSnippets {
- data, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("failed to read %s: %v", name, err)
- }
- for _, snippet := range snippets {
- if !strings.Contains(string(data), snippet) {
- t.Fatalf("%s must contain %q", name, snippet)
- }
- }
- }
-}
-
func TestPlatformActivityTimelineContractStaysCanonical(t *testing.T) {
requiredSnippets := map[string][]string{
filepath.Join(".", "changes.go"): {
@@ -1176,228 +1076,6 @@ func TestPlatformActivityTimelineContractStaysCanonical(t *testing.T) {
}
}
-func TestResourcePolicyPresentationUsesCanonicalLabels(t *testing.T) {
- data, err := os.ReadFile(filepath.Join(".", "policy_presentation.go"))
- if err != nil {
- t.Fatalf("failed to read policy_presentation.go: %v", err)
- }
- source := string(data)
-
- requiredSnippets := []string{
- "ResourceSensitivityOrder",
- "ResourceRoutingScopeOrder",
- "ResourceRedactionHintOrder",
- "ResourceSensitivityLabel(",
- "ResourceRoutingScopeLabel(",
- "ResourceRedactionHintLabel(",
- "ResourcePolicyRedactionLabels(",
- "ResourcePolicyRedactionLabelsFromCounts(",
- "ResourcePolicySensitivitySummaryFromCounts(",
- "ResourcePolicyRoutingSummaryFromCounts(",
- "ResourcePolicySummaryLines(",
- "ResourcePolicyRedacts(",
- "ResourcePolicyUsesAISafeSummary(",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("policy_presentation.go must contain %q", snippet)
- }
- }
-}
-
-func TestResourcePolicyCloneHelperUsedByAIConsumers(t *testing.T) {
- requiredFiles := []string{
- filepath.Join("..", "ai", "chat", "context_prefetch.go"),
- filepath.Join("..", "ai", "tools", "tools_query.go"),
- filepath.Join(".", "policy_metadata.go"),
- }
- requiredSnippets := map[string]string{
- filepath.Join("..", "ai", "chat", "context_prefetch.go"): "unifiedresources.CanonicalGovernanceMetadata(resource)",
- filepath.Join("..", "ai", "tools", "tools_query.go"): "unifiedresources.CanonicalGovernanceMetadata(resource)",
- filepath.Join(".", "policy_metadata.go"): "func CanonicalGovernanceMetadata(resource *Resource) (*ResourcePolicy, string)",
- }
- for _, name := range requiredFiles {
- data, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("failed to read %s: %v", name, err)
- }
- snippet := requiredSnippets[name]
- if !strings.Contains(string(data), snippet) {
- t.Fatalf("%s must contain %q", name, snippet)
- }
- }
-}
-
-func TestAISafeSummarySuffixHelperIsOwnedByUnifiedResources(t *testing.T) {
- data, err := os.ReadFile(filepath.Join(".", "policy_metadata.go"))
- if err != nil {
- t.Fatalf("failed to read policy_metadata.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "func resourceAISafeSummaryPolicySuffix(sensitivity ResourceSensitivity) string",
- "return \"redacted for cloud summary\"",
- "return \"local-only context\"",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("policy_metadata.go must contain %q", snippet)
- }
- }
-}
-
-func TestCanonicalMetadataRefreshHelperUsedByConsumers(t *testing.T) {
- requiredSnippets := map[string][]string{
- filepath.Join(".", "policy_metadata.go"): {
- "func RefreshCanonicalMetadata(resource *Resource)",
- "func RefreshCanonicalMetadataSlice(resources []Resource) []Resource",
- },
- filepath.Join(".", "clone.go"): {
- "RefreshCanonicalMetadata(&out)",
- },
- filepath.Join("..", "api", "resourceapi", "resources.go"): {
- "unified.RefreshCanonicalMetadata(&resourceCopy)",
- "unified.RefreshCanonicalMetadataSlice(paged)",
- "unified.RefreshCanonicalMetadataSlice(children)",
- },
- filepath.Join("..", "ai", "resource_context.go"): {
- "unifiedresources.RefreshCanonicalMetadataSlice(urp.GetInfrastructure())",
- "unifiedresources.RefreshCanonicalMetadataSlice(urp.GetWorkloads())",
- "unifiedresources.RefreshCanonicalMetadataSlice(urp.GetAll())",
- },
- filepath.Join("..", "ai", "intelligence.go"): {
- "unifiedresources.RefreshCanonicalMetadataSlice(unifiedResourceProvider.GetAll())",
- },
- }
-
- for name, snippets := range requiredSnippets {
- data, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("failed to read %s: %v", name, err)
- }
- for _, snippet := range snippets {
- if !strings.Contains(string(data), snippet) {
- t.Fatalf("%s must contain %q", name, snippet)
- }
- }
- }
-}
-
-func TestResourcePolicyLabelHelpersUsedByAIConsumers(t *testing.T) {
- requiredSnippets := map[string][]string{
- filepath.Join("..", "ai", "intelligence.go"): {
- "func (i *Intelligence) HasCorrelationsSource() bool",
- "func (i *Intelligence) GetCorrelations(resourceID string) []*correlation.Correlation",
- "func (i *Intelligence) FormatCorrelationsContext(resourceID string) string",
- },
- filepath.Join("..", "ai", "service.go"): {
- "intel.FormatCorrelationsContext(resourceID)",
- },
- filepath.Join("..", "ai", "patrol_ai.go"): {
- "intelFacade.GetCorrelations(\"\")",
- },
- filepath.Join("..", "api", "ai_intelligence_handlers.go"): {
- "intel.HasCorrelationsSource()",
- "intel.GetCorrelations(resourceID)",
- },
- filepath.Join("..", "ai", "chat", "knowledge_extractor.go"): {
- "unifiedresources.ResourcePolicyLabel(",
- "unifiedresources.ResourcePolicyRedactedValue(",
- },
- filepath.Join("..", "ai", "chat", "context_prefetch.go"): {
- "tools.CanonicalToolResourceType(",
- "unifiedresources.ResourcePolicyRequiresGovernedSummary(mention.Policy)",
- "unifiedresources.FormatResourcePolicyGovernedSummary(mention.AISafeSummary, mention.Policy)",
- },
- filepath.Join("..", "ai", "tools", "executor.go"): {
- "func CanonicalToolResourceType(raw string) string",
- },
- filepath.Join("..", "ai", "resource_export.go"): {
- "unifiedresources.ResourceRedactionLabelsFromHints(redactionHints)",
- },
- filepath.Join("..", "ai", "resource_context.go"): {
- "unifiedresources.ResourcePolicyLabel(",
- "unifiedresources.ResourcePolicyRedactedText(",
- "unifiedresources.ResourceDisplayName(",
- "unifiedresources.ResourceClusterName(",
- "unifiedresources.ResourceIPSummary(",
- },
- filepath.Join("..", "ai", "chat", "service.go"): {
- "unifiedresources.ResourcePolicyRedactedTextWithReferences(",
- "unifiedresources.ResourcePolicyReference(",
- },
- filepath.Join("..", "unifiedresources", "unified_ai_adapter.go"): {
- "ResourceDisplayName(results[i])",
- "ResourceDisplayName(results[j])",
- },
- filepath.Join(".", "policy_presentation.go"): {
- "func ResourcePolicyLabel(name, aiSafeSummary string, policy *ResourcePolicy) string",
- "if ResourcePolicyRequiresGovernedSummary(policy) {",
- "return ResourcePolicyRedactedLabel",
- "return ResourcePolicyRequiresGovernedSummary(policy)",
- "Policy: sensitivity=%s, routing=%s",
- "func ResourcePolicyRedactedValue(value string, policy *ResourcePolicy, hints ...ResourceRedactionHint) string",
- "func ResourcePolicyRedactedText(value string, resource Resource) string",
- "func ResourcePolicyRedactedTextWithReferences(value string, resource Resource, references ...ResourcePolicyRedactionReference) string",
- "func ResourcePolicyReference(value string, hints ...ResourceRedactionHint) ResourcePolicyRedactionReference",
- "const ResourcePolicyRedactedLabel = \"redacted by policy\"",
- "func ResourceRedactionLabelsFromHints(hints []ResourceRedactionHint) []string",
- "func ResourceClusterName(resource Resource) string",
- "func ResourceIPSummary(resource Resource, limit int) string",
- "func ResourcePolicyRequiresGovernedSummary(policy *ResourcePolicy) bool",
- "func ResourcePolicyGovernedSummaryPreamble() string",
- "func ResourcePolicyGovernedSummaryFooter() string",
- "func FormatResourcePolicyGovernedSummary(summary string, policy *ResourcePolicy) string",
- "func ResourceDisplayName(resource Resource) string",
- },
- }
- for name, snippets := range requiredSnippets {
- data, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("failed to read %s: %v", name, err)
- }
- for _, snippet := range snippets {
- if !strings.Contains(string(data), snippet) {
- t.Fatalf("%s must contain %q", name, snippet)
- }
- }
- }
-}
-
-func TestPolicyPostureSummaryIsOwnedByUnifiedResources(t *testing.T) {
- requiredSnippets := map[string][]string{
- filepath.Join(".", "policy_posture.go"): {
- "type PolicyPostureSummary struct {",
- "func SummarizePolicyPosture(resources []Resource) *PolicyPostureSummary",
- "type ResourcePolicyPostureSummary struct {",
- "func ResourcePolicyPostureContract(summary *PolicyPostureSummary) *ResourcePolicyPostureSummary",
- },
- filepath.Join("..", "ai", "intelligence.go"): {
- "unifiedresources.PolicyPostureSummary",
- "unifiedresources.SummarizePolicyPosture(",
- },
- filepath.Join("..", "ai", "resource_context.go"): {
- "unifiedresources.SummarizePolicyPosture(allResources)",
- },
- filepath.Join("..", "api", "resourceapi", "resources.go"): {
- "resourcePolicyPostureAggregation(allResources)",
- "unified.ResourcePolicyPostureContract(unified.SummarizePolicyPosture(canonicalResources))",
- },
- }
-
- for name, snippets := range requiredSnippets {
- data, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("failed to read %s: %v", name, err)
- }
- for _, snippet := range snippets {
- if !strings.Contains(string(data), snippet) {
- t.Fatalf("%s must contain %q", name, snippet)
- }
- }
- }
-}
-
func TestExportDecisionHelpersUsedByAIConsumers(t *testing.T) {
data, err := os.ReadFile(filepath.Join("..", "ai", "resource_export.go"))
if err != nil {
@@ -1432,77 +1110,6 @@ func TestExportDecisionHelpersCanonicalInUnifiedResources(t *testing.T) {
}
}
-func TestRootCauseEngineUsesCanonicalRelationshipModel(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("..", "ai", "correlation", "rootcause.go"))
- if err != nil {
- t.Fatalf("failed to read rootcause.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "type RelationshipType = unifiedresources.RelationshipType",
- "type ResourceRelationship = unifiedresources.ResourceRelationship",
- "GetRelationships(resourceID string) []ResourceRelationship",
- "score += relationshipScore(rel.Type)",
- "func relationshipScore(t RelationshipType) float64",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("internal/ai/correlation/rootcause.go must pin canonical relationship snippet %q", snippet)
- }
- }
-}
-
-func TestResourceDisplayNameUsedByInfrastructureConsumers(t *testing.T) {
- requiredSnippets := map[string][]string{
- filepath.Join("..", "monitoring", "connected_infrastructure.go"): {
- "unifiedresources.ResourceDisplayName(resource)",
- },
- filepath.Join(".", "monitored_systems.go"): {
- "if name := ResourceDisplayName(*resource); name != \"\" {",
- },
- }
- for name, snippets := range requiredSnippets {
- data, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("failed to read %s: %v", name, err)
- }
- for _, snippet := range snippets {
- if !strings.Contains(string(data), snippet) {
- t.Fatalf("%s must contain %q", name, snippet)
- }
- }
- }
-}
-
-func TestTopLevelSystemResolverPinsCanonicalInfrastructureCounting(t *testing.T) {
- requiredSnippets := map[string][]string{
- filepath.Join(".", "monitored_systems.go"): {
- "resolveMonitoredSystemTopLevelSystems(rs).Count()",
- "ResolveTopLevelSystems(resources)",
- },
- filepath.Join(".", "top_level_systems.go"): {
- "ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver",
- "match.Confidence < HighConfidenceThreshold",
- "topLevelSystemGroupingExplanation(",
- "monitoredSystemCandidateAllowsHostAttachment(candidate)",
- "isNonUniqueIP(normalizedIP)",
- "When adding a new top-level monitored-system source, update:",
- },
- }
- for name, snippets := range requiredSnippets {
- data, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("failed to read %s: %v", name, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must contain %q", name, snippet)
- }
- }
- }
-}
-
func TestResourceTimelineStoreIndexesSupportFilteredReads(t *testing.T) {
data, err := os.ReadFile(filepath.Join("store.go"))
if err != nil {
@@ -1551,34 +1158,6 @@ func TestResourceChangeEmissionCoversRelationshipAndCapabilityChanges(t *testing
}
}
-func TestResourceChangePresentationUsesCanonicalLabels(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("change_presentation.go"))
- if err != nil {
- t.Fatalf("failed to read change_presentation.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "func ChangeKindLabel(kind ChangeKind) string",
- "func DescribeChange(change ResourceChange) ChangePresentation",
- "func FormatResourceChangeSummary(change ResourceChange) string",
- "func resourceRelationshipSummary(relationships []ResourceRelationship) string",
- "resourceStateSummary(resource Resource) string",
- "resourceRestartSummary(resource Resource) string",
- "resourceIncidentSummary(resource Resource) string",
- "resourceIncidentSummaryFromSlice(incidents []ResourceIncident) string",
- "resourceIncidentLabel(incident ResourceIncident) string",
- "resourceConfigSummary(resource Resource) string",
- "KindLabel: ChangeKindLabel(change.Kind)",
- "presentation.SourceType = strings.TrimSpace(string(change.SourceType))",
- "presentation.SourceAdapter = strings.TrimSpace(string(change.SourceAdapter))",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("internal/unifiedresources/change_presentation.go must pin canonical change presentation snippet %q", snippet)
- }
- }
-}
-
func TestAlertSnoozeChangeKindsRemainCanonical(t *testing.T) {
filters, err := ParseResourceChangeFilters([]string{"alert_snoozed,alert_unsnoozed"}, nil, nil)
if err != nil {
@@ -1593,152 +1172,6 @@ func TestAlertSnoozeChangeKindsRemainCanonical(t *testing.T) {
}
}
-func TestResourceRelationshipContextUsesCanonicalRelationshipPresentation(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("..", "ai", "service.go"))
- if err != nil {
- t.Fatalf("failed to read service.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "func (s *Service) buildResourceRelationshipContext(resourceID string) string",
- "if relationshipContext := s.buildResourceRelationshipContext(resourceID); relationshipContext != \"\" {",
- "Get canonical relationship context from unified resources.",
- "unifiedresources.FormatResourceRelationshipContext(resource, 3)",
- "unifiedresources.FormatResourceRecentChangesContext(changes, false, \"###\")",
- "type canonicalResourceGetter interface {",
- "intel.FormatCorrelationsContext(resourceID)",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("internal/ai/service.go must pin canonical relationship presentation snippet %q", snippet)
- }
- }
-}
-
-func TestResourceRelationshipModelUsesCanonicalEdgeComment(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("relationships.go"))
- if err != nil {
- t.Fatalf("failed to read relationships.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "// ResourceRelationship represents a typed relationship edge between two unified resources.",
- "type ResourceRelationship struct {",
- "const parentRelationshipDiscoverer = \"resource_registry\"",
- "func ResourceRelationshipsWithCanonicalParent(resource Resource) []ResourceRelationship",
- "relationshipType := parentRelationshipType(resource.Type)",
- "Metadata: map[string]any{",
- "func parentRelationshipType(resourceType ResourceType) RelationshipType",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("internal/unifiedresources/relationships.go must pin canonical relationship edge snippet %q", snippet)
- }
- }
-}
-
-func TestPatrolSeedCorrelationContextUsesCanonicalSummaryFormatter(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("..", "ai", "patrol_ai.go"))
- if err != nil {
- t.Fatalf("failed to read patrol_ai.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "# Known Resource Correlations",
- "correlation.FormatCorrelationSummary(c)",
- "memory.ChangeFromUnifiedResourceChange(change)",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("internal/ai/patrol_ai.go must pin canonical correlation presentation snippet %q", snippet)
- }
- }
-}
-
-func TestIntelligenceRecentChangesUseCanonicalSummaryFormatter(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("..", "ai", "intelligence.go"))
- if err != nil {
- t.Fatalf("failed to read intelligence.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "func (i *Intelligence) GetRecentChanges(since time.Time, limit int) []unifiedresources.ResourceChange",
- "func (i *Intelligence) DescribeResource(resourceID string) (string, string)",
- "func (i *Intelligence) HasRecentChangesSource() bool",
- "unifiedresources.FormatResourceRecentChangesContext(recent, includeResourcePrefix, \"##\")",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("internal/ai/intelligence.go must pin canonical recent-change snippet %q", snippet)
- }
- }
-}
-
-func TestMemoryChangeConversionHelpersAreSharedAcrossAIConsumers(t *testing.T) {
- requiredFiles := map[string][]string{
- filepath.Join("..", "ai", "patrol_ai.go"): {
- "memory.ChangeFromUnifiedResourceChange(change)",
- },
- filepath.Join("..", "ai", "intelligence.go"): {
- "memory.ResourceChangeFromMemoryChange(change)",
- },
- filepath.Join("..", "ai", "memory", "presentation.go"): {
- "func ChangeFromUnifiedResourceChange(change unifiedresources.ResourceChange) Change",
- "func ResourceChangeFromMemoryChange(change Change) unifiedresources.ResourceChange",
- },
- }
-
- for path, snippets := range requiredFiles {
- data, err := os.ReadFile(path)
- if err != nil {
- t.Fatalf("failed to read %s: %v", path, err)
- }
- source := string(data)
- for _, snippet := range snippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("%s must pin canonical memory conversion snippet %q", path, snippet)
- }
- }
- }
-}
-
-func TestAIRecentChangesHandlerUsesCanonicalIntelligencePath(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("..", "api", "ai_intelligence_handlers.go"))
- if err != nil {
- t.Fatalf("failed to read ai_intelligence_handlers.go: %v", err)
- }
- source := string(data)
- requiredSnippets := []string{
- "intel := patrol.GetIntelligence()",
- "intel.HasRecentChangesSource()",
- "intel.GetRecentChanges(since, 100)",
- "intel.DescribeResource(change.ResourceID)",
- "unifiedresources.FormatResourceChangeSummary(change)",
- "Recent changes not initialized",
- }
- for _, snippet := range requiredSnippets {
- if !strings.Contains(source, snippet) {
- t.Fatalf("internal/api/ai_intelligence_handlers.go must pin canonical recent-changes snippet %q", snippet)
- }
- }
-}
-
-func TestResourcePresentationsUseSharedDurationHelper(t *testing.T) {
- requiredFiles := []string{
- "change_presentation.go",
- "relationship_presentation.go",
- }
- for _, name := range requiredFiles {
- data, err := os.ReadFile(filepath.Join(name))
- if err != nil {
- t.Fatalf("failed to read %s: %v", name, err)
- }
- if !strings.Contains(string(data), "utils.FormatDurationAgo(") {
- t.Fatalf("%s must use the shared utils.FormatDurationAgo helper", name)
- }
- }
-}
-
func TestResourceFacetCountsAreCanonicalResourceFields(t *testing.T) {
typesData, err := os.ReadFile(filepath.Join("types.go"))
if err != nil {
@@ -2594,45 +2027,6 @@ func TestCanonicalResourceOrderingContractsStayShared(t *testing.T) {
}
}
-func TestBroadcastStateUsesSharedCanonicalResourceContract(t *testing.T) {
- repoRoot := filepath.Join("..", "..")
- typesPath := filepath.Join(repoRoot, "internal", "unifiedresources", "types.go")
- resourcesPath := filepath.Join(repoRoot, "internal", "api", "resourceapi", "resources.go")
- monitorPath := filepath.Join(repoRoot, "internal", "monitoring", "monitor.go")
-
- typesSource, err := os.ReadFile(typesPath)
- if err != nil {
- t.Fatalf("failed to read %s: %v", typesPath, err)
- }
- resourcesSource, err := os.ReadFile(resourcesPath)
- if err != nil {
- t.Fatalf("failed to read %s: %v", resourcesPath, err)
- }
- monitorSource, err := os.ReadFile(monitorPath)
- if err != nil {
- t.Fatalf("failed to read %s: %v", monitorPath, err)
- }
-
- if !strings.Contains(string(typesSource), "func ContractResourceType(resource Resource) ResourceType {") {
- t.Fatalf("%s: unified resource contract type helper must remain canonical", filepath.ToSlash(typesPath))
- }
- if !strings.Contains(string(resourcesSource), "return unified.ContractResourceType(r)") {
- t.Fatalf("%s: /api/resources must derive external resource types from unified.ContractResourceType", filepath.ToSlash(resourcesPath))
- }
-
- requiredMonitorSnippets := []string{
- "unifiedView := m.currentUnifiedStateView()",
- "return string(unifiedresources.ContractResourceType(*resource))",
- "unifiedresources.ResourceDisplayName(*resource)",
- "unifiedresources.ResourceClusterName(*resource)",
- }
- for _, snippet := range requiredMonitorSnippets {
- if !strings.Contains(string(monitorSource), snippet) {
- t.Fatalf("%s: websocket/state broadcast must contain %q", filepath.ToSlash(monitorPath), snippet)
- }
- }
-}
-
func TestCloneHostSensorMetaKeepsGPUSensorsIsolated(t *testing.T) {
temperature := 63.0
utilization := 42.0