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.

Refuse ambiguous Assistant action targets across installations

pulse-triage[bot]e22450e72edb
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 6ac4fb49d5..db7b8026ad 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -25,6 +25,25 @@ that same result. Successful reads retain their content and execution provenance
## Purpose
+### Assistant action plans do not guess an installation from session placement
+
+An explicit current canonical resource ID takes precedence over stale session
+aliases in `pulse_control`. Without one, session-to-inventory binding must have
+one canonical match: repeated VMID/node pairs, container-ID/host pairs, agent
+names or conflicting canonical aliases cannot select the first listed resource.
+Ambiguity returns the canonical alternatives with the tool error bit before
+calling the action planner, including for an older session-only reference.
+The advertised-action projection omits these ambiguous targets too.
+
+Unique placement, canonical aliases and inventory-only lookup remain usable
+without another discovery step. Inventory-only canonical lookup retains session
+registration. Capability checks, approval policy and execution remain with the
+existing action lifecycle; these source controls establish no native action or
+cross-installation monitoring recovery.
+`control_target_identity_test.go` covers both inventory orders, all four control
+resource kinds, conflicting aliases, planning refusal, stale-session canonical
+override, unique placement and session continuity.
+
### Guest-config tools require an unambiguous resource identity
The existing VM/system-container configuration tool selects an exact canonical
diff --git a/internal/ai/tools/control_target_identity_test.go b/internal/ai/tools/control_target_identity_test.go
new file mode 100644
index 0000000000..35d37b8889
--- /dev/null
+++ b/internal/ai/tools/control_target_identity_test.go
@@ -0,0 +1,200 @@
+package tools
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// VMIDs and node/host names are scoped to an installation, not globally
+// unique. An older session without a canonical alias cannot choose whichever
+// matching installation happens to be listed first.
+func TestCanonicalResourceForResolvedRefusesCrossInstallationAmbiguity(t *testing.T) {
+ for _, kind := range []string{"vm", "system-container", "app-container", "agent"} {
+ t.Run(kind, func(t *testing.T) {
+ home := controlIdentityResource(kind, "home")
+ remote := controlIdentityResource(kind, "remote")
+ resolved := controlIdentitySession(kind)
+ for _, resources := range [][]unifiedresources.Resource{{home, remote}, {remote, home}} {
+ provider := &stubUnifiedResourceProvider{resources: resources}
+ if resource, ok := canonicalResourceForResolved(provider, resolved); ok {
+ t.Fatalf("ambiguous %s identity selected %s", kind, resource.ID)
+ }
+ }
+ })
+ }
+}
+
+func TestCanonicalResourceForResolvedKeepsUniqueIdentityAndCanonicalAliases(t *testing.T) {
+ for _, kind := range []string{"vm", "system-container", "app-container", "agent"} {
+ t.Run(kind, func(t *testing.T) {
+ home := controlIdentityResource(kind, "home")
+ remote := controlIdentityResource(kind, "remote")
+ resolved := controlIdentitySession(kind)
+ assertID := func(provider *stubUnifiedResourceProvider, want string) {
+ t.Helper()
+ resource, ok := canonicalResourceForResolved(provider, resolved)
+ if !ok || resource.ID != want {
+ t.Fatalf("resolved %s identity = %q (ok=%t), want %q", kind, resource.ID, ok, want)
+ }
+ }
+ assertID(&stubUnifiedResourceProvider{resources: []unifiedresources.Resource{home}}, home.ID)
+ resolved.aliases = append(resolved.aliases, remote.ID)
+ assertID(&stubUnifiedResourceProvider{resources: []unifiedresources.Resource{home, remote}}, remote.ID)
+ resolved.aliases = []string{"shared-name", remote.ID, remote.ID}
+ assertID(&stubUnifiedResourceProvider{resources: []unifiedresources.Resource{remote, home}}, remote.ID)
+ })
+ }
+}
+
+func TestCanonicalResourceForResolvedKeepsPlacementDisambiguation(t *testing.T) {
+ for _, kind := range []string{"vm", "system-container", "app-container"} {
+ t.Run(kind, func(t *testing.T) {
+ home := controlIdentityResource(kind, "home")
+ remote := controlIdentityResource(kind, "remote")
+ if remote.Proxmox != nil {
+ remote.Proxmox.NodeName = "pve2"
+ } else {
+ remote.ParentName = "other-host"
+ }
+ provider := &stubUnifiedResourceProvider{resources: []unifiedresources.Resource{remote, home}}
+ resource, ok := canonicalResourceForResolved(provider, controlIdentitySession(kind))
+ if !ok || resource.ID != home.ID {
+ t.Fatalf("unique placement resolved %q (ok=%t), want %q", resource.ID, ok, home.ID)
+ }
+ })
+ }
+}
+
+func TestCanonicalResourceForResolvedRefusesConflictingCanonicalAliases(t *testing.T) {
+ home := controlIdentityResource("vm", "home")
+ remote := controlIdentityResource("vm", "remote")
+ provider := &stubUnifiedResourceProvider{resources: []unifiedresources.Resource{home, remote}}
+ resolved := controlIdentitySession("vm")
+ for _, aliases := range [][]string{{home.ID, remote.ID}, {remote.ID, home.ID}} {
+ resolved.aliases = aliases
+ if resource, ok := canonicalResourceForResolved(provider, resolved); ok {
+ t.Fatalf("conflicting canonical aliases selected %s", resource.ID)
+ }
+ }
+}
+
+func TestExecuteControlResourceRefusesAmbiguousSessionPlacementBeforePlanning(t *testing.T) {
+ for _, kind := range []string{"vm", "system-container", "app-container", "agent"} {
+ for _, ref := range []string{"shared-name", "old-session-target"} {
+ t.Run(kind+"/"+ref, func(t *testing.T) {
+ home := controlIdentityResource(kind, "home")
+ remote := controlIdentityResource(kind, "remote")
+ provider := &stubUnifiedResourceProvider{resources: []unifiedresources.Resource{home, remote}}
+ resolved := newControlTestResolvedContext()
+ resolved.aliases[ref] = controlIdentitySession(kind)
+ plans := &recordedPlan{}
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ ControlLevel: ControlLevelControlled,
+ TypedActionPlanner: plans.planner(nil),
+ })
+ executor.SetResolvedContext(resolved)
+ result, err := executor.executeControl(context.Background(), map[string]interface{}{
+ "type": "resource", "resource_id": ref, "action": "reboot",
+ })
+ if err != nil || !result.IsError || len(plans.requests) != 0 {
+ t.Fatalf("ambiguous session reached planning: err=%v isError=%t requests=%+v", err, result.IsError, plans.requests)
+ }
+ text := result.Content[0].Text
+ if !strings.Contains(text, home.ID) || !strings.Contains(text, remote.ID) {
+ t.Fatalf("ambiguity did not return both canonical alternatives: %s", text)
+ }
+ })
+ }
+ }
+}
+
+func TestExecuteControlResourceExplicitCanonicalIDBeatsStaleSessionAlias(t *testing.T) {
+ home := controlIdentityResource("vm", "home")
+ remote := controlIdentityResource("vm", "remote")
+ provider := &stubUnifiedResourceProvider{resources: []unifiedresources.Resource{home, remote}}
+ resolved := newControlTestResolvedContext()
+ stale := controlIdentitySession("vm")
+ stale.aliases = []string{home.ID}
+ resolved.aliases[remote.ID] = stale
+ plans := &recordedPlan{}
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ ControlLevel: ControlLevelControlled,
+ TypedActionPlanner: plans.planner(nil),
+ })
+ executor.SetResolvedContext(resolved)
+ result, err := executor.executeControl(context.Background(), map[string]interface{}{
+ "type": "resource", "resource_id": remote.ID, "action": "reboot",
+ })
+ if err != nil || result.IsError || len(plans.requests) != 1 || plans.requests[0].ResourceID != remote.ID {
+ t.Fatalf("explicit canonical identity was replaced by session history: err=%v isError=%t requests=%+v", err, result.IsError, plans.requests)
+ }
+ payload := decodeControlPayload(t, result)
+ if payload["execution_requested"] != false || payload["requires_approval"] != true {
+ t.Fatalf("canonical selection changed approval/execution boundaries: %+v", payload)
+ }
+}
+
+func TestExecuteControlResourceCanonicalLookupKeepsSessionRegistration(t *testing.T) {
+ vm := controlTestProxmoxVM("win-unique", 101, "pve", true)
+ provider := &stubUnifiedResourceProvider{resources: []unifiedresources.Resource{vm}}
+ resolved := newControlTestResolvedContext()
+ plans := &recordedPlan{}
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ ControlLevel: ControlLevelControlled,
+ TypedActionPlanner: plans.planner(nil),
+ })
+ executor.SetResolvedContext(resolved)
+ result, err := executor.executeControl(context.Background(), map[string]interface{}{
+ "type": "resource", "resource_id": vm.ID, "action": "reboot",
+ })
+ if err != nil || result.IsError || len(plans.requests) != 1 || plans.requests[0].ResourceID != vm.ID {
+ t.Fatalf("unique canonical identity failed to plan: err=%v isError=%t requests=%+v", err, result.IsError, plans.requests)
+ }
+ if targets := executor.SessionTargetsAdvertisingAction("reboot"); len(targets) != 1 || targets[0].CanonicalID != vm.ID {
+ t.Fatalf("canonical lookup lost session continuity: %+v", targets)
+ }
+}
+
+func TestSessionTargetsAdvertisingActionOmitsAmbiguousPlacement(t *testing.T) {
+ home := controlIdentityResource("vm", "home")
+ remote := controlIdentityResource("vm", "remote")
+ provider := &stubUnifiedResourceProvider{resources: []unifiedresources.Resource{home, remote}}
+ resolved := newControlTestResolvedContext()
+ resolved.resources["old-session-target"] = controlIdentitySession("vm")
+ executor := NewPulseToolExecutor(ExecutorConfig{UnifiedResourceProvider: provider})
+ executor.SetResolvedContext(resolved)
+ if targets := executor.SessionTargetsAdvertisingAction("reboot"); len(targets) != 0 {
+ t.Fatalf("ambiguous session advertised a guessed action target: %+v", targets)
+ }
+}
+
+func controlIdentitySession(kind string) *mockResource {
+ return &mockResource{
+ resourceID: "old-session-target", resourceType: kind, kind: kind,
+ vmID: 100, node: "pve1", targetHost: "same-host", providerUID: "same-container-id",
+ aliases: []string{"shared-name"},
+ }
+}
+
+func controlIdentityResource(kind, instance string) unifiedresources.Resource {
+ resourceType, _ := controlResourceTypeForKind(kind)
+ resource := unifiedresources.Resource{
+ ID: instance + "-" + kind, Type: resourceType, Name: "shared-name",
+ Status: unifiedresources.StatusOnline,
+ Capabilities: []unifiedresources.ResourceCapability{{Name: "reboot"}},
+ }
+ switch kind {
+ case "vm", "system-container":
+ resource.Proxmox = &unifiedresources.ProxmoxData{Instance: instance, NodeName: "pve1", VMID: 100}
+ case "app-container":
+ resource.ParentName = "same-host"
+ resource.Docker = &unifiedresources.DockerData{ContainerID: "same-container-id", HostSourceID: instance + "-machine"}
+ }
+ return resource
+}
diff --git a/internal/ai/tools/control_targets.go b/internal/ai/tools/control_targets.go
index 7d0d0fe8a1..6c1de6153f 100644
--- a/internal/ai/tools/control_targets.go
+++ b/internal/ai/tools/control_targets.go
@@ -133,59 +133,78 @@ func controlResourceTypeForKind(kind string) (unifiedresources.ResourceType, boo
}
// canonicalResourceForResolved maps a session-resolved resource back to its
-// unified-inventory record. It matches on the canonical ID that query tools
-// register as an alias, then on provider identity (Proxmox VMID on the same
-// node, app-container provider ID on the same host, agent name). It never
-// matches on host names, IP addresses, or tags, which the alias list also
-// carries: those are lookup conveniences, not identity, and a write must not
-// bind to a neighbour by accident.
+// unified-inventory record only when its identity is unambiguous. Provider
+// IDs and node/host names can recur across independent installations.
func canonicalResourceForResolved(provider UnifiedResourceProvider, resolved ResolvedResourceInfo) (unifiedresources.Resource, bool) {
+ candidates := canonicalResourcesForResolved(provider, resolved)
+ if len(candidates) == 1 {
+ return candidates[0], true
+ }
+ return unifiedresources.Resource{}, false
+}
+
+// canonicalResourcesForResolved prefers canonical IDs over placement/name
+// hints, but collects every match at each tier. Conflicting canonical aliases
+// and ambiguous legacy placement must not be resolved by listing order.
+func canonicalResourcesForResolved(provider UnifiedResourceProvider, resolved ResolvedResourceInfo) []unifiedresources.Resource {
if provider == nil || resolved == nil {
- return unifiedresources.Resource{}, false
+ return nil
}
resourceType, ok := controlResourceTypeForKind(firstNonEmptyString(resolved.GetKind(), resolved.GetResourceType()))
if !ok {
- return unifiedresources.Resource{}, false
+ return nil
}
candidates := provider.GetByType(resourceType)
- for _, alias := range resolved.GetAliases() {
+ var matches []unifiedresources.Resource
+ seen := make(map[string]bool)
+ addMatch := func(resource unifiedresources.Resource) {
+ id := strings.TrimSpace(resource.ID)
+ if id != "" && !seen[id] {
+ seen[id] = true
+ matches = append(matches, resource)
+ }
+ }
+ for _, alias := range append([]string{resolved.GetResourceID()}, resolved.GetAliases()...) {
alias = strings.TrimSpace(alias)
if alias == "" {
continue
}
for _, resource := range candidates {
if strings.EqualFold(strings.TrimSpace(resource.ID), alias) {
- return resource, true
+ addMatch(resource)
}
}
}
+ if len(matches) > 0 {
+ return matches
+ }
switch resourceType {
case unifiedresources.ResourceTypeVM, unifiedresources.ResourceTypeSystemContainer:
vmid := resolved.GetVMID()
node := strings.TrimSpace(resolved.GetNode())
if vmid <= 0 {
- return unifiedresources.Resource{}, false
+ return nil
}
for _, resource := range candidates {
if resource.Proxmox == nil || resource.Proxmox.VMID != vmid {
continue
}
if node == "" || strings.EqualFold(strings.TrimSpace(resource.Proxmox.NodeName), node) {
- return resource, true
+ addMatch(resource)
}
}
case unifiedresources.ResourceTypeAppContainer:
providerUID := strings.TrimSpace(resolved.GetProviderUID())
host := strings.TrimSpace(resolved.GetTargetHost())
if providerUID == "" {
- return unifiedresources.Resource{}, false
+ return nil
}
for _, resource := range candidates {
if !strings.EqualFold(strings.TrimSpace(appContainerProviderID(resource)), providerUID) {
continue
}
if host == "" || strings.EqualFold(strings.TrimSpace(canonicalAppContainerHost(resource)), host) {
- return resource, true
+ addMatch(resource)
}
}
case unifiedresources.ResourceTypeAgent:
@@ -193,12 +212,12 @@ func canonicalResourceForResolved(provider UnifiedResourceProvider, resolved Res
name := strings.TrimSpace(resourceDisplayName(resource))
for _, alias := range resolved.GetAliases() {
if name != "" && strings.EqualFold(name, strings.TrimSpace(alias)) {
- return resource, true
+ addMatch(resource)
}
}
}
}
- return unifiedresources.Resource{}, false
+ return matches
}
// canonicalControlCandidates resolves a model-supplied reference against the
@@ -226,12 +245,11 @@ func canonicalControlCandidates(provider UnifiedResourceProvider, ref string) []
}
// resolveControlTarget binds a pulse_control reference to a canonical
-// resource. Session context is consulted first because it is what the model
-// just saw, but a reference that is absent from the session and resolves
-// uniquely in the unified inventory is registered and accepted: the inventory
-// is Pulse's own discovery, so demanding a second in-session "discovery" step
-// is an ordering accident, not a safety property. Capability, approval, and
-// execution stay with the shared action lifecycle.
+// resource. An explicit canonical ID wins over stale session aliases. Other
+// session references must have unambiguous current identity. A reference absent
+// from the session but unique in inventory is still accepted without a second
+// discovery step. Capability, approval and execution stay with the shared
+// action lifecycle.
func (e *PulseToolExecutor) resolveControlTarget(ref, action string) (controlTarget, *CallToolResult) {
target := controlTarget{}
if e.resolvedContext != nil {
@@ -243,47 +261,46 @@ func (e *PulseToolExecutor) resolveControlTarget(ref, action string) (controlTar
}
if e.unifiedResourceProvider != nil {
- if target.session != nil {
- if resource, ok := canonicalResourceForResolved(e.unifiedResourceProvider, target.session); ok {
+ inventoryCandidates := canonicalControlCandidates(e.unifiedResourceProvider, ref)
+ if len(inventoryCandidates) == 1 && strings.EqualFold(strings.TrimSpace(inventoryCandidates[0].ID), strings.TrimSpace(ref)) {
+ resource := inventoryCandidates[0]
+ target.canonical = &resource
+ }
+ if target.canonical == nil && target.session != nil {
+ candidates := canonicalResourcesForResolved(e.unifiedResourceProvider, target.session)
+ switch len(candidates) {
+ case 0:
+ case 1:
+ resource := candidates[0]
target.canonical = &resource
+ default:
+ result := ambiguousControlTargetResult(ref, action, candidates)
+ return target, &result
}
}
if target.canonical == nil {
- candidates := canonicalControlCandidates(e.unifiedResourceProvider, ref)
+ candidates := inventoryCandidates
switch len(candidates) {
case 0:
case 1:
resource := candidates[0]
target.canonical = &resource
- if target.session == nil && e.resolvedContext != nil {
- if reg, ok := CanonicalHandoffResourceRegistration(e.unifiedResourceProvider, resource.ID, "", string(unifiedresources.ContractResourceType(resource)), ""); ok {
- e.registerResolvedResourceWithExplicitAccess(reg)
- if res, ok := e.resolvedContext.GetResolvedResourceByID(resource.ID); ok && res != nil {
- target.session = res
- } else if res, ok := e.resolvedContext.GetResolvedResourceByAlias(reg.Name); ok && res != nil {
- target.session = res
- }
- }
- }
default:
- ids := make([]string, 0, len(candidates))
- for _, candidate := range candidates {
- ids = append(ids, fmt.Sprintf("%s (%s)", candidate.ID, unifiedresources.ContractResourceType(candidate)))
- }
- sort.Strings(ids)
- result := NewToolResponseResult(NewToolBlockedError(
- agentcapabilities.ErrCodeInvalidInput,
- fmt.Sprintf("%d canonical resources are named %q; call pulse_control again with one of these canonical resource ids: %s.", len(candidates), ref, strings.Join(ids, ", ")),
- map[string]interface{}{
- "resource_id": ref,
- "action": action,
- "candidates": ids,
- "policy_boundary": "Ambiguous target reference. Retry with a canonical resource id from this list; this is a lookup detail, not a missing prerequisite.",
- },
- ))
+ result := ambiguousControlTargetResult(ref, action, candidates)
return target, &result
}
}
+ if target.canonical != nil && target.session == nil && e.resolvedContext != nil {
+ resource := *target.canonical
+ if reg, ok := CanonicalHandoffResourceRegistration(e.unifiedResourceProvider, resource.ID, "", string(unifiedresources.ContractResourceType(resource)), ""); ok {
+ e.registerResolvedResourceWithExplicitAccess(reg)
+ if res, ok := e.resolvedContext.GetResolvedResourceByID(resource.ID); ok && res != nil {
+ target.session = res
+ } else if res, ok := e.resolvedContext.GetResolvedResourceByAlias(reg.Name); ok && res != nil {
+ target.session = res
+ }
+ }
+ }
}
if target.session == nil && target.canonical == nil {
@@ -314,6 +331,24 @@ func (e *PulseToolExecutor) resolveControlTarget(ref, action string) (controlTar
return target, nil
}
+func ambiguousControlTargetResult(ref, action string, candidates []unifiedresources.Resource) CallToolResult {
+ ids := make([]string, 0, len(candidates))
+ for _, candidate := range candidates {
+ ids = append(ids, fmt.Sprintf("%s (%s)", candidate.ID, unifiedresources.ContractResourceType(candidate)))
+ }
+ sort.Strings(ids)
+ return NewToolResponseResult(NewToolBlockedError(
+ agentcapabilities.ErrCodeInvalidInput,
+ fmt.Sprintf("%d canonical resources match %q; call pulse_control again with one of these canonical resource ids: %s.", len(candidates), ref, strings.Join(ids, ", ")),
+ map[string]interface{}{
+ "resource_id": ref,
+ "action": action,
+ "candidates": ids,
+ "policy_boundary": "Ambiguous target reference. Retry with a canonical resource id from this list; this is a lookup detail, not a missing prerequisite.",
+ },
+ ))
+}
+
// controlPlanFailureResult turns a planning error into tool evidence the model
// can report faithfully. A capability the resource does not advertise is a
// real boundary and is described with the resource's current capability list;