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.

Align discovery with tool-led AI runtime

rcourtman6aad1118cdcc
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index f7c7e2a2c7..753476cbdd 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -2956,7 +2956,7 @@
},
{
"id": "RA29",
- "summary": "Interactive Pulse Assistant chat behaves like a governed LLM tool surface, not a Pulse-authored intent router: the operator's selected model receives the user turn and governed tools, decides whether tools are needed, and Pulse must not use prompt heuristics to force tool_choice, force a named tool, retry because an expected tool was not used, hide tools from the model by keyword detection, rewrite recent-context turns into Pulse-targeted instructions, fuzzy-match plain chat text into resource context before the model acts, synthesize/prefill/auto-submit product-authored Assistant prompts from handoffs, keyword-match prior remediation history into suggested fixes, or generate Patrol handoff attention/decision/remediation guidance before the model reasons. Pulse only provides current context and enforces approvals, resource resolution, FSM gates, and tool policy after that model choice; any model-visible policy block must describe the boundary without naming a required next tool. The chat surface must echo user messages before network/session creation finishes and must not render Pulse-owned explore or internal workflow status cards as assistant output.",
+ "summary": "Pulse intelligence comes from the operator-selected large language model using governed Pulse tools over data the model cannot reach on its own: agent-collected machine evidence, canonical APIs, metrics, discovery records, and resource state. Interactive Pulse Assistant chat therefore behaves like a governed LLM tool surface, not a Pulse-authored intent router: the operator's selected model receives the user turn and governed tools, decides whether tools are needed, and Pulse must not use prompt heuristics to force tool_choice, force a named tool, retry because an expected tool was not used, hide tools from the model by keyword detection, rewrite recent-context turns into Pulse-targeted instructions, fuzzy-match plain chat text into resource context before the model acts, synthesize/prefill/auto-submit product-authored Assistant prompts from handoffs, keyword-match prior remediation history into suggested fixes, or generate Patrol handoff attention/decision/remediation guidance before the model reasons. Pulse only provides current context and enforces approvals, resource resolution, FSM gates, and tool policy after that model choice; any model-visible policy block must describe the boundary without naming a required next tool. The chat surface must echo user messages before network/session creation finishes and must not render Pulse-owned explore or internal workflow status cards as assistant output.",
"kind": "invariant",
"blocking_level": "repo-ready",
"proof_type": "automated",
@@ -6446,21 +6446,7 @@
],
"coverage_gaps": [],
"candidate_lanes": [],
- "work_claims": [
- {
- "id": "codex-lane-l6",
- "agent_id": "codex",
- "summary": "Fix workload discovery settings persistence and per-guest manual discovery control",
- "target_id": "v6-product-lane-expansion",
- "claimed_at": "2026-05-15T21:36:03Z",
- "heartbeat_at": "2026-05-15T21:36:03Z",
- "expires_at": "2026-05-15T23:36:03Z",
- "work_item": {
- "kind": "lane",
- "id": "L6"
- }
- }
- ],
+ "work_claims": [],
"open_decisions": [],
"source_of_truth_file": "docs/release-control/v6/internal/SOURCE_OF_TRUTH.md",
"resolved_decisions": [
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 1fc1ed8228..c18248ef83 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -110,6 +110,13 @@ runtime cost control, and shared AI transport surfaces.
9. Add or change public AI overview wording through `docs/AI.md`; it may
describe Assistant and Patrol capabilities, but it must not revive legacy
commercial shorthand such as `incident memory` as a current product promise.
+10. Platform-first top-level pages registered in
+ `frontend-modern/src/App.tsx` and the platform tab list in
+ `frontend-modern/src/AppLayout.tsx` must keep the AI launcher chrome
+ intact: they extend `aiChatStore`-aware route shells rather than mounting
+ bespoke layouts that suppress the Assistant launcher, Patrol entry, or
+ the AI keyboard-shortcut handlers. New per-platform sub-routes inherit
+ the shared AI-aware chrome by virtue of routing through `AppLayout`.
## Forbidden Paths
@@ -154,7 +161,7 @@ runtime cost control, and shared AI transport surfaces.
divergence must be sourced from canonical `ReadState.DockerHosts()` views,
with model-shaped data limited to the watcher adapter input rather than
direct `StateSnapshot.DockerHosts` reads in the Patrol run loop.
-4. Keep discovery scheduling authoritative through `internal/config/ai.go`: `discovery_enabled` and `discovery_interval_hours` must govern both lightweight infrastructure discovery and deep service-discovery background loops. `internal/api/ai_handlers.go` must preserve an explicitly supplied `discovery_interval_hours: 0` as the manual-only setting and may only apply the 24-hour default when discovery is enabled without an explicit interval payload.
+4. Keep discovery scheduling authoritative through `internal/config/ai.go`: `discovery_enabled` and `discovery_interval_hours` must govern both lightweight infrastructure discovery and deep service-discovery background loops. `internal/api/ai_handlers.go` must preserve an explicitly supplied `discovery_interval_hours: 0` as the manual-only setting and may only apply the 24-hour default when discovery is enabled without an explicit interval payload. Discovery analysis remains a Pulse tool-led model workflow: Pulse supplies agent/API/metrics evidence and cache orchestration, while the selected model provides the intelligence. Background or drawer-triggered discovery progress must describe that discovery analysis directly and must not imply a live Pulse Assistant chat transcript unless the run is actually executing inside the chat surface. Assistant and Patrol access to discovery must stay behind the governed `pulse_discovery` tool, including an explicit forced refresh action for known resources.
5. Preserve auditability for outbound model-bound context exports and keep the export record aligned with the prompt boundary that actually reaches the provider
External provider-bound unified-resource context must enforce the same
data-handling policy the export audit records: `local-only` resources are
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 6c1400984a..064d8a54f9 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1367,7 +1367,11 @@ the canonical monitored-system blocked payload.
must send `discovery_enabled` and `discovery_interval_hours` together as
explicit form truth, and the backend must persist a provided
`discovery_interval_hours: 0` as manual-only rather than replacing it with
- the automatic-scan default.
+ the automatic-scan default. Manual discovery can be triggered directly
+ through the discovery API for a known resource and through the governed
+ `pulse_discovery` tool; the API progress payload must describe discovery
+ evidence analysis rather than presenting background work as a visible
+ Pulse Assistant chat session.
25. Keep shared AI runtime reads centralized on that same governed contract:
`frontend-modern/src/stores/aiRuntimeState.ts` is the canonical frontend
read owner for `/api/settings/ai` and `/api/ai/models`. AI-owned consumers
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 8dfcb4a9b4..dfdd3b9bf0 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -322,6 +322,11 @@ AI runtime.
if the shell exposes a shortcut hint, it must name an actual key chord,
otherwise the hint must remain unset so the shared `SearchInput` renders no
shortcut chip.
+ Native select state belongs to the shared
+ `frontend-modern/src/components/shared/FormSelect.tsx` primitive. It must
+ apply controlled `value` props after options are mounted so settings panels
+ such as workload discovery show the persisted option instead of falling back
+ to the first option while the collapsed summary shows a different value.
2. Route new top-level settings surfaces through the canonical settings shell
instead of introducing page-local framing.
When a new operator-facing concern is closely related to an
@@ -909,6 +914,16 @@ AI runtime.
plain select options. The picker must also constrain its dropdown and
internal result list to the available viewport height so settings model
catalogs remain usable on mobile and tablet layouts with bottom navigation.
+ Platform-first top-level pages registered through
+ `frontend-modern/src/App.tsx` must stay chrome-only and route through the
+ canonical app shell: each per-platform surface owns navigation and sub-tab
+ chrome, then embeds the canonical `WorkloadsSurface`, `StorageSurface`,
+ `RecoverySurface`, or `UnifiedResourceTable` in `embedded tableOnly` mode
+ with a forced platform or source filter. Per-platform features must not
+ fork their own table primitives, header layouts, or summary cards when a
+ shared canonical surface already exists; new shared platform-page
+ primitives live under `frontend-modern/src/features/platformPage/` so the
+ chrome stays reusable across families.
## Forbidden Paths
diff --git a/frontend-modern/src/components/shared/FormSelect.test.tsx b/frontend-modern/src/components/shared/FormSelect.test.tsx
index 02412113f9..cf15524aaf 100644
--- a/frontend-modern/src/components/shared/FormSelect.test.tsx
+++ b/frontend-modern/src/components/shared/FormSelect.test.tsx
@@ -15,7 +15,9 @@ describe('FormSelect', () => {
</FormSelect>
));
- expect(screen.getByLabelText('Delivery mode')).toBe(screen.getByTestId('delivery-mode'));
+ const select = screen.getByLabelText('Delivery mode');
+ expect(select).toBe(screen.getByTestId('delivery-mode'));
+ expect(select).toHaveValue('cli');
});
it('preserves explicit ids and compact styling hooks', () => {
diff --git a/frontend-modern/src/components/shared/FormSelect.tsx b/frontend-modern/src/components/shared/FormSelect.tsx
index 9befba9a6b..4000bc8d45 100644
--- a/frontend-modern/src/components/shared/FormSelect.tsx
+++ b/frontend-modern/src/components/shared/FormSelect.tsx
@@ -1,4 +1,4 @@
-import { Show, createUniqueId, splitProps } from 'solid-js';
+import { Show, createEffect, createUniqueId, splitProps } from 'solid-js';
import type { Component, JSX } from 'solid-js';
import { formField, formHelpText, formLabel, formSelect } from '@/components/shared/Form';
@@ -30,7 +30,9 @@ export const FormSelect: Component<FormSelectProps> = (props) => {
'class',
'selectBaseClass',
'selectClass',
+ 'value',
]);
+ let selectElement: HTMLSelectElement | undefined;
const generatedId = `form-select-${createUniqueId()}`;
const selectId = () => (typeof local.id === 'string' && local.id ? local.id : generatedId);
const helpId = () => `${selectId()}-help`;
@@ -46,12 +48,33 @@ export const FormSelect: Component<FormSelectProps> = (props) => {
return ids || undefined;
};
+ createEffect(() => {
+ const value = local.value;
+ if (!selectElement || value === undefined || value === null) return;
+
+ if (Array.isArray(value)) {
+ const selectedValues = new Set(value.map(String));
+ for (const option of Array.from(selectElement.options)) {
+ option.selected = selectedValues.has(option.value);
+ }
+ return;
+ }
+
+ const nextValue = String(value);
+ if (selectElement.value !== nextValue) {
+ selectElement.value = nextValue;
+ }
+ });
+
return (
<div class={joinClass(local.fieldBaseClass ?? formField, local.fieldClass)}>
<label for={selectId()} class={joinClass(formLabel, local.labelClass)}>
{local.label}
</label>
<select
+ ref={(element) => {
+ selectElement = element;
+ }}
{...selectProps}
id={selectId()}
aria-describedby={describedBy()}
diff --git a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
index 8f0f668432..d590ae3f5d 100644
--- a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
+++ b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
@@ -248,6 +248,9 @@ describe('shared primitive guardrails', () => {
expect(formSelectSource).toContain('<select');
expect(formSelectSource).toContain('id={selectId()}');
expect(formSelectSource).toContain('aria-describedby={describedBy()}');
+ expect(formSelectSource).toContain('createEffect');
+ expect(formSelectSource).toContain("'value'");
+ expect(formSelectSource).toContain('selectElement.value = nextValue');
expect(formSelectSource).toContain('local.selectBaseClass ?? formSelect');
expect(formSelectSource).toContain('local.fieldBaseClass ?? formField');
});
diff --git a/internal/ai/chat/context_prefetch.go b/internal/ai/chat/context_prefetch.go
index 056c82f867..195b28764a 100644
--- a/internal/ai/chat/context_prefetch.go
+++ b/internal/ai/chat/context_prefetch.go
@@ -628,7 +628,7 @@ func (p *ContextPrefetcher) getOrTriggerDiscovery(ctx context.Context, mention R
Str("type", canonicalType).
Msg("[ContextPrefetch] Triggering discovery")
- discovery, err = p.discoveryProvider.TriggerDiscovery(ctx, discoveryType, mention.TargetID, mention.ResourceID)
+ discovery, err = p.discoveryProvider.TriggerDiscovery(ctx, discoveryType, mention.TargetID, mention.ResourceID, false)
if err != nil {
return nil, err
}
diff --git a/internal/ai/chat/context_prefetch_additional_test.go b/internal/ai/chat/context_prefetch_additional_test.go
index c9fb1e9267..4e6c690151 100644
--- a/internal/ai/chat/context_prefetch_additional_test.go
+++ b/internal/ai/chat/context_prefetch_additional_test.go
@@ -48,7 +48,7 @@ func (m *mockDiscoveryProvider) FormatForAIContext(discoveries []*tools.Resource
return ""
}
-func (m *mockDiscoveryProvider) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string) (*tools.ResourceDiscoveryInfo, error) {
+func (m *mockDiscoveryProvider) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, _ bool) (*tools.ResourceDiscoveryInfo, error) {
m.triggeredKey = append(m.triggeredKey, m.key(resourceType, targetID, resourceID))
if m.triggerErr != nil {
return nil, m.triggerErr
diff --git a/internal/ai/tools/adapters.go b/internal/ai/tools/adapters.go
index 07c893e2b6..302df96f0c 100644
--- a/internal/ai/tools/adapters.go
+++ b/internal/ai/tools/adapters.go
@@ -876,7 +876,7 @@ type DiscoverySource interface {
ListDiscoveriesByTarget(targetID string) ([]DiscoverySourceData, error)
FormatForAIContext(discoveries []DiscoverySourceData) string
// TriggerDiscovery initiates discovery for a resource, returning discovered data
- TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string) (DiscoverySourceData, error)
+ TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, force bool) (DiscoverySourceData, error)
}
// DiscoverySourceData represents discovery data from the source
@@ -1085,12 +1085,12 @@ func (a *DiscoveryMCPAdapter) FormatForAIContext(discoveries []*ResourceDiscover
}
// TriggerDiscovery implements tools.DiscoveryProvider
-func (a *DiscoveryMCPAdapter) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string) (*ResourceDiscoveryInfo, error) {
+func (a *DiscoveryMCPAdapter) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, force bool) (*ResourceDiscoveryInfo, error) {
if a.source == nil {
return nil, fmt.Errorf("discovery source not available")
}
- data, err := a.source.TriggerDiscovery(ctx, resourceType, targetID, resourceID)
+ data, err := a.source.TriggerDiscovery(ctx, resourceType, targetID, resourceID, force)
if err != nil {
return nil, err
}
diff --git a/internal/ai/tools/discovery_adapter_test.go b/internal/ai/tools/discovery_adapter_test.go
index c556bc0c23..b0ab97990d 100644
--- a/internal/ai/tools/discovery_adapter_test.go
+++ b/internal/ai/tools/discovery_adapter_test.go
@@ -45,8 +45,8 @@ func (m *MockDiscoverySource) FormatForAIContext(discoveries []DiscoverySourceDa
return args.String(0)
}
-func (m *MockDiscoverySource) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string) (DiscoverySourceData, error) {
- args := m.Called(ctx, resourceType, targetID, resourceID)
+func (m *MockDiscoverySource) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, force bool) (DiscoverySourceData, error) {
+ args := m.Called(ctx, resourceType, targetID, resourceID, force)
return args.Get(0).(DiscoverySourceData), args.Error(1)
}
@@ -191,9 +191,9 @@ func TestDiscoveryMCPAdapter_TriggerDiscovery(t *testing.T) {
ctx := context.Background()
expectedData := DiscoverySourceData{ID: "new1"}
- mockSource.On("TriggerDiscovery", ctx, "vm", "h1", "100").Return(expectedData, nil)
+ mockSource.On("TriggerDiscovery", ctx, "vm", "h1", "100", true).Return(expectedData, nil)
- result, err := adapter.TriggerDiscovery(ctx, "vm", "h1", "100")
+ result, err := adapter.TriggerDiscovery(ctx, "vm", "h1", "100", true)
assert.NoError(t, err)
assert.Equal(t, "new1", result.ID)
diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.go
index c953cca147..bcff2e723f 100644
--- a/internal/ai/tools/executor.go
+++ b/internal/ai/tools/executor.go
@@ -280,7 +280,7 @@ type DiscoveryProvider interface {
ListDiscoveriesByTarget(targetID string) ([]*ResourceDiscoveryInfo, error)
FormatForAIContext(discoveries []*ResourceDiscoveryInfo) string
// TriggerDiscovery initiates discovery for a resource and returns the result
- TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string) (*ResourceDiscoveryInfo, error)
+ TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, force bool) (*ResourceDiscoveryInfo, error)
}
// ResolvedResourceInfo contains the minimal information needed for tool validation.
@@ -1087,7 +1087,7 @@ func (e *PulseToolExecutor) registerTools() {
// pulse_file_edit - read, append, write files (requires control permission)
e.registerFileTools()
- // pulse_discovery - get, list discoveries
+ // pulse_discovery - get, run, list discoveries
e.registerDiscoveryTools()
// pulse_knowledge - remember, recall, incidents, correlate, relationships
diff --git a/internal/ai/tools/tools_discovery.go b/internal/ai/tools/tools_discovery.go
index 585fabb6fc..c0c91e9826 100644
--- a/internal/ai/tools/tools_discovery.go
+++ b/internal/ai/tools/tools_discovery.go
@@ -14,27 +14,27 @@ func (e *PulseToolExecutor) registerDiscoveryTools() {
e.registry.Register(RegisteredTool{
Definition: Tool{
Name: "pulse_discovery",
- Description: `Get AI-discovered service details (log paths, config locations, ports). action="get" triggers discovery for a resource (requires resource_type, resource_id, target_id). action="list" searches existing discoveries. Resource details must already be known from the current context or a prior resource lookup.`,
+ Description: `Get or run AI-discovered service details from Pulse-owned resource access. action="get" returns existing discovery and triggers discovery only when missing. action="run" forces a fresh discovery run for a known resource. action="list" searches existing discoveries. Resource details must already be known from the current context or a prior resource lookup.`,
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
"action": {
Type: "string",
- Description: "Discovery action: get or list",
- Enum: []string{"get", "list"},
+ Description: "Discovery action: get, run, or list",
+ Enum: []string{"get", "run", "list"},
},
"resource_type": {
Type: "string",
- Description: "For get: canonical v6 resource type (vm, system-container, app-container, agent)",
+ Description: "For get/run: canonical v6 resource type (vm, system-container, app-container, agent)",
Enum: []string{"vm", "system-container", "app-container", "agent"},
},
"resource_id": {
Type: "string",
- Description: "For get: resource identifier (VMID, container name, hostname)",
+ Description: "For get/run: resource identifier (VMID, container name, hostname)",
},
"target_id": {
Type: "string",
- Description: "For get/list: canonical target identifier (agent ID, node ID, or cluster ID)",
+ Description: "For get/run/list: canonical target identifier (agent ID, node ID, or cluster ID)",
},
"type": {
Type: "string",
@@ -57,9 +57,9 @@ func (e *PulseToolExecutor) registerDiscoveryTools() {
return exec.executeDiscovery(ctx, args)
},
Governance: ToolGovernance{
- ActionMode: ToolActionRead,
- ApprovalPolicy: "no approval required",
- Summary: "Reads discovered service paths, ports, and bind mounts for known resources.",
+ ActionMode: ToolActionMixed,
+ ApprovalPolicy: "no approval required; run uses read-only evidence collection and updates the discovery cache",
+ Summary: "Reads or refreshes discovered service paths, ports, and bind mounts for known resources.",
},
})
}
@@ -70,10 +70,12 @@ func (e *PulseToolExecutor) executeDiscovery(ctx context.Context, args map[strin
switch action {
case "get":
return e.executeGetDiscovery(ctx, args)
+ case "run":
+ return e.executeRunDiscovery(ctx, args)
case "list":
return e.executeListDiscoveries(ctx, args)
default:
- return NewErrorResult(fmt.Errorf("unknown action: %s. Use: get, list", action)), nil
+ return NewErrorResult(fmt.Errorf("unknown action: %s. Use: get, run, list", action)), nil
}
}
@@ -227,32 +229,40 @@ func CanonicalDiscoveryTargetID(discovery *ResourceDiscoveryInfo, fallbackTarget
return targetID
}
-func (e *PulseToolExecutor) executeGetDiscovery(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {
+type discoveryResourceRequest struct {
+ resourceType string
+ providerResourceType string
+ resourceID string
+ targetID string
+ cliAccess string
+}
+
+func (e *PulseToolExecutor) normalizeDiscoveryResourceRequest(args map[string]interface{}) (discoveryResourceRequest, CallToolResult, bool) {
if e.discoveryProvider == nil {
- return NewTextResult("Discovery service not available."), nil
+ return discoveryResourceRequest{}, NewTextResult("Discovery service not available."), false
}
resourceTypeRaw, _ := args["resource_type"].(string)
resourceID, _ := args["resource_id"].(string)
targetID, _ := args["target_id"].(string)
if isUnsupportedDiscoveryLegacyResourceTypeToken(resourceTypeRaw) {
- return NewErrorResult(fmt.Errorf("unsupported resource_type %q", strings.TrimSpace(resourceTypeRaw))), nil
+ return discoveryResourceRequest{}, NewErrorResult(fmt.Errorf("unsupported resource_type %q", strings.TrimSpace(resourceTypeRaw))), false
}
resourceType := CanonicalDiscoveryResourceType(resourceTypeRaw)
providerResourceType := DiscoveryProviderResourceType(resourceType)
targetID = strings.TrimSpace(targetID)
if resourceType == "" {
- return NewErrorResult(fmt.Errorf("resource_type is required")), nil
+ return discoveryResourceRequest{}, NewErrorResult(fmt.Errorf("resource_type is required")), false
}
if !isSupportedDiscoveryResourceType(resourceType) {
- return NewErrorResult(fmt.Errorf("unsupported resource_type %q", strings.TrimSpace(resourceTypeRaw))), nil
+ return discoveryResourceRequest{}, NewErrorResult(fmt.Errorf("unsupported resource_type %q", strings.TrimSpace(resourceTypeRaw))), false
}
if resourceID == "" {
- return NewErrorResult(fmt.Errorf("resource_id is required")), nil
+ return discoveryResourceRequest{}, NewErrorResult(fmt.Errorf("resource_id is required")), false
}
if targetID == "" {
- return NewErrorResult(fmt.Errorf("target_id is required - use the node/agent field from search or get_resource results")), nil
+ return discoveryResourceRequest{}, NewErrorResult(fmt.Errorf("target_id is required - use the node/agent field from search or get_resource results")), false
}
// For system-container and VM types, resourceID should be a numeric VMID.
@@ -284,23 +294,35 @@ func (e *PulseToolExecutor) executeGetDiscovery(ctx context.Context, args map[st
}
if !resolved {
- return NewErrorResult(fmt.Errorf("could not resolve resource name '%s' to a VMID on target '%s'", resourceID, targetID)), nil
+ return discoveryResourceRequest{}, NewErrorResult(fmt.Errorf("could not resolve resource name '%s' to a VMID on target '%s'", resourceID, targetID)), false
}
}
}
+ return discoveryResourceRequest{
+ resourceType: resourceType,
+ providerResourceType: providerResourceType,
+ resourceID: resourceID,
+ targetID: targetID,
+ cliAccess: getCLIAccessPattern(resourceType, targetID, resourceID),
+ }, CallToolResult{}, true
+}
+
+func (e *PulseToolExecutor) executeGetDiscovery(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {
+ req, blocked, ok := e.normalizeDiscoveryResourceRequest(args)
+ if !ok {
+ return blocked, nil
+ }
+
// First try to get existing discovery
- discovery, err := e.discoveryProvider.GetDiscoveryByResource(providerResourceType, targetID, resourceID)
+ discovery, err := e.discoveryProvider.GetDiscoveryByResource(req.providerResourceType, req.targetID, req.resourceID)
if err != nil {
return NewErrorResult(fmt.Errorf("failed to get discovery: %w", err)), nil
}
- // Compute CLI access pattern (always useful, even if discovery fails)
- cliAccess := getCLIAccessPattern(resourceType, targetID, resourceID)
-
// If no discovery exists, trigger one
if discovery == nil {
- discovery, err = e.discoveryProvider.TriggerDiscovery(ctx, providerResourceType, targetID, resourceID)
+ discovery, err = e.discoveryProvider.TriggerDiscovery(ctx, req.providerResourceType, req.targetID, req.resourceID, false)
if err != nil {
// Distinguish transient errors (rate limits, timeouts) from genuine not-found.
// Transient errors must surface as IsError so the model stops retrying.
@@ -317,10 +339,10 @@ func (e *PulseToolExecutor) executeGetDiscovery(ctx context.Context, args map[st
// Genuine failure (e.g. resource doesn't exist) — keep existing behavior
return NewJSONResult(map[string]interface{}{
"found": false,
- "resource_type": resourceType,
- "resource_id": resourceID,
- "target_id": targetID,
- "cli_access": cliAccess,
+ "resource_type": req.resourceType,
+ "resource_id": req.resourceID,
+ "target_id": req.targetID,
+ "cli_access": req.cliAccess,
"message": fmt.Sprintf("Discovery failed: %v", err),
"hint": "Command-capable investigation may still be possible. Common log locations include /var/log/.",
}), nil
@@ -331,19 +353,70 @@ func (e *PulseToolExecutor) executeGetDiscovery(ctx context.Context, args map[st
// No discovery but provide cli_access for manual investigation
return NewJSONResult(map[string]interface{}{
"found": false,
- "resource_type": resourceType,
- "resource_id": resourceID,
- "target_id": targetID,
- "cli_access": cliAccess,
+ "resource_type": req.resourceType,
+ "resource_id": req.resourceID,
+ "target_id": req.targetID,
+ "cli_access": req.cliAccess,
"message": "Discovery returned no data. The resource may not be accessible.",
"hint": "Command-capable investigation may still be possible. Common next evidence includes /var/log/ entries or running-process state.",
}), nil
}
+ return NewJSONResult(buildDiscoveryToolResponse(req, discovery)), nil
+}
+
+func (e *PulseToolExecutor) executeRunDiscovery(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {
+ req, blocked, ok := e.normalizeDiscoveryResourceRequest(args)
+ if !ok {
+ return blocked, nil
+ }
+
+ discovery, err := e.discoveryProvider.TriggerDiscovery(ctx, req.providerResourceType, req.targetID, req.resourceID, true)
+ if err != nil {
+ if isTransientError(err) {
+ return CallToolResult{
+ Content: []Content{{
+ Type: "text",
+ Text: fmt.Sprintf("Discovery run temporarily unavailable: %v. Immediate retry is unlikely to add information; command-capable investigation or another approach may be needed.", err),
+ }},
+ IsError: true,
+ }, nil
+ }
+ return NewJSONResult(map[string]interface{}{
+ "found": false,
+ "refreshed": false,
+ "resource_type": req.resourceType,
+ "resource_id": req.resourceID,
+ "target_id": req.targetID,
+ "cli_access": req.cliAccess,
+ "message": fmt.Sprintf("Discovery run failed: %v", err),
+ "hint": "Command-capable investigation may still be possible. Common next evidence includes /var/log/ entries or running-process state.",
+ }), nil
+ }
+
+ if discovery == nil {
+ return NewJSONResult(map[string]interface{}{
+ "found": false,
+ "refreshed": false,
+ "resource_type": req.resourceType,
+ "resource_id": req.resourceID,
+ "target_id": req.targetID,
+ "cli_access": req.cliAccess,
+ "message": "Discovery run returned no data. The resource may not be accessible.",
+ "hint": "Command-capable investigation may still be possible. Common next evidence includes /var/log/ entries or running-process state.",
+ }), nil
+ }
+
+ response := buildDiscoveryToolResponse(req, discovery)
+ response["refreshed"] = true
+ return NewJSONResult(response), nil
+}
+
+func buildDiscoveryToolResponse(req discoveryResourceRequest, discovery *ResourceDiscoveryInfo) map[string]interface{} {
// Use fallback cli_access if discovery didn't provide one
responseCLIAccess := discovery.CLIAccess
if responseCLIAccess == "" {
- responseCLIAccess = cliAccess
+ responseCLIAccess = req.cliAccess
}
// Use fallback paths for known services if discovery didn't find specific ones
@@ -364,12 +437,12 @@ func (e *PulseToolExecutor) executeGetDiscovery(ctx context.Context, args map[st
}
}
- discoveryTargetID := CanonicalDiscoveryTargetID(discovery, targetID)
+ discoveryTargetID := CanonicalDiscoveryTargetID(discovery, req.targetID)
// Return the discovery information
responseResourceType := CanonicalDiscoveryResourceType(discovery.ResourceType)
if responseResourceType == "" {
- responseResourceType = resourceType
+ responseResourceType = req.resourceType
}
response := map[string]interface{}{
"found": true,
@@ -438,7 +511,7 @@ func (e *PulseToolExecutor) executeGetDiscovery(ctx context.Context, args map[st
response["ports"] = ports
}
- return NewJSONResult(response), nil
+ return response
}
// isTransientError checks whether an error is a transient API/infrastructure error
diff --git a/internal/ai/tools/tools_discovery_test.go b/internal/ai/tools/tools_discovery_test.go
index 61131b9481..27698ac979 100644
--- a/internal/ai/tools/tools_discovery_test.go
+++ b/internal/ai/tools/tools_discovery_test.go
@@ -20,6 +20,13 @@ type stubDiscoveryProvider struct {
lastListTargetID string
listResp []*ResourceDiscoveryInfo
listErr error
+
+ lastTriggerResourceType string
+ lastTriggerTargetID string
+ lastTriggerResourceID string
+ lastTriggerForce bool
+ triggerResp *ResourceDiscoveryInfo
+ triggerErr error
}
func (s *stubDiscoveryProvider) GetDiscovery(_ string) (*ResourceDiscoveryInfo, error) {
@@ -51,8 +58,12 @@ func (s *stubDiscoveryProvider) FormatForAIContext(_ []*ResourceDiscoveryInfo) s
return ""
}
-func (s *stubDiscoveryProvider) TriggerDiscovery(_ context.Context, _, _, _ string) (*ResourceDiscoveryInfo, error) {
- return nil, nil
+func (s *stubDiscoveryProvider) TriggerDiscovery(_ context.Context, resourceType, targetID, resourceID string, force bool) (*ResourceDiscoveryInfo, error) {
+ s.lastTriggerResourceType = resourceType
+ s.lastTriggerTargetID = targetID
+ s.lastTriggerResourceID = resourceID
+ s.lastTriggerForce = force
+ return s.triggerResp, s.triggerErr
}
func TestIsTransientError(t *testing.T) {
@@ -135,6 +146,26 @@ func TestExecuteGetDiscovery_UsesTargetID(t *testing.T) {
assert.NotContains(t, payload, "host_id")
}
+func TestPulseDiscoveryToolSchemaIncludesRunAction(t *testing.T) {
+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: &stubDiscoveryProvider{}})
+ tools := exec.ListTools()
+
+ var discoveryTool *Tool
+ for i := range tools {
+ if tools[i].Name == "pulse_discovery" {
+ discoveryTool = &tools[i]
+ break
+ }
+ }
+ if discoveryTool == nil {
+ t.Fatalf("expected pulse_discovery tool")
+ }
+
+ actionSchema := discoveryTool.InputSchema.Properties["action"]
+ assert.Contains(t, actionSchema.Enum, "run")
+ assert.Contains(t, discoveryTool.Description, `action="run" forces a fresh discovery run`)
+}
+
func TestCanonicalDiscoveryResourceType(t *testing.T) {
tests := []struct {
in string
@@ -325,6 +356,38 @@ func TestExecuteGetDiscovery_CanonicalAppContainerUsesDockerProviderType(t *test
assert.Equal(t, "app-container", payload["resource_type"])
}
+func TestExecuteRunDiscovery_ForcesFreshDiscovery(t *testing.T) {
+ provider := &stubDiscoveryProvider{
+ triggerResp: &ResourceDiscoveryInfo{
+ ID: "vm:node1:101",
+ ResourceType: "vm",
+ ResourceID: "101",
+ TargetID: "node1",
+ Hostname: "vm-101",
+ ServiceName: "PostgreSQL",
+ },
+ }
+ exec := NewPulseToolExecutor(ExecutorConfig{DiscoveryProvider: provider})
+
+ result, err := exec.executeDiscovery(context.Background(), map[string]interface{}{
+ "action": "run",
+ "resource_type": "vm",
+ "resource_id": "101",
+ "target_id": "node1",
+ })
+ assert.NoError(t, err)
+ assert.False(t, result.IsError)
+ assert.Equal(t, "vm", provider.lastTriggerResourceType)
+ assert.Equal(t, "node1", provider.lastTriggerTargetID)
+ assert.Equal(t, "101", provider.lastTriggerResourceID)
+ assert.True(t, provider.lastTriggerForce)
+
+ var payload map[string]interface{}
+ assert.NoError(t, json.Unmarshal([]byte(result.Content[0].Text), &payload))
+ assert.Equal(t, true, payload["refreshed"])
+ assert.Equal(t, "PostgreSQL", payload["service_name"])
+}
+
func TestExecuteListDiscoveries_FiltersByTargetID(t *testing.T) {
provider := &stubDiscoveryProvider{
listResp: []*ResourceDiscoveryInfo{
diff --git a/internal/servicediscovery/service.go b/internal/servicediscovery/service.go
index 7811d0c03e..46a025743d 100644
--- a/internal/servicediscovery/service.go
+++ b/internal/servicediscovery/service.go
@@ -1656,9 +1656,10 @@ func (s *Service) DiscoverResource(ctx context.Context, req DiscoveryRequest) (*
// Broadcast progress: AI analysis starting
s.broadcastProgress(&DiscoveryProgress{
- ResourceID: resourceID,
- Status: DiscoveryStatusRunning,
- CurrentStep: "Analyzing with Pulse Assistant...",
+ ResourceID: resourceID,
+ Status: DiscoveryStatusRunning,
+ CurrentStep: "Analyzing discovery evidence with the selected model...",
+ PercentComplete: 75,
})
analyzeCtx, cancel := context.WithTimeout(ctx, s.aiAnalysisTimeout)
diff --git a/internal/servicediscovery/service_test.go b/internal/servicediscovery/service_test.go
index 062b0e75ec..1d740a57f6 100644
--- a/internal/servicediscovery/service_test.go
+++ b/internal/servicediscovery/service_test.go
@@ -50,6 +50,29 @@ func (b *blockingAnalyzer) AnalyzeForDiscovery(ctx context.Context, prompt strin
return "", ctx.Err()
}
+type captureProgressHub struct {
+ mu sync.Mutex
+ progress []*DiscoveryProgress
+}
+
+func (h *captureProgressHub) BroadcastDiscoveryProgress(progress *DiscoveryProgress) {
+ if progress == nil {
+ return
+ }
+ progressCopy := *progress
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ h.progress = append(h.progress, &progressCopy)
+}
+
+func (h *captureProgressHub) snapshots() []*DiscoveryProgress {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ out := make([]*DiscoveryProgress, len(h.progress))
+ copy(out, h.progress)
+ return out
+}
+
func TestFilterSensitiveLabels(t *testing.T) {
tests := []struct {
name string
@@ -211,6 +234,52 @@ func TestFilterSensitiveLabels(t *testing.T) {
}
}
+func TestService_DiscoverResource_ProgressDescribesModelAnalysisNotAssistantChat(t *testing.T) {
+ store, err := NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewStore error: %v", err)
+ }
+ store.crypto = nil
+
+ service := NewService(store, nil, DefaultConfig())
+ service.SetAIAnalyzer(&stubAnalyzer{
+ response: `{"service_type":"postgresql","service_name":"PostgreSQL","service_version":"16","category":"database","cli_access":"ssh root@host","facts":[],"config_paths":[],"data_paths":[],"ports":[],"confidence":0.9,"reasoning":"metadata-only identification"}`,
+ })
+ hub := &captureProgressHub{}
+ service.SetWSHub(hub)
+
+ _, err = service.DiscoverResource(context.Background(), DiscoveryRequest{
+ ResourceType: ResourceTypeAgent,
+ TargetID: "agent-1",
+ ResourceID: "agent-1",
+ Hostname: "agent-1",
+ Force: true,
+ })
+ if err != nil {
+ t.Fatalf("DiscoverResource error: %v", err)
+ }
+
+ var analysisProgress *DiscoveryProgress
+ for _, progress := range hub.snapshots() {
+ if progress.Status == DiscoveryStatusRunning {
+ analysisProgress = progress
+ break
+ }
+ }
+ if analysisProgress == nil {
+ t.Fatalf("expected running analysis progress")
+ }
+ if strings.Contains(analysisProgress.CurrentStep, "Pulse Assistant") {
+ t.Fatalf("progress step must not imply a live Assistant chat, got %q", analysisProgress.CurrentStep)
+ }
+ if analysisProgress.CurrentStep != "Analyzing discovery evidence with the selected model..." {
+ t.Fatalf("unexpected progress step: %q", analysisProgress.CurrentStep)
+ }
+ if analysisProgress.PercentComplete != 75 {
+ t.Fatalf("expected analysis progress at 75%%, got %v", analysisProgress.PercentComplete)
+ }
+}
+
// readStateFromSnapshot builds a ReadState backed by a ResourceRegistry
// from a local servicediscovery StateSnapshot. This lets tests populate
// state using the familiar local types while exercising the ReadState path.
diff --git a/internal/servicediscovery/tools_adapter.go b/internal/servicediscovery/tools_adapter.go
index 8447dabcc5..87d2715787 100644
--- a/internal/servicediscovery/tools_adapter.go
+++ b/internal/servicediscovery/tools_adapter.go
@@ -83,12 +83,12 @@ func (a *ToolsAdapter) FormatForAIContext(sourceData []tools.DiscoverySourceData
}
// TriggerDiscovery implements tools.DiscoverySource - initiates discovery for a resource
-func (a *ToolsAdapter) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string) (tools.DiscoverySourceData, error) {
+func (a *ToolsAdapter) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, force bool) (tools.DiscoverySourceData, error) {
req := DiscoveryRequest{
ResourceType: ResourceType(resourceType),
TargetID: targetID,
ResourceID: resourceID,
- Force: false, // Don't force if recently discovered
+ Force: force,
}
discovery, err := a.service.DiscoverResource(ctx, req)
diff --git a/internal/servicediscovery/tools_adapter_test.go b/internal/servicediscovery/tools_adapter_test.go
index 94eb3e901e..50288f90b1 100644
--- a/internal/servicediscovery/tools_adapter_test.go
+++ b/internal/servicediscovery/tools_adapter_test.go
@@ -226,7 +226,7 @@ func TestToolsAdapter_TriggerDiscovery(t *testing.T) {
d1 := &ResourceDiscovery{ID: id, ResourceType: "docker", TargetID: "h1", ResourceID: "r1", DiscoveredAt: time.Now()}
require.NoError(t, store.Save(d1))
- result, err := adapter.TriggerDiscovery(context.Background(), "docker", "h1", "r1")
+ result, err := adapter.TriggerDiscovery(context.Background(), "docker", "h1", "r1", false)
require.NoError(t, err)
assert.Equal(t, id, result.ID)
})