Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Preserve canonical resource ownership in Assistant
rcourtman88338e9a7c7b
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 219bba7b90..07523d6c53 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -6697,21 +6697,24 @@ the summary layout locally.The chat prefetch path now also calls the shared governed-summary predicatedirectly at each mention site, so it no longer carries a local wrapper aroundthe canonical policy decision or a separate mention-summary trim helper.-Structured mention resolution also uses the shared AI tools discovery-canonicalization helpers now, so chat prefetch and discovery responses agree-on resource-type and target-ID formatting instead of maintaining chat-local-copies.+Structured mentions and command routing use the shared unified-resource+reference resolver. An explicit ID selects one owned record for current name,+type, policy and native execution coordinates. Client labels, node hints and+unscoped provider IDs cannot replace an unknown or ambiguous selection.The chat mention picker now also carries the canonical preferred resourcelabel as `label` through the structured mention payload, and the insertionpath uses that same label for prompt text and cursor placement, so mentionsearch, selection, and submission do not depend on a raw `displayName` fieldfork.-Structured `app-container` mentions must now use canonical unified-resource-identity (`app-container:<host>:<provider_uid>`) instead of a Docker-transport-ID. Frontend mention pickers should emit that canonical ID for every-app-container, including API-backed platforms such as TrueNAS, while backend-structured-mention resolution may continue to accept legacy `docker:...`-mentions only as a compatibility path.+All mention kinds carry the registry-issued ID from /api/resources unchanged.+The ID's spelling is not an execution contract. Bounded legacy mention and+session-registration formats remain readable only when they identify a unique+current owner. ResolvedContext stores records by that ID and indexes only+unambiguous names and aliases, including after JSON reload and pinned clearing.+Native provider IDs remain executor coordinates. Session registration and+explicit-access marking share ResourceRegistration.ResolvedID rather than+rebuilding identity independently. Recent context omits unresolved owners and+continues to withhold governed identifiers.Compatibility-only top-level TrueNAS mention types must also collapse to thecanonical `agent` host type at that same handler boundary, so the AI runtimedoes not carry a parallel raw `truenas` mention contract once transport inputdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex a581db55e8..865672f046 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -7631,8 +7631,11 @@ structured mention payloads for canonical `agent`, `vm`, `storage`, andso VMware-backed reads stay on `/api/ai/*` and `/api/resources*` instead ofintroducing VMware-only mention payloads or provider-local inventory readsunder `/api/vmware/*`. Runtime-specific container/app mentions remain shared-unified-resource mentions as well; VMware network inventory does not create a-provider-local mention family.+unified-resource mentions as well. The existing {id,name,type,node} payload+shape is retained, with registry ID as selection authority and labels/type/node+as hints. Unknown IDs cannot recover through a client name. Legacy structured+mention and session ID formats resolve only to a unique current owner.+VMware network inventory does not create a provider-local mention family.That same `/api/ai/chat` payload boundary owns request-local execution mode,and the server sets it. `ChatRequest` in `internal/api/ai_handler.go` has no`autonomous_mode` field, so a stale client's `autonomous_mode` is dropped atdiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 02f3dbf71a..61289cebba 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -846,6 +846,14 @@ on component mount. Closing clears the registered input so later keyboardcommands cannot target a detached composer. A handoff must leave Escape andkeyboard input in Assistant, not the underlying alert search.+Assistant mention suggestions preserve each resource.id. Provider scope and+current node identify same-label guests where policy permits them, and search+can use those visible fields. Selected chips retain independent canonical+IDs, allow removal without discarding prompt text, and show current owned+labels after inventory refresh. Governed labels never expose node or site+metadata through either suggestions or chips. Prompt history keeps the same+identity, including older bounded payloads interpreted by the runtime.+Mobile incident drawers transfer their exact context to Assistant and closethrough the shared explicit handoff callback. Keeping the source drawer aboveAssistant, or dropping its occurrence identity to make navigation work, failsdiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 44b4811e79..c66d517759 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -3136,7 +3136,10 @@ service-history reads plus denial/recovery without fabricated samples.If a store-backed read-state has not yet been refreshed for the PVE instancewhose current monitor state already contains guests, backup/snapshot pollingrefreshes the canonical resource store from the current state and continues- through the read-state interface. It must not fall back to direct legacy+ through the read-state interface. Explicit selections use the optional+ `ReferenceReadState` capability on the current `MonitorAdapter` generation,+ preserving registry identity across rename or node movement instead of+ binding a same-name guest from another provider. It must not fall back to direct legacyguest slices as the primary source of truth. Clustered PVE snapshot pollingmust therefore see guests collected earlier in the same cycle before callingthe Proxmox guest snapshot APIs.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 38b7dc913d..929f9c726e 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -400,6 +400,11 @@ retained buffers. Complete broadcast benchmarks include projection and deltaqueues rather than treating an ID-only or component allocation result as fieldCPU relief. Installed connected/closed-dashboard CPU remains separate evidence.+Realtime normalization also keeps provider ownership source-authoritative.+Flat storage instance/node fields may synthesize Proxmox facts only when the+current sources permit it, with explicit ownership facets preserved. Full and+delta merges apply the same bounded per-row rule without estate-wide lookup.+The resource adapter fast delta path must remain content-equivalent to the full merge for explicit Proxmox memory withdrawal. An absent canonical metric plus incoming Proxmox usageUnavailable clears the old display value; store patch operations must emit that clear even when only the raw facet key changed. This bounded per-changed-row check must not introduce an estate-wide scan or defeat untouched-row identity preservation. Adapter tests cover both delta paths and store writes, including trusted-zero recovery and ordinary partial omission.The PR #1935 log-level parser benchmark remains an unresolved environment-bounddiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex c30bdc88fb..22ac317998 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -5526,12 +5526,14 @@ falls back to the canonical redacted label if that governed summary ismissing, so path-only and IP-only redactions do not regress to raw identityleakage or over-redaction in chat context. That same unified-resource contractnow also owns the canonical mention identity path for shared Assistant reads:-chat surfaces must carry the backend-issued unified resource ID for canonical-`agent`, `vm`, `storage`, and `app-container` records, and backend mention-resolution must be able to recover those resources by canonical ID and-canonical name through the shared read-state instead of relying on-provider-local route families or frontend reconstruction of VMware- or-TrueNAS-specific coordinates.+chat surfaces carry the backend-issued ID for every supported mention kind.+ResolveResourceReferenceContext binds explicit selections to one owned record.+ResolveResourceContext allows unique name lookup for callers without a+selection. Both share current native coordinates and provider-scoped parent+ownership. Unknown selections and duplicated names refuse routing. Provider+renames update current display names without replacing canonical identity or+overriding a present higher-priority source. Native and legacy wire formats+remain bounded input compatibility, never a second primary identity model.Assistant finding handoffs now resolve product-originated resource referencesthrough the same canonical unified-resource helper before building policycontext, so handoff handling guidance uses `CanonicalGovernanceMetadata(...)`,@@ -6014,6 +6016,10 @@ sparklines match chart series to rows through the chart-key candidates inowns the typed extraction of platform-data fragments from unified resources,and `frontend-modern/src/utils/resourceStateAdapters.ts` owns canonicalprojection from unified resources into node/PBS/PMG runtime view models.+Legacy flat fields may synthesize a Proxmox facet only when current sources+include Proxmox, or source ownership is absent and the legacy shape applies.+Storage `instance` and `node` coordinates do not override VMware, TrueNAS or+agent ownership. Explicit ownership facets remain authoritative.Future resource-to-runtime mapping changes should extend these unified-resourceowners instead of rebuilding ad hoc platform-data parsing or action-targetfallback logic inside alerts, settings, recovery, AI, or infrastructure-localdiff --git a/frontend-modern/browser-verification/e80c37907c255b11.json b/frontend-modern/browser-verification/e80c37907c255b11.jsonnew file mode 100644index 0000000000..0850282151--- /dev/null+++ b/frontend-modern/browser-verification/e80c37907c255b11.json@@ -0,0 +1,64 @@+{+ "version": 1,+ "base_sha": "421a784783ebf29709a9d5e1b6fb5c1f0d3a179a",+ "verified_at": "2026-10-13T00:50:58.421Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx",+ "frontend-modern/src/components/AI/Chat/index.tsx",+ "frontend-modern/src/utils/resourceStateAdapters.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/components/AI/Chat/index.tsx": "95bf41da8b96cf528ea9aab1b6aef98443d749158dd016a02d04f85bfac203ca",+ "frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx": "f6836b4da038aacee20846f3e1d0db29406bbf48b2baee88fee4513b3aa31b6b",+ "frontend-modern/src/utils/resourceStateAdapters.ts": "f46778a596def79e0593197f8b001c21ae98ba4f74253fa8329585412d95e1a0"+ },+ "routes": [+ "/proxmox/overview"+ ],+ "viewports": [+ {+ "width": 1280,+ "height": 800+ },+ {+ "width": 900,+ "height": 800+ },+ {+ "width": 390,+ "height": 844+ }+ ],+ "states": [+ "configured and unconfigured Assistant",+ "open resource picker with same-name resources in different provider scopes",+ "hover and keyboard selection",+ "selected and removed chips",+ "current provider name and node refresh",+ "submitted, pending and completed response",+ "restored prompt after reload and server error",+ "empty resource search",+ "nested model menu and resource picker dismissal",+ "governed suggestions and selected resources"+ ],+ "interactions": [+ "open and close Assistant",+ "search by name and provider scope",+ "hover options",+ "ArrowUp, ArrowDown, Enter and Tab selection",+ "remove and reselect resource with draft text preserved",+ "Escape and outside-click dismissal with focus return",+ "select VM, system container, application container, agent and storage using registry IDs",+ "submit distinct clone IDs",+ "rename and move selected resource without rebinding",+ "reload persisted prompt history",+ "restore draft after HTTP 503",+ "model menu cross-control dismissal",+ "withhold private name, provider and node according to current resource policy"+ ],+ "binary_sha256": "b64ec7c36c3255f561c9bc8fbbbf4b4e22c0eca151af71049fcff08f86f3e00b",+ "checks": 108,+ "pixel_inspection": "Open pickers, hover, selected chips, renamed/moved selections, pending/completed response, restored storage draft, model menu, governed picker/selection and unconfigured composer inspected from current build screenshots.",+ "fixture_boundary": "Local synthetic registry inventory and controlled provider/session/SSE transport. No native infrastructure action or external inference claimed."+}diff --git a/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx b/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsxindex e05b6912cb..9e7bd2cdc6 100644--- a/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx+++ b/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx@@ -8,6 +8,7 @@ export interface MentionResource {type: 'vm' | 'system-container' | 'app-container' | 'agent' | 'storage';status?: string;node?: string;+ scope?: string;}interface MentionAutocompleteProps {@@ -31,7 +32,9 @@ export function MentionAutocomplete(props: MentionAutocompleteProps) {const q = props.query.toLowerCase();if (!q) return props.resources.slice(0, 10); // Show first 10 if no query- return props.resources.filter((r) => r.label.toLowerCase().includes(q)).slice(0, 10); // Limit to 10 results+ return props.resources+ .filter((r) => [r.label, r.node, r.scope].some((value) => value?.toLowerCase().includes(q)))+ .slice(0, 10); // Limit to 10 results};// Reset selection when query changes@@ -208,8 +211,8 @@ export function MentionAutocomplete(props: MentionAutocompleteProps) {tabIndex={-1}aria-selected={index() === selectedIndex()}aria-label={`Mention ${resource.label}: ${resource.type}${- resource.node ? ` on ${resource.node}` : ''- }${resource.status ? `, ${resource.status}` : ''}`}+ resource.node && resource.node !== resource.scope ? ` on ${resource.node}` : ''+ }${resource.scope ? ` in ${resource.scope}` : ''}${resource.status ? `, ${resource.status}` : ''}`}class={`w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-surface-hover transition-colors ${index() === selectedIndex() ? 'bg-surface-hover' : ''}`}@@ -234,9 +237,13 @@ export function MentionAutocomplete(props: MentionAutocompleteProps) {/></Show></div>- <div class="text-xs text-muted">+ <div class="text-xs text-muted break-words">{resource.type}- <Show when={resource.node}>+ <Show when={resource.scope}>+ {' · '}+ {resource.scope}+ </Show>+ <Show when={resource.node && resource.node !== resource.scope}>{' · '}{resource.node}</Show>diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsxindex e2598884c8..6a7856eb34 100644--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx@@ -415,6 +415,7 @@ vi.mock('../MentionAutocomplete', () => ({data-resource-count={String(props.resources.length)}data-resource-ids={props.resources.map((resource) => resource.id).join('|')}data-resource-labels={props.resources.map((resource) => resource.label).join('|')}+ data-resource-nodes={props.resources.map((resource) => resource.node || '').join('|')}><buttontype="button"@@ -4983,6 +4984,113 @@ describe('AIChat', () => {// ── @ mention detection ──────────────────────────────────────────────describe('mention autocomplete', () => {+ it('uses canonical provider labels without displaying a legacy instance placeholder', async () => {+ const storage = {+ id: 'storage-opaque',+ type: 'storage' as const,+ name: 'Archive',+ displayName: 'Archive',+ status: 'online',+ platformType: 'vmware-vsphere',+ sourceType: 'api',+ vmware: {+ connectionName: 'Lab vCenter',+ entityType: 'datastore',+ managedObjectId: 'datastore-1',+ },+ platformData: { instance: 'storage-opaque' },+ };+ mockByType.mockImplementation((type: string) => (type === 'storage' ? [storage] : []));+ mockResources.mockReturnValue([storage]);+ renderChat();+ const textarea = screen.getByPlaceholderText(+ 'Ask about your infrastructure...',+ ) as HTMLTextAreaElement;+ Object.defineProperty(textarea, 'selectionStart', { value: 1, writable: true });+ fireEvent.input(textarea, { target: { value: '@' } });+ fireEvent.click(screen.getByTestId('mention-select-storage-opaque'));+ const selected = screen.getByLabelText('Selected resources');+ expect(selected).toHaveTextContent('Lab vCenter');+ expect(selected).not.toHaveTextContent('storage-opaque');+ expect(selected.textContent?.match(/Lab vCenter/g)).toHaveLength(1);+ });++ it('withholds governed guest nodes and site names from suggestions and selected chips', async () => {+ const guest = {+ id: 'vm-governed',+ type: 'vm' as const,+ name: 'secret-guest',+ status: 'running',+ label: 'withheld guest',+ aiSafeSummary: 'withheld guest',+ policy: {+ sensitivity: 'restricted' as const,+ routing: { scope: 'local-only' as const, redact: ['hostname'] as const },+ },+ proxmox: { vmid: 101, nodeName: 'secret-node', instance: 'secret-site' },+ };+ mockByType.mockImplementation((type: string) => (type === 'vm' ? [guest] : []));+ mockResources.mockReturnValue([guest]);+ renderChat();+ const textarea = screen.getByPlaceholderText(+ 'Ask about your infrastructure...',+ ) as HTMLTextAreaElement;+ Object.defineProperty(textarea, 'selectionStart', { value: 1, writable: true });+ fireEvent.input(textarea, { target: { value: '@' } });+ const suggestions = screen.getByTestId('mention-autocomplete');+ expect(suggestions).toHaveAttribute('data-resource-nodes', '');+ fireEvent.click(screen.getByTestId('mention-select-vm-governed'));+ const selected = screen.getByLabelText('Selected resources');+ expect(selected).not.toHaveTextContent('secret-node');+ expect(selected).not.toHaveTextContent('secret-site');+ expect(selected).not.toHaveTextContent('secret-guest');+ });++ it('keeps same-label selections distinct and removable by canonical ID', async () => {+ const clones = ['Site A', 'Site B'].map((instance, index) => ({+ id: 'vm-owner-' + index,+ type: 'vm' as const,+ name: 'duplicate',+ displayName: 'duplicate',+ status: 'running',+ platformType: 'proxmox',+ sourceType: 'proxmox',+ proxmox: { vmid: 101, nodeName: 'node1', instance },+ }));+ mockByType.mockImplementation((type: string) => (type === 'vm' ? clones : []));+ mockResources.mockReturnValue(clones);+ renderChat();+ const textarea = screen.getByPlaceholderText(+ 'Ask about your infrastructure...',+ ) as HTMLTextAreaElement;+ const pick = (id: string) => {+ Object.defineProperty(textarea, 'selectionStart', {+ value: 1,+ writable: true,+ configurable: true,+ });+ fireEvent.input(textarea, { target: { value: '@' } });+ fireEvent.click(screen.getByTestId('mention-select-' + id));+ };+ pick('vm-owner-0');+ pick('vm-owner-1');+ const selected = screen.getByLabelText('Selected resources');+ expect(selected).toHaveTextContent('Site A');+ expect(selected).toHaveTextContent('Site B');+ fireEvent.click(+ within(selected).getByRole('button', { name: 'Remove resource: duplicate: Site A: node1' }),+ );+ expect(selected).not.toHaveTextContent('Site A');+ expect(textarea.value).toContain('@duplicate');+ await waitForProviderCheckSettled();+ fireEvent.keyDown(textarea, { key: 'Enter' });+ expect(mockChat.sendMessage).toHaveBeenCalledWith(+ '@duplicate',+ [expect.objectContaining({ id: 'vm-owner-1', name: 'duplicate', type: 'vm' })],+ undefined,+ );+ });+it('activates mention autocomplete on @ input', () => {renderChat();const textarea = screen.getByPlaceholderText(@@ -5212,10 +5320,10 @@ describe('AIChat', () => {await waitFor(() => {expect(screen.getByTestId('mention-autocomplete').getAttribute('data-resource-ids'),- ).toContain('agent:vc-1:host:host-101');+ ).toContain('vmware-host-1');});- fireEvent.click(screen.getByTestId('mention-select-agent:vc-1:host:host-101'));+ fireEvent.click(screen.getByTestId('mention-select-vmware-host-1'));fireEvent.keyDown(textarea, { key: 'Enter' });await waitFor(() => {@@ -5223,7 +5331,7 @@ describe('AIChat', () => {'@ESXi 01',[expect.objectContaining({- id: 'agent:vc-1:host:host-101',+ id: 'vmware-host-1',name: 'ESXi 01',type: 'agent',}),@@ -5339,7 +5447,7 @@ describe('AIChat', () => {'@redacted by policy',[expect.objectContaining({- id: 'node::secret-node-1',+ id: 'agent-1',name: 'redacted by policy',type: 'agent',}),diff --git a/frontend-modern/src/components/AI/Chat/__tests__/MentionAutocomplete.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/MentionAutocomplete.test.tsxindex e691a0e5f5..ac0146f1ce 100644--- a/frontend-modern/src/components/AI/Chat/__tests__/MentionAutocomplete.test.tsx+++ b/frontend-modern/src/components/AI/Chat/__tests__/MentionAutocomplete.test.tsx@@ -435,3 +435,19 @@ describe('MentionAutocomplete', () => {});});});++describe('provider-scoped mentions', () => {+ it('shows and searches site names without collapsing equal labels', () => {+ const resources = [+ makeResource({ id: 'vm-site-a', label: 'duplicate', scope: 'Site A' }),+ makeResource({ id: 'vm-site-b', label: 'duplicate', scope: 'Site B' }),+ ];+ const selected = vi.fn();+ renderAutocomplete({ resources, query: 'site b', onSelect: selected });+ expect(screen.queryByRole('option', { name: /in Site A/ })).not.toBeInTheDocument();+ const option = screen.getByRole('option', { name: /in Site B/ });+ expect(option).toHaveTextContent('Site B');+ fireEvent.click(option);+ expect(selected).toHaveBeenCalledWith(resources[1]);+ });+});diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsxindex fd33d6c52c..69db031d00 100644--- a/frontend-modern/src/components/AI/Chat/index.tsx+++ b/frontend-modern/src/components/AI/Chat/index.tsx@@ -133,12 +133,8 @@ import {} from '@/utils/aiProviderPresentation';import { getCachedUnifiedResources } from '@/hooks/useUnifiedResources';import type { ModelInfo as RuntimeModelInfo } from '@/types/ai';-import type { Resource } from '@/types/resource';-import { isAppContainerDiscoveryResourceType } from '@/utils/discoveryTarget';-import {- getActionableAgentIdFromResource,- isAgentFacetInfrastructureResource,-} from '@/utils/agentResources';+import { requiresGovernedResourceDisplay, type Resource } from '@/types/resource';+import { isAgentFacetInfrastructureResource } from '@/utils/agentResources';import { normalizeChatMentionKeyPart } from '@/utils/chatIdentifiers';import { getGlobalWebSocketStore } from '@/stores/websocket-global';import { copyToClipboard } from '@/utils/clipboard';@@ -374,6 +370,7 @@ const normalizePromptHistoryEntry = (value: unknown): PromptHistoryEntry | nullid,label,type,+ scope: typeof mentionRecord.scope === 'string' ? mentionRecord.scope : undefined,node: typeof mentionRecord.node === 'string' ? mentionRecord.node : undefined,status: typeof mentionRecord.status === 'string' ? mentionRecord.status : undefined,};@@ -814,6 +811,9 @@ export const AIChat: Component<AIChatProps> = (props) => {textareaRef.style.height = `${Math.min(textareaRef.scrollHeight, 160)}px`;};+ const selectedMention = (mention: MentionResource) =>+ mentionResources().find((candidate) => candidate.id === mention.id) || mention;+const cloneMentions = (mentions: MentionResource[]) =>mentions.map((mention) => ({ ...mention }));@@ -888,7 +888,8 @@ export const AIChat: Component<AIChatProps> = (props) => {mention.id === other.id &&mention.label === other.label &&mention.type === other.type &&- mention.node === other.node+ mention.node === other.node &&+ mention.scope === other.scope);});};@@ -3011,23 +3012,7 @@ export const AIChat: Component<AIChatProps> = (props) => {value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;const asString = (value: unknown): string | undefined =>typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;- const getAgentActionId = (resource: Resource): string => {- return getActionableAgentIdFromResource(resource) || resource.id;- };- const getDockerActionId = (resource: Resource): string => {- const platformData = readPlatformData(resource);- const platformDocker = asRecord(platformData?.docker);- const discoveryTarget = resource.discoveryTarget;- return (- (isAppContainerDiscoveryResourceType(discoveryTarget?.resourceType)- ? discoveryTarget?.resourceId- : undefined) ||- asString(platformDocker?.hostSourceId) ||- asString(platformData?.hostSourceId) ||- discoveryTarget?.agentId ||- resource.id- );- };+const getAppContainerMentionHost = (resource: Resource): string => {const platformData = readPlatformData(resource);const platformDocker = asRecord(platformData?.docker);@@ -3040,43 +3025,12 @@ export const AIChat: Component<AIChatProps> = (props) => {'');};- const getAppContainerMentionId = (resource: Resource): string => {- if (resource.id.startsWith('app-container:')) {- return resource.id;- }-- const host = getAppContainerMentionHost(resource);- const platformData = readPlatformData(resource);- const platformDocker = asRecord(platformData?.docker);- const containerID =- asString(platformDocker?.containerId) ||- asString(platformDocker?.name) ||- asString(resource.canonicalIdentity?.primaryId) ||- asString(resource.name) ||- asString(resource.id);-- if (host && containerID) {- return `app-container:${host}:${containerID}`;- }-- return resource.id;- };-- const parseLegacyVmid = (- platformData: Record<string, unknown> | undefined,- ): number | undefined => {- const vmidRaw = platformData?.vmid;- if (typeof vmidRaw === 'number' && Number.isFinite(vmidRaw) && vmidRaw > 0) return vmidRaw;- if (typeof vmidRaw === 'string') {- const parsed = parseInt(vmidRaw, 10);- if (Number.isFinite(parsed) && parsed > 0) return parsed;- }- return undefined;- };const getVMMentionNode = (resource: Resource): string => {const platformData = readPlatformData(resource);return (+ asString(resource.proxmox?.nodeName) ||+ asString(resource.proxmox?.node) ||asString(platformData?.node) ||asString(resource.vmware?.runtimeHostName) ||asString(resource.vmware?.runtimeHostId) ||@@ -3085,36 +3039,6 @@ export const AIChat: Component<AIChatProps> = (props) => {);};- const getVMMentionId = (resource: Resource): string => {- if (resource.id.startsWith('vm:')) {- return resource.id;- }-- const platformData = readPlatformData(resource);- const node = getVMMentionNode(resource);- const vmid = parseLegacyVmid(platformData);- if (node && vmid !== undefined) {- return `vm:${node}:${vmid}`;- }-- return resource.id;- };-- const getSystemContainerMentionId = (resource: Resource): string => {- if (resource.id.startsWith('system-container:')) {- return resource.id;- }-- const platformData = readPlatformData(resource);- const node = asString(platformData?.node) || resource.parentName || '';- const vmid = parseLegacyVmid(platformData);- if (node && vmid !== undefined) {- return `system-container:${node}:${vmid}`;- }-- return resource.id;- };-const getStorageMentionNode = (resource: Resource): string => {return (resource.parentName ||@@ -3135,41 +3059,52 @@ export const AIChat: Component<AIChatProps> = (props) => {);const mentionCandidates: MentionResource[] = [];+ const mentionScope = (resource: Resource): string | undefined => {+ if (requiresGovernedResourceDisplay(resource.policy)) return undefined;+ return asString(resource.proxmox?.instance) || asString(resource.vmware?.connectionName);+ };+// Add VMsfor (const vm of vms) {const node = getVMMentionNode(vm);mentionCandidates.push({- id: getVMMentionId(vm),+ id: vm.id,+ scope: mentionScope(vm),label: getPreferredResourceDisplayName(vm),type: 'vm',status: vm.status === 'running' ? 'running' : 'stopped',- node,+ node: requiresGovernedResourceDisplay(vm.policy) ? undefined : node,});}// Add LXC/system containers (includes OCI containers).for (const container of containers) {const platformData = readPlatformData(container);- const node = asString(platformData?.node) || container.parentName || '';+ const node =+ asString(container.proxmox?.nodeName) ||+ asString(container.proxmox?.node) ||+ asString(platformData?.node) ||+ container.parentName ||+ '';mentionCandidates.push({- id: getSystemContainerMentionId(container),+ id: container.id,+ scope: mentionScope(container),label: getPreferredResourceDisplayName(container),type: 'system-container',status: container.status === 'running' ? 'running' : 'stopped',- node,+ node: requiresGovernedResourceDisplay(container.policy) ? undefined : node,});}// Add container runtimesfor (const runtime of dockerHosts) {- const dockerActionId = getDockerActionId(runtime);const label = getPreferredResourceDisplayName(runtime);const runtimeStatus =runtime.status === 'online' || runtime.status === 'running'? 'online': runtime.status || 'online';mentionCandidates.push({- id: `agent:${dockerActionId}`,+ id: runtime.id,label,type: 'agent',status: runtimeStatus,@@ -3181,28 +3116,34 @@ export const AIChat: Component<AIChatProps> = (props) => {// the same mention contract as Docker-backed workloads.for (const container of appContainers) {mentionCandidates.push({- id: getAppContainerMentionId(container),+ id: container.id,label: getPreferredResourceDisplayName(container),type: 'app-container',status: container.status === 'running' ? 'running' : 'exited',- node: getAppContainerMentionHost(container),+ node: requiresGovernedResourceDisplay(container.policy)+ ? undefined+ : getAppContainerMentionHost(container),});}for (const storage of storageResources) {mentionCandidates.push({id: storage.id,+ scope: mentionScope(storage),label: getPreferredResourceDisplayName(storage),type: 'storage',status: storage.status,- node: getStorageMentionNode(storage),+ node: requiresGovernedResourceDisplay(storage.policy)+ ? undefined+ : getStorageMentionNode(storage),});}// Add nodesfor (const node of nodes) {mentionCandidates.push({- id: `node:${node.platformId || ''}:${node.name}`,+ id: node.id,+ scope: mentionScope(node),label: getPreferredResourceDisplayName(node),type: 'agent',status: node.status,@@ -3211,14 +3152,14 @@ export const AIChat: Component<AIChatProps> = (props) => {// Add standalone agentsfor (const agentResource of agentResources) {- const agentActionId = getAgentActionId(agentResource);const label = getPreferredResourceDisplayName(agentResource);const agentStatus =agentResource.status === 'online' || agentResource.status === 'running'? 'online': agentResource.status;mentionCandidates.push({- id: `agent:${agentActionId}`,+ id: agentResource.id,+ scope: mentionScope(agentResource),label,type: 'agent',status: agentStatus,@@ -5235,6 +5176,57 @@ export const AIChat: Component<AIChatProps> = (props) => {</For></div></Show>+ <Show when={accumulatedMentions().length > 0}>+ <div+ class="mb-2 flex min-w-0 flex-wrap items-center gap-1.5"+ aria-label="Selected resources"+ >+ <For each={accumulatedMentions()}>+ {(mention) => (+ <div class="inline-flex max-w-full items-center gap-1 rounded-md border border-border bg-surface-alt pl-2 pr-0.5 text-xs text-base-content">+ <span class="min-w-0 break-words py-1">+ {selectedMention(mention).label}+ <Show when={selectedMention(mention).scope}>+ {' · '}+ {selectedMention(mention).scope}+ </Show>+ <Show+ when={+ selectedMention(mention).node &&+ selectedMention(mention).node !== selectedMention(mention).scope+ }+ >+ {' · '}+ {selectedMention(mention).node}+ </Show>+ </span>+ <ActionIconButton+ onClick={() => {+ setAccumulatedMentions((previous) =>+ previous.filter((resource) => resource.id !== mention.id),+ );+ focusComposer();+ }}+ tone="muted"+ size="2xs"+ label={[+ 'Remove resource',+ selectedMention(mention).label,+ selectedMention(mention).scope,+ selectedMention(mention).node !== selectedMention(mention).scope+ ? selectedMention(mention).node+ : undefined,+ ]+ .filter(Boolean)+ .join(': ')}+ >+ <XIcon class="h-3 w-3" aria-hidden="true" />+ </ActionIconButton>+ </div>+ )}+ </For>+ </div>+ </Show><Show when={pastedBlocks().length > 0}><divclass="mb-2 flex min-w-0 flex-wrap items-center gap-1.5"diff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.tsindex 1bed7b1f83..6fb9b60ae3 100644--- a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts@@ -1326,6 +1326,46 @@ describe('resourceStateAdapters nodeFromResource', () => {]);});+ it.each(['vmware', 'truenas', 'agent'])(+ 'keeps flat storage coordinates within their %s source',+ (source) => {+ const platformType = source === 'vmware' ? 'vmware-vsphere' : source;+ const incoming = {+ ...createNodeResource({ instance: 'storage-canonical', node: '', cpus: 4 }),+ id: 'storage-canonical',+ type: 'storage',+ platformType,+ sources: [source],+ vmware:+ source === 'vmware' ? { connectionId: 'vc-1', connectionName: 'Lab vCenter' } : undefined,+ } as Resource;+ const [resource] = mergeCanonicalResourceSnapshot([incoming], []);+ expect(resource.proxmox).toBeUndefined();+ expect((resource.platformData as Record<string, unknown>).proxmox).toBeUndefined();+ expect(resource.platformType).toBe(platformType);+ expect(resource.vmware).toEqual(incoming.vmware);+ const [refreshed] = mergeCanonicalResourceDeltaSnapshot(+ [incoming],+ [resource],+ new Set([incoming.id]),+ );+ expect(refreshed.proxmox).toBeUndefined();+ expect(refreshed.vmware).toEqual(incoming.vmware);+ },+ );++ it('keeps explicit Proxmox ownership on an agent-reported disk', () => {+ const incoming = {+ ...createNodeResource({ instance: 'legacy-storage-coordinate' }),+ type: 'physical_disk',+ platformType: 'agent',+ sources: ['agent'],+ proxmox: { instance: 'owned-pve', nodeName: 'owned-node' },+ } as Resource;+ const [resource] = mergeCanonicalResourceSnapshot([incoming], []);+ expect(resource.proxmox).toEqual(incoming.proxmox);+ });+it('uses authoritative top-level sources for realtime storage platform canonicalization', () => {const [resource] = mergeCanonicalResourceSnapshot([diff --git a/frontend-modern/src/utils/resourceStateAdapters.ts b/frontend-modern/src/utils/resourceStateAdapters.tsindex 5880c70b20..53d360b266 100644--- a/frontend-modern/src/utils/resourceStateAdapters.ts+++ b/frontend-modern/src/utils/resourceStateAdapters.ts@@ -328,20 +328,27 @@ const hasLegacyProxmoxShape = (resource: Resource,platformData: JsonRecord,sources?: string[],-): boolean =>- resource.platformType === 'proxmox-pve' ||- sourceListHas(sources, 'proxmox-pve') ||- [- 'instance',- 'node',- 'clusterName',- 'vmid',- 'cpus',- 'template',- 'swapUsed',- 'swapTotal',- 'balloon',- ].some((key) => platformData[key] !== undefined);+): boolean => {+ // Flat instance/node fields also describe storage from other providers.+ // Current source ownership takes precedence over the legacy field shape.+ if (sources && sources.length > 0) {+ return sourceListHas(sources, 'proxmox-pve');+ }+ return (+ resource.platformType === 'proxmox-pve' ||+ [+ 'instance',+ 'node',+ 'clusterName',+ 'vmid',+ 'cpus',+ 'template',+ 'swapUsed',+ 'swapTotal',+ 'balloon',+ ].some((key) => platformData[key] !== undefined)+ );+};const canonicalizeLegacyPlatformData = (resource: Resource): Resource['platformData'] => {const platformData = asRecord(resource.platformData);diff --git a/internal/ai/chat/context_prefetch.go b/internal/ai/chat/context_prefetch.goindex 52f814cd85..ee832bf6b6 100644--- a/internal/ai/chat/context_prefetch.go+++ b/internal/ai/chat/context_prefetch.go@@ -184,221 +184,61 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMenrs := p.readStatefor _, sm := range structured {- // Parse the structured ID to extract resource details.- // Frontend ID formats: "vm:node:vmid", "system-container:node:vmid",- // "app-container:host:providerUid" (canonical), legacy "docker:hostId:containerId",- // "agent:id", "node:instance:name"- parts := strings.Split(sm.ID, ":")-- // Enforce canonical v6 frontend mention types only.- legacyMentionType := strings.ToLower(strings.TrimSpace(sm.Type))- if legacyMentionType == "container" || legacyMentionType == "lxc" || legacyMentionType == "docker" || legacyMentionType == "docker-container" {- log.Warn().- Str("name", sm.Name).- Str("id", sm.ID).- Msg("[ContextPrefetch] Ignoring unsupported legacy structured mention type")+ if unifiedresources.IsUnsupportedLegacyResourceTypeAlias(sm.Type) {+ continue+ }+ var resolved unifiedresources.ResolvedResourceContext+ if strings.TrimSpace(sm.ID) != "" {+ resolved = unifiedresources.ResolveResourceReferenceContext(rs, sm.ID)+ } else {+ resolved = unifiedresources.ResolveResourceContext(rs, sm.Name)+ }+ resource := resolved.Resource+ if resource == nil || !resolved.Location.Found {continue}- resourceType := tools.CanonicalToolResourceType(sm.Type)-- // Use the canonical unified-resource resolver for routing plus policy metadata.- resolved := unifiedresources.ResolveResourceContext(rs, sm.Name)- policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource)loc := resolved.Location-+ resourceType := tools.CanonicalToolResourceType(loc.ResourceType)+ policy, summary := resourceMentionGovernance(resource)+ mention := ResourceMention{+ Name: loc.Name, ResourceType: resourceType,+ ResourceID: mentionResourceIDFromResolved(resourceType, resource),+ TargetID: mentionTargetIDFromResolved(resourceType, resource),+ Adapter: mentionAdapterFromResolved(resource), MatchedText: sm.Name,+ Policy: policy, AISafeSummary: summary, UnifiedResourceID: resource.ID,+ TargetHost: loc.TargetHost, SupportsControl: resourceSupportsControl(resourceType, resource),+ }switch resourceType {- case "vm":- vmID := ""- node := sm.Node- if len(parts) >= 3 {- node = parts[1]- vmID = strings.Join(parts[2:], ":")- }- vmID = firstNonEmptyTrimmed(vmID, mentionResourceIDFromResolved("vm", resolved.Resource))- node = firstNonEmptyTrimmed(node, mentionTargetIDFromResolved("vm", resolved.Resource))- mentions = append(mentions, ResourceMention{- Name: sm.Name,- ResourceType: "vm",- ResourceID: vmID,- TargetID: node,- Adapter: mentionAdapterFromResolved(resolved.Resource),- MatchedText: sm.Name,- Policy: policy,- AISafeSummary: aiSafeSummary,- UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),- TargetHost: loc.TargetHost,- SupportsControl: resourceSupportsControl("vm", resolved.Resource),- })-- case "system-container":- vmID := ""- node := sm.Node- if len(parts) >= 3 {- node = parts[1]- vmID = strings.Join(parts[2:], ":")- }- vmID = firstNonEmptyTrimmed(vmID, mentionResourceIDFromResolved("system-container", resolved.Resource))- node = firstNonEmptyTrimmed(node, mentionTargetIDFromResolved("system-container", resolved.Resource))- mentions = append(mentions, ResourceMention{- Name: sm.Name,- ResourceType: "system-container",- ResourceID: vmID,- TargetID: node,- Adapter: mentionAdapterFromResolved(resolved.Resource),- MatchedText: sm.Name,- Policy: policy,- AISafeSummary: aiSafeSummary,- UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),- TargetHost: loc.TargetHost,- SupportsControl: resourceSupportsControl("system-container", resolved.Resource),- })-case "app-container":- hostID, containerID := parseStructuredAppContainerMentionID(sm.ID, rs)- if resolved.Resource != nil {- resolvedHost, resolvedContainerID := resolvedAppContainerMentionCoordinates(resolved.Resource)- hostID = firstNonEmptyTrimmed(hostID, resolvedHost)- containerID = firstNonEmptyTrimmed(containerID, resolvedContainerID)- }-- // Gather bind mounts via ReadState- var mounts []MountInfo- if rs != nil {- for _, container := range rs.DockerContainers() {- if container == nil {- continue- }- if container.Name() == sm.Name || container.ContainerID() == containerID {- for _, m := range container.Mounts() {- if m.Source != "" && m.Destination != "" {- mounts = append(mounts, MountInfo{- Source: m.Source,- Destination: m.Destination,- })- }- }- break+ mention.TargetID, mention.ResourceID = resolvedAppContainerMentionCoordinates(resource)+ mention.DockerHostName, mention.DockerHostType = loc.DockerHostName, loc.DockerHostType+ mention.DockerHostVMID, mention.NodeName = loc.DockerHostVMID, loc.Node+ for _, container := range rs.DockerContainers() {+ if container == nil || container.ID() != resource.ID {+ continue+ }+ for _, mount := range container.Mounts() {+ if mount.Source != "" && mount.Destination != "" {+ mention.BindMounts = append(mention.BindMounts, MountInfo{Source: mount.Source, Destination: mount.Destination})}}+ break}-- mentions = append(mentions, ResourceMention{- Name: sm.Name,- ResourceType: "app-container",- ResourceID: containerID,- TargetID: hostID,- Adapter: mentionAdapterFromResolved(resolved.Resource),- MatchedText: sm.Name,- Policy: policy,- AISafeSummary: aiSafeSummary,- UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),- BindMounts: mounts,- DockerHostName: loc.DockerHostName,- DockerHostType: loc.DockerHostType,- DockerHostVMID: loc.DockerHostVMID,- NodeName: loc.Node,- TargetHost: loc.TargetHost,- })-case "storage":- resourceID := firstNonEmptyTrimmed(sm.ID, resolvedUnifiedResourceID(resolved.Resource), mentionResourceIDFromResolved("storage", resolved.Resource))- targetID := firstNonEmptyTrimmed(sm.Node, mentionTargetIDFromResolved("storage", resolved.Resource), loc.TargetHost)- mentions = append(mentions, ResourceMention{- Name: sm.Name,- ResourceType: "storage",- ResourceID: resourceID,- TargetID: targetID,- Adapter: mentionAdapterFromResolved(resolved.Resource),- MatchedText: sm.Name,- Policy: policy,- AISafeSummary: aiSafeSummary,- UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),- SupportsControl: resourceSupportsControl("storage", resolved.Resource),- TargetHost: firstNonEmptyTrimmed(loc.TargetHost, targetID),- })-- case "node":- mentions = append(mentions, ResourceMention{- Name: sm.Name,- ResourceType: "node",- ResourceID: sm.Name,- TargetID: sm.Name,- MatchedText: sm.Name,- Policy: policy,- AISafeSummary: aiSafeSummary,- UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),- TargetHost: loc.TargetHost,- })-+ mention.ResourceID = resource.ID+ mention.TargetID = firstNonEmptyTrimmed(mention.TargetID, loc.TargetID, loc.TargetHost)case "agent":- hostID := ""- if len(parts) >= 2 {- hostID = strings.Join(parts[1:], ":")- }- mentions = append(mentions, ResourceMention{- Name: sm.Name,- ResourceType: "agent",- ResourceID: hostID,- TargetID: hostID,- Adapter: mentionAdapterFromResolved(resolved.Resource),- MatchedText: sm.Name,- Policy: policy,- AISafeSummary: aiSafeSummary,- UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),- SupportsControl: resourceSupportsControl("agent", resolved.Resource),- TargetHost: loc.TargetHost,- })-- default:- if unifiedresources.IsUnsupportedLegacyResourceTypeAlias(sm.Type) {- log.Warn().- Str("name", sm.Name).- Str("id", sm.ID).- Msg("[ContextPrefetch] Ignoring unsupported structured mention type")- continue- }- log.Warn().- Str("name", sm.Name).- Str("type", sm.Type).- Msg("[ContextPrefetch] Unknown structured mention type, falling back to ResolveResource")- mentions = append(mentions, ResourceMention{- Name: sm.Name,- ResourceType: resourceType,- ResourceID: firstNonEmptyTrimmed(sm.ID, mentionResourceIDFromResolved(resourceType, resolved.Resource)),- TargetID: firstNonEmptyTrimmed(sm.Node, mentionTargetIDFromResolved(resourceType, resolved.Resource)),- MatchedText: sm.Name,- Policy: policy,- AISafeSummary: aiSafeSummary,- UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource),- TargetHost: loc.TargetHost,- })+ mention.ResourceID = firstNonEmptyTrimmed(mention.ResourceID, loc.TargetID, resource.ID)+ mention.TargetID = firstNonEmptyTrimmed(mention.TargetID, loc.TargetID)+ case "node":+ mention.ResourceID, mention.TargetID = loc.Name, loc.Node}+ mentions = append(mentions, mention)}return mentions}-type appContainerResourceGetter interface {- GetByType(unifiedresources.ResourceType) []unifiedresources.Resource-}--type appContainerResourceLister interface {- ListByType(unifiedresources.ResourceType) []unifiedresources.Resource-}--func appContainerResourcesFromReadState(rs unifiedresources.ReadState) []unifiedresources.Resource {- if rs == nil {- return nil- }- if getter, ok := any(rs).(appContainerResourceGetter); ok {- return getter.GetByType(unifiedresources.ResourceTypeAppContainer)- }- if lister, ok := any(rs).(appContainerResourceLister); ok {- return lister.ListByType(unifiedresources.ResourceTypeAppContainer)- }- return nil-}-func appContainerResourceHost(resource unifiedresources.Resource) string {if host := strings.TrimSpace(resource.ParentName); host != "" {return host@@ -421,35 +261,6 @@ func appContainerResourceHost(resource unifiedresources.Resource) string {return ""}-func parseStructuredAppContainerMentionID(mentionID string, rs unifiedresources.ReadState) (hostID string, containerID string) {- const canonicalPrefix = "app-container:"- if strings.HasPrefix(mentionID, canonicalPrefix) {- if rs != nil {- for _, resource := range appContainerResourcesFromReadState(rs) {- if !strings.EqualFold(strings.TrimSpace(resource.ID), mentionID) {- continue- }- host := appContainerResourceHost(resource)- if host == "" {- continue- }- if providerUID := appContainerProviderUID(resource, host); providerUID != "" {- return host, providerUID- }- }- }-- raw := strings.TrimPrefix(mentionID, canonicalPrefix)- parts := strings.SplitN(raw, ":", 2)- if len(parts) == 2 && strings.TrimSpace(parts[0]) != "" && strings.TrimSpace(parts[1]) != "" {- return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])- }- return "", ""- }-- return parseStructuredDockerMentionID(mentionID, rs)-}-func appContainerProviderUID(resource unifiedresources.Resource, host string) string {prefix := "app-container:" + strings.TrimSpace(host) + ":"if strings.HasPrefix(resource.ID, prefix) {@@ -478,21 +289,13 @@ func resolvedAppContainerMentionCoordinates(resource *unifiedresources.Resource)return "", ""}hostID = appContainerResourceHost(*resource)+ if resource.Docker != nil && strings.TrimSpace(resource.Docker.HostSourceID) != "" {+ hostID = strings.TrimSpace(resource.Docker.HostSourceID)+ }containerID = appContainerProviderUID(*resource, hostID)return strings.TrimSpace(hostID), strings.TrimSpace(containerID)}-func resolvedUnifiedResourceID(resource *unifiedresources.Resource) string {- if resource == nil {- return ""- }- return strings.TrimSpace(resource.ID)-}--func resolvedStructuredUnifiedResourceID(structuredID string, resource *unifiedresources.Resource) string {- return firstNonEmptyTrimmed(resolvedUnifiedResourceID(resource), structuredID)-}-func mentionResourceIDFromResolved(resourceType string, resource *unifiedresources.Resource) string {if resource == nil {return ""@@ -568,56 +371,6 @@ func firstNonEmptyTrimmed(values ...string) string {return ""}-func parseStructuredDockerMentionID(mentionID string, rs unifiedresources.ReadState) (hostID string, containerID string) {- const prefix = "docker:"- if !strings.HasPrefix(mentionID, prefix) {- return "", ""- }-- raw := strings.TrimPrefix(mentionID, prefix)- if raw == "" {- return "", ""- }-- // Prefer matching known docker host IDs via ReadState so host IDs containing- // colons remain intact (V6 unified IDs can include colon separators).- bestHostID := ""- bestContainerID := ""- if rs != nil {- for _, dockerHost := range rs.DockerHosts() {- if dockerHost == nil {- continue- }- id := strings.TrimSpace(dockerHost.HostSourceID())- if id == "" {- continue- }- hostPrefix := id + ":"- if !strings.HasPrefix(raw, hostPrefix) {- continue- }- candidateContainerID := strings.TrimPrefix(raw, hostPrefix)- if candidateContainerID == "" {- continue- }- if len(id) > len(bestHostID) {- bestHostID = id- bestContainerID = candidateContainerID- }- }- }- if bestHostID != "" {- return bestHostID, bestContainerID- }-- // Legacy fallback: split once after the docker prefix.- parts := strings.SplitN(raw, ":", 2)- if len(parts) < 2 {- return "", ""- }- return parts[0], parts[1]-}-// formatContextSummary creates a formatted summary of the resolved mentions.func (p *ContextPrefetcher) formatContextSummary(mentions []ResourceMention) string {if len(mentions) == 0 {@@ -654,7 +407,7 @@ func (p *ContextPrefetcher) formatContextSummary(mentions []ResourceMention) strsb.WriteString(fmt.Sprintf("Location: Docker on host \"%s\"\n", mention.DockerHostName))}- sb.WriteString(fmt.Sprintf("target_host: \"%s\"\n", mention.TargetHost))+ sb.WriteString(fmt.Sprintf("target_host: \"%s\"\n", firstNonEmptyTrimmed(mention.UnifiedResourceID, mention.TargetHost)))// Bind mounts - clarify these are on the LXC/VM filesystemif len(mention.BindMounts) > 0 {@@ -677,7 +430,7 @@ func (p *ContextPrefetcher) formatContextSummary(mentions []ResourceMention) strif (mention.ResourceType == "system-container" || mention.ResourceType == "vm") && mention.ResourceID != "" {sb.WriteString(fmt.Sprintf("VMID: %s\n", mention.ResourceID))if mention.SupportsControl {- sb.WriteString(fmt.Sprintf("Shared guest control actions are available with guest_id=\"%s\" and action=\"start|stop|shutdown|restart\".\n", mention.ResourceID))+ sb.WriteString(fmt.Sprintf("Shared guest control actions use pulse_control with type=\"resource\", resource_id=\"%s\" and action=\"start|stop|shutdown|restart\".\n", firstNonEmptyTrimmed(mention.UnifiedResourceID, mention.ResourceID)))} else {sb.WriteString("This guest is read-only in Pulse; shared write/control actions are unavailable for this resource.\n")}diff --git a/internal/ai/chat/context_prefetch_additional_test.go b/internal/ai/chat/context_prefetch_additional_test.goindex b65d4f724a..37d3945873 100644--- a/internal/ai/chat/context_prefetch_additional_test.go+++ b/internal/ai/chat/context_prefetch_additional_test.go@@ -16,6 +16,59 @@ func newTestReadState(snapshot models.StateSnapshot) unifiedresources.ReadStatereturn rr}+func TestContextPrefetcherCanonicalGuestMentionsKeepIndependentInstancesDistinct(t *testing.T) {+ rr := unifiedresources.NewRegistry(nil)+ rr.IngestSnapshot(models.StateSnapshot{VMs: []models.VM{+ {ID: "cluster-a:node1:101", Name: "duplicate", Instance: "cluster-a", Node: "node1", VMID: 101, Type: "qemu"},+ {ID: "cluster-b:node1:101", Name: "duplicate", Instance: "cluster-b", Node: "node1", VMID: 101, Type: "qemu"},+ }})+ prefetcher := NewContextPrefetcher(rr)+ for _, instance := range []string{"cluster-a", "cluster-b"} {+ id := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeVM, instance, 101)+ if _, found := rr.Get(id); !found {+ t.Fatalf("fixture did not publish canonical guest %s", id)+ }+ mentions := prefetcher.resolveStructuredMentions([]StructuredMention{{+ ID: id, Name: "duplicate", Type: "vm", Node: "node1",+ }})+ if len(mentions) != 1 || mentions[0].UnifiedResourceID != id {+ t.Errorf("explicit canonical guest selection crossed instance boundaries: selected=%s mentions=%+v", id, mentions)+ }+ }+}++func TestContextPrefetcherCanonicalGuestMentionUsesCurrentCoordinates(t *testing.T) {+ rr := unifiedresources.NewRegistry(nil)+ id := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeVM, "cluster-a", 101)+ rr.IngestSnapshot(models.StateSnapshot{VMs: []models.VM{{+ ID: "cluster-a:old-node:101", Name: "old-name", Instance: "cluster-a", Node: "old-node", VMID: 101, Type: "qemu",+ }}})+ rr.IngestSnapshot(models.StateSnapshot{VMs: []models.VM{{+ ID: "cluster-a:new-node:101", Name: "current-name", Instance: "cluster-a", Node: "new-node", VMID: 101, Type: "qemu",+ }}})+ prefetcher := NewContextPrefetcher(rr)+ mentions := prefetcher.resolveStructuredMentions([]StructuredMention{{+ ID: id, Name: "old-name", Type: "vm", Node: "old-node",+ }})+ if len(mentions) != 1 || mentions[0].UnifiedResourceID != id ||+ mentions[0].ResourceID != "101" || mentions[0].TargetID != "new-node" ||+ mentions[0].Name != "current-name" {+ t.Fatalf("canonical mention trusted stale client labels or coordinates: %+v", mentions)+ }+}++func TestContextPrefetcherUnknownCanonicalGuestCannotAttachByDisplayName(t *testing.T) {+ prefetcher := NewContextPrefetcher(newTestReadState(models.StateSnapshot{VMs: []models.VM{{+ ID: "cluster-a:node1:101", Name: "duplicate", Instance: "cluster-a", Node: "node1", VMID: 101, Type: "qemu",+ }}}))+ mentions := prefetcher.resolveStructuredMentions([]StructuredMention{{+ ID: "vm-0000000000000000", Name: "duplicate", Type: "vm", Node: "node1",+ }})+ if len(mentions) != 0 {+ t.Fatalf("unknown explicit resource ID selected a different same-name guest: %+v", mentions)+ }+}+func TestContextPrefetcher_NoReadState(t *testing.T) {prefetcher := NewContextPrefetcher(nil)if ctx := prefetcher.Prefetch(context.Background(), "check @missing", nil); ctx != nil {@@ -76,6 +129,7 @@ func TestContextPrefetcher_PlainTextResourceNamesDoNotPrefetch(t *testing.T) {func TestContextPrefetcher_ResolveStructuredMentions(t *testing.T) {state := models.StateSnapshot{+ Containers: []models.Container{{ID: "lab:node1:201", Name: "beta", Instance: "lab", Node: "node1", VMID: 201, Type: "lxc"}},DockerHosts: []models.DockerHost{{ID: "dock1",Hostname: "dock1",@@ -139,8 +193,8 @@ func TestContextPrefetcher_ResolveStructuredMentions(t *testing.T) {}unknown := prefetcher.resolveStructuredMentions([]StructuredMention{{ID: "weird:1", Name: "mystery", Type: "weird"}})- if len(unknown) != 1 || unknown[0].ResourceType != "weird" {- t.Fatalf("expected unknown type to be preserved")+ if len(unknown) != 0 {+ t.Fatalf("unknown resource reference must not fabricate monitoring context")}legacyHost := prefetcher.resolveStructuredMentions([]StructuredMention{{ID: "host:host1", Name: "host1", Type: "host"}})@@ -324,7 +378,7 @@ func TestContextPrefetcher_ResolveStructuredMentions_VMwareCanonicalIDs(t *testiif mentions[0].SupportsControl {t.Fatalf("expected VMware host mention to stay read-only, got %+v", mentions[0])}- if mentions[0].UnifiedResourceID != "agent:vc-1:host:host-101" {+ if mentions[0].UnifiedResourceID != rr.Hosts()[0].ID() {t.Fatalf("expected VMware host unified resource id, got %+v", mentions[0])}if mentions[1].ResourceType != "vm" || mentions[1].ResourceID != "vm-201" || mentions[1].TargetID != "esxi-01.lab.local" {@@ -434,10 +488,10 @@ func TestContextPrefetcher_FormatContextSummary_VMwareGuestStaysReadOnly(t *testif strings.Contains(summary, "target_host:") {t.Fatalf("expected VMware guest summary to avoid target_host routing, got %q", summary)}- if !strings.Contains(summary, "resource_id: \"app-01\"") {+ if !strings.Contains(summary, "resource_id: \"vmware-vm-1\"") {t.Fatalf("expected VMware guest summary to expose canonical resource_id routing, got %q", summary)}- if !strings.Contains(summary, "Status, alerts, recent activity, and metrics are available through resource_id=\"app-01\"") {+ if !strings.Contains(summary, "Status, alerts, recent activity, and metrics are available through resource_id=\"vmware-vm-1\"") {t.Fatalf("expected VMware summary to expose resource_id read context, got %q", summary)}}@@ -500,10 +554,10 @@ func TestContextPrefetcher_FormatContextSummary_TrueNASAppUsesNativeResourceReadif strings.Contains(summary, "target_host:") {t.Fatalf("expected native TrueNAS app summary to avoid target_host routing, got %q", summary)}- if !strings.Contains(summary, "resource_id: \"Nextcloud\"") {+ if !strings.Contains(summary, "resource_id: \"app-container:truenas-main:nextcloud\"") {t.Fatalf("expected native TrueNAS app summary to expose resource_id routing, got %q", summary)}- if !strings.Contains(summary, "Shared reads address this resource by resource_id=\"Nextcloud\"") {+ if !strings.Contains(summary, "Shared reads address this resource by resource_id=\"app-container:truenas-main:nextcloud\"") {t.Fatalf("expected native TrueNAS app summary to expose native resource context, got %q", summary)}}diff --git a/internal/ai/chat/read_routing_hints.go b/internal/ai/chat/read_routing_hints.goindex d82b83c183..3d545c6c34 100644--- a/internal/ai/chat/read_routing_hints.go+++ b/internal/ai/chat/read_routing_hints.go@@ -26,7 +26,7 @@ func buildReadRoutingHint(kind, adapter, targetHost, displayName, resourceID strcanonicalKind := tools.CanonicalToolResourceType(kind)adapter = strings.ToLower(strings.TrimSpace(adapter))targetHost = strings.TrimSpace(targetHost)- resourceRef := firstNonEmptyTrimmed(displayName, resourceID)+ resourceRef := firstNonEmptyTrimmed(resourceID, displayName)switch {case canonicalKind == "app-container" && adapter == "truenas":@@ -43,12 +43,13 @@ func buildReadRoutingHint(kind, adapter, targetHost, displayName, resourceID str}func readRoutingHintForMention(mention ResourceMention) readRoutingHint {- resourceRef := firstNonEmptyTrimmed(mention.Name, mention.UnifiedResourceID, mention.ResourceID)- return buildReadRoutingHint(mention.ResourceType, mention.Adapter, mention.TargetHost, resourceRef, mention.ResourceID)+ resourceRef := firstNonEmptyTrimmed(mention.UnifiedResourceID, mention.ResourceID, mention.Name)+ target := firstNonEmptyTrimmed(mention.UnifiedResourceID, mention.TargetHost)+ return buildReadRoutingHint(mention.ResourceType, mention.Adapter, target, mention.Name, resourceRef)}func readRoutingHintForResolvedResource(kind, adapter, targetHost, displayName, resourceID string) readRoutingHint {- return buildReadRoutingHint(kind, adapter, targetHost, displayName, resourceID)+ return buildReadRoutingHint(kind, adapter, firstNonEmptyTrimmed(resourceID, targetHost), displayName, resourceID)}func (h readRoutingHint) targetFact() string {diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 7e60570c59..bc745205af 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -2736,7 +2736,7 @@ func (s *Service) hydrateHandoffResources(sessionID string, handoffResources []Hcontinue}resolvedCtx.AddResolvedResource(reg)- if resolved, ok := resolvedCtx.GetResolvedResourceByAlias(reg.Name); ok {+ if resolved, ok := resolvedCtx.GetResolvedResourceByID(reg.ResolvedID()); ok {resolvedCtx.MarkExplicitAccess(resolved.GetResourceID())log.Debug().Str("session_id", sessionID).@@ -3906,7 +3906,10 @@ func (s *Service) injectRecentSessionContext(sessionID string, messages []Messagif !ok || res == nil {continue}- policy, aiSafeSummary := recentSessionResourceGovernance(resourceProvider, resourceID, res)+ policy, aiSafeSummary, owned := recentSessionResourceGovernance(resourceProvider, resourceID, res)+ if !owned {+ continue+ }label := res.Nameif label == "" {label = resourceID@@ -3992,29 +3995,19 @@ func (s *Service) injectRecentSessionContext(sessionID string, messages []Messagmessages[lastIdx].Content = context + "\n\n---\nUser message:\n" + messages[lastIdx].Content}-func recentSessionResourceGovernance(provider tools.UnifiedResourceProvider, resourceID string, res *ResolvedResource) (*unifiedresources.ResourcePolicy, string) {- if provider == nil || res == nil {- return nil, ""- }- resourceType := res.Kind- if resourceType == "" {- resourceType = res.ResourceType- }- node := res.Node- if node == "" {- node = res.Scope.HostName- }- resource, ok := tools.CanonicalHandoffUnifiedResource(provider, firstNonEmptyRecentString(resourceID, res.ResourceID, res.ProviderUID), res.Name, resourceType, node)- if !ok && res.ResourceID != "" && res.ResourceID != resourceID {- resource, ok = tools.CanonicalHandoffUnifiedResource(provider, res.ResourceID, res.Name, resourceType, node)+func recentSessionResourceGovernance(provider tools.UnifiedResourceProvider, resourceID string, res *ResolvedResource) (*unifiedresources.ResourcePolicy, string, bool) {+ if res == nil {+ return nil, "", false}- if !ok && res.ProviderUID != "" {- resource, ok = tools.CanonicalHandoffUnifiedResource(provider, res.ProviderUID, res.Name, resourceType, node)+ if provider == nil {+ return nil, "", true}+ resource, ok := tools.CanonicalHandoffUnifiedResource(provider, firstNonEmptyRecentString(resourceID, res.ResourceID), "", "", "")if !ok {- return nil, ""+ return nil, "", false}- return unifiedresources.CanonicalGovernanceMetadata(&resource)+ policy, summary := unifiedresources.CanonicalGovernanceMetadata(&resource)+ return policy, summary, true}func firstNonEmptyRecentString(values ...string) string {diff --git a/internal/ai/chat/service_recent_context_test.go b/internal/ai/chat/service_recent_context_test.goindex 1583603a89..460f165c7f 100644--- a/internal/ai/chat/service_recent_context_test.go+++ b/internal/ai/chat/service_recent_context_test.go@@ -50,7 +50,7 @@ func TestInjectRecentSessionContext_InjectsNeutralResourceFacts(t *testing.T) {if !strings.Contains(content, "Session context from earlier Assistant turns. Use only if relevant to the user's message; otherwise ignore it or ask a clarifying question.") {t.Fatalf("expected neutral session context framing, got: %s", content)}- if !strings.Contains(content, "- api (app-container on minipc); tool addressing fact: target_host=\"host-1\"") {+ if !strings.Contains(content, "- api (app-container on minipc); tool addressing fact: target_host=\"app-container:minipc:abc\"") {t.Fatalf("expected primary resource facts, got: %s", content)}if !strings.Contains(content, "- db (vm on node-2)") {@@ -195,7 +195,7 @@ func TestInjectRecentSessionContext_UsesResourceIDFactForTrueNASApp(t *testing.Tservice.injectRecentSessionContext(session.ID, messages, store)content := messages[0].Content- if !strings.Contains(content, "- Nextcloud (app-container on truenas-main); tool addressing fact: resource_id=\"Nextcloud\"") {+ if !strings.Contains(content, "- Nextcloud (app-container on truenas-main); tool addressing fact: resource_id=\"app-container:truenas-main:nextcloud\"") {t.Fatalf("expected resource_id fact, got: %s", content)}}@@ -225,10 +225,33 @@ func TestInjectRecentSessionContext_UsesQueryResourceIDFactForVMware(t *testing.service.injectRecentSessionContext(session.ID, messages, store)content := messages[0].Content- if !strings.Contains(content, "- esxi-01.lab.local (agent on Lab VC); tool addressing fact: resource_id=\"esxi-01.lab.local\"") {+ if !strings.Contains(content, "- esxi-01.lab.local (agent on Lab VC); tool addressing fact: resource_id=\"agent:vc-1:host:host-101\"") {t.Fatalf("expected resource_id fact, got: %s", content)}if strings.Contains(content, "target_host=\"esxi-01.lab.local\"") {t.Fatalf("expected VMware recent context to avoid target_host routing, got: %s", content)}}++func TestInjectRecentSessionContextUnknownIDCannotBorrowAnotherOwner(t *testing.T) {+ store, err := NewSessionStore(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ session, err := store.Create()+ if err != nil {+ t.Fatal(err)+ }+ store.GetResolvedContext(session.ID).AddResourceWithExplicitAccess("same-name", &ResolvedResource{+ ResourceID: "vm-unknown", ProviderUID: "vm-known", Name: "same-name", Kind: "vm", TargetHost: "secret-node",+ })+ provider := handoffUnifiedProvider{resources: map[unifiedresources.ResourceType][]unifiedresources.Resource{+ unifiedresources.ResourceTypeVM: {{ID: "vm-known", Name: "same-name", Type: unifiedresources.ResourceTypeVM}},+ }}+ messages := []Message{{Role: "user", Content: "what happened?"}}+ service := &Service{unifiedResourceProvider: provider}+ service.injectRecentSessionContext(session.ID, messages, store)+ if messages[0].Content != "what happened?" {+ t.Fatalf("unknown session ID borrowed identity or policy: %s", messages[0].Content)+ }+}diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.goindex 71f64e14fc..e97fef8679 100644--- a/internal/ai/chat/types.go+++ b/internal/ai/chat/types.go@@ -641,11 +641,11 @@ type ResolvedContext struct {SessionID string `json:"session_id"`- // Resources maps resource names to their resolved information- // Multiple names can point to the same resource (aliases)+ // Resources stores each resolved resource once, keyed by registry identity.+ // Legacy name-keyed JSON is normalized when the derived indexes are rebuilt.Resources map[string]*ResolvedResource `json:"resources"`- // ResourcesByID provides lookup by canonical ResourceID (kind:provider_uid)+ // ResourcesByID provides lookup by canonical ResourceIDResourcesByID map[string]*ResolvedResource `json:"-"` // Not persisted, rebuilt on load// ResourcesByAlias provides lookup by any alias (case-insensitive)@@ -711,6 +711,7 @@ func (rc *ResolvedContext) touch(resourceID string) {// evictExpired removes resources that haven't been accessed within the TTLfunc (rc *ResolvedContext) evictExpired() {+ rc.ensureResourceIndexes()if rc.ttl == 0 {return}@@ -791,21 +792,60 @@ func (rc *ResolvedContext) evictOverflow() {// removeByID removes a resource and all its aliases from the contextfunc (rc *ResolvedContext) removeByID(resourceID string) {- res, ok := rc.ResourcesByID[resourceID]- if !ok {- return- }-- // Remove from primary mapsdelete(rc.ResourcesByID, resourceID)- delete(rc.Resources, res.Name)+ delete(rc.Resources, resourceID)delete(rc.lastAccessed, resourceID)+ delete(rc.explicitlyAccessed, resourceID)+ delete(rc.pinned, resourceID)+ rc.rebuildAliasIndex()+}- // Remove all aliases- for _, alias := range res.Aliases {- delete(rc.ResourcesByAlias, strings.ToLower(alias))+// rebuildAliasIndex keeps only unambiguous aliases. A nil entry reserves a+// duplicated label until one of its distinct owners leaves the context.+func (rc *ResolvedContext) rebuildAliasIndex() {+ rc.ResourcesByAlias = make(map[string]*ResolvedResource)+ for _, res := range rc.ResourcesByID {+ if res == nil {+ continue+ }+ for _, alias := range append(append([]string(nil), res.Aliases...), res.Name) {+ key := strings.ToLower(strings.TrimSpace(alias))+ if key == "" {+ continue+ }+ previous, exists := rc.ResourcesByAlias[key]+ if exists && (previous == nil || previous.ResourceID != res.ResourceID) {+ rc.ResourcesByAlias[key] = nil+ } else {+ rc.ResourcesByAlias[key] = res+ }+ }+ }+}++// ensureResourceIndexes restores derived indexes from old and current JSON.+func (rc *ResolvedContext) ensureResourceIndexes() {+ if rc.ResourcesByID != nil {+ return+ }+ old := rc.Resources+ rc.Resources = make(map[string]*ResolvedResource)+ rc.ResourcesByID = make(map[string]*ResolvedResource)+ for key, res := range old {+ if res == nil {+ continue+ }+ if res.ResourceID == "" {+ res.ResourceID = key+ }+ if res.Name == "" {+ res.Name = key+ }+ rc.Resources[res.ResourceID] = res+ rc.ResourcesByID[res.ResourceID] = res+ rc.touch(res.ResourceID)}- delete(rc.ResourcesByAlias, strings.ToLower(res.Name))+ rc.rebuildAliasIndex()}// PinResource marks a resource as pinned (won't be evicted)@@ -836,6 +876,7 @@ func (rc *ResolvedContext) IsPinned(resourceID string) bool {func (rc *ResolvedContext) Clear(keepPinned bool) {rc.mu.Lock()defer rc.mu.Unlock()+ rc.ensureResourceIndexes()if !keepPinned {rc.Resources = make(map[string]*ResolvedResource)rc.ResourcesByID = make(map[string]*ResolvedResource)@@ -862,18 +903,16 @@ func (rc *ResolvedContext) Clear(keepPinned bool) {for _, resourceID := range toKeep {if res, ok := oldByID[resourceID]; ok {- rc.Resources[res.Name] = res+ rc.Resources[resourceID] = resrc.ResourcesByID[resourceID] = res- for _, alias := range res.Aliases {- rc.ResourcesByAlias[strings.ToLower(alias)] = res- }- rc.ResourcesByAlias[strings.ToLower(res.Name)] = res+if lastAccess, ok := rc.lastAccessed[resourceID]; ok {newLastAccessed[resourceID] = lastAccess}}}rc.lastAccessed = newLastAccessed+ rc.rebuildAliasIndex()}// Stats returns statistics about the context@@ -1017,7 +1056,7 @@ func (rc *ResolvedContext) addResourceInternal(name string, res *ResolvedResourcrc.Resources = make(map[string]*ResolvedResource)}if rc.ResourcesByID == nil {- rc.ResourcesByID = make(map[string]*ResolvedResource)+ rc.ensureResourceIndexes()}if rc.ResourcesByAlias == nil {rc.ResourcesByAlias = make(map[string]*ResolvedResource)@@ -1041,14 +1080,18 @@ func (rc *ResolvedContext) addResourceInternal(name string, res *ResolvedResourc// Evict expired and overflow before addingrc.evictExpired()- rc.Resources[name] = res- rc.ResourcesByID[res.ResourceID] = res- // Index all aliases- for _, alias := range res.Aliases {- rc.ResourcesByAlias[strings.ToLower(alias)] = res+ if res == nil {+ return+ }+ if res.ResourceID == "" {+ res.ResourceID = name}- // Also index the primary name- rc.ResourcesByAlias[strings.ToLower(res.Name)] = res+ if name != "" && name != res.Name {+ res.Aliases = append(res.Aliases, name)+ }+ rc.Resources[res.ResourceID] = res+ rc.ResourcesByID[res.ResourceID] = res+ rc.rebuildAliasIndex()// Always update lastAccessed for LRU/TTL trackingrc.touch(res.ResourceID)@@ -1099,40 +1142,7 @@ func (rc *ResolvedContext) MarkExplicitAccess(resourceID string) {func (rc *ResolvedContext) AddResolvedResource(reg tools.ResourceRegistration) {rc.mu.Lock()defer rc.mu.Unlock()- // Build the canonical resource ID with scope for global uniqueness.- // Format: {kind}:{host}:{provider_uid} for scoped resources- // {kind}:{provider_uid} for global resources (nodes, clusters)- //- // Examples:- // lxc:pve-node:141 (LXC container 141 on node pve-node)- // vm:minipc:203 (VM 203 on node minipc)- // app-container:media-server:abc123 (Docker container on host media-server)- // node:pve-node (Proxmox node - no parent scope)- var resourceID string- if reg.ProviderUID != "" {- // Include host scope for resources that have a parent host- if reg.HostUID != "" || reg.HostName != "" {- hostScope := reg.HostUID- if hostScope == "" {- hostScope = reg.HostName- }- resourceID = reg.Kind + ":" + hostScope + ":" + reg.ProviderUID- } else {- // Global resources (nodes, clusters) don't need host scope- resourceID = reg.Kind + ":" + reg.ProviderUID- }- } else {- // Fallback to name-based ID for backwards compatibility- if reg.HostUID != "" || reg.HostName != "" {- hostScope := reg.HostUID- if hostScope == "" {- hostScope = reg.HostName- }- resourceID = reg.Kind + ":" + hostScope + ":" + reg.Name- } else {- resourceID = reg.Kind + ":" + reg.Name- }- }+ resourceID := reg.ResolvedID()// Build display path from location chainvar displayPath string@@ -1252,7 +1262,7 @@ func (rc *ResolvedContext) getResourceInternal(name string) (*ResolvedResource,return res, true}// Try alias index- if res, ok := rc.ResourcesByAlias[strings.ToLower(name)]; ok {+ if res, ok := rc.ResourcesByAlias[strings.ToLower(strings.TrimSpace(name))]; ok && res != nil {rc.touch(res.ResourceID)return res, true}@@ -1306,8 +1316,8 @@ func (rc *ResolvedContext) GetResolvedResourceByAlias(alias string) (tools.Resol// Evict expired on accessrc.evictExpired()- res, ok := rc.ResourcesByAlias[strings.ToLower(alias)]- if !ok {+ res, ok := rc.ResourcesByAlias[strings.ToLower(strings.TrimSpace(alias))]+ if !ok || res == nil {return nil, false}rc.touch(res.ResourceID)diff --git a/internal/ai/chat/types_identity_test.go b/internal/ai/chat/types_identity_test.gonew file mode 100644index 0000000000..177b550d10--- /dev/null+++ b/internal/ai/chat/types_identity_test.go@@ -0,0 +1,107 @@+package chat++import (+ "encoding/json"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "testing"+ "time"+)++type handoffIdentityRegistry struct {+ *unifiedresources.ResourceRegistry+}++func (p handoffIdentityRegistry) GetByType(t unifiedresources.ResourceType) []unifiedresources.Resource {+ return p.ListByType(t)+}++func TestResolvedContextSameNameOwnersSurvivePersistence(t *testing.T) {+ rc := NewResolvedContext("two-sites")+ for _, id := range []string{"vm-site-a", "vm-site-b"} {+ rc.AddResource("duplicate", &ResolvedResource{ResourceID: id, Name: "duplicate", Kind: "vm", Aliases: []string{"duplicate", "101"}, ResolvedAt: time.Now()})+ }+ if _, ok := rc.GetResource("duplicate"); ok {+ t.Fatal("duplicate name picked an owner")+ }+ if _, ok := rc.GetResolvedResourceByAlias("101"); ok {+ t.Fatal("duplicate native ID picked an owner")+ }+ encoded, err := json.Marshal(rc)+ if err != nil {+ t.Fatal(err)+ }+ var restored ResolvedContext+ if err := json.Unmarshal(encoded, &restored); err != nil {+ t.Fatal(err)+ }+ for _, id := range []string{"vm-site-a", "vm-site-b"} {+ res, ok := restored.GetResourceByID(id)+ if !ok || res.ResourceID != id {+ t.Fatalf("lost owner %s after round trip: %s", id, encoded)+ }+ }+ if _, ok := restored.GetResource("duplicate"); ok {+ t.Fatal("reload revived ambiguous name")+ }+ restored.PinResource("vm-site-b")+ restored.Clear(true)+ if res, ok := restored.GetResource("duplicate"); !ok || res.ResourceID != "vm-site-b" {+ t.Fatal("removing one owner failed to restore the remaining unique alias")+ }+}++func TestResolvedContextCanonicalHandoffDoesNotRebuildProviderIdentity(t *testing.T) {+ rr := unifiedresources.NewRegistry(nil)+ rr.IngestSnapshot(models.StateSnapshot{VMs: []models.VM{+ {ID: "site-a:node1:101", Instance: "site-a", Node: "node1", VMID: 101, Name: "duplicate", Type: "qemu"},+ {ID: "site-b:node1:101", Instance: "site-b", Node: "node1", VMID: 101, Name: "duplicate", Type: "qemu"},+ }})+ rc := NewResolvedContext("two-sites")+ for _, vm := range rr.VMs() {+ reg, ok := tools.CanonicalHandoffResourceRegistration(handoffIdentityRegistry{rr}, vm.ID(), "stale-label", "agent", "wrong-node")+ if !ok || reg.ResourceID != vm.ID() || reg.Kind != "vm" {+ t.Fatalf("client label/type overrode owner: %+v", reg)+ }+ rc.AddResolvedResource(reg)+ rc.MarkExplicitAccess(reg.ResourceID)+ }+ if len(rc.ListResolvedResources()) != 2 {+ t.Fatal("canonical registrations conflated provider scopes")+ }+ for _, vm := range rr.VMs() {+ if res, ok := rc.GetResourceByID(vm.ID()); !ok || res.VMID != 101 || res.Kind != "vm" {+ t.Fatal("canonical ID lost native executor coordinates")+ }+ }+ if _, ok := tools.CanonicalHandoffResourceRegistration(handoffIdentityRegistry{rr}, "vm-missing", "duplicate", "vm", "node1"); ok {+ t.Fatal("unknown explicit ID recovered through display name")+ }+ if _, ok := tools.CanonicalHandoffResourceRegistration(handoffIdentityRegistry{rr}, "vm:node1:101", "duplicate", "vm", "node1"); ok {+ t.Fatal("ambiguous legacy selection picked a site")+ }+ if _, ok := tools.CanonicalHandoffResourceRegistration(handoffIdentityRegistry{rr}, "", "duplicate", "vm", ""); ok {+ t.Fatal("name-only handoff picked a site")+ }+}++func TestResolvedContextReadsLegacyNameKeyedJSON(t *testing.T) {+ old := map[string]any{"session_id": "legacy", "resources": map[string]*ResolvedResource{+ "old-label": {ResourceID: "vm-old", Name: "current-label", Kind: "vm", Aliases: []string{"old-label"}},+ }}+ encoded, err := json.Marshal(old)+ if err != nil {+ t.Fatal(err)+ }+ var rc ResolvedContext+ if err := json.Unmarshal(encoded, &rc); err != nil {+ t.Fatal(err)+ }+ if res, ok := rc.GetResourceByID("vm-old"); !ok || res.Name != "current-label" {+ t.Fatal("legacy context lost its contained resource ID")+ }+ if res, ok := rc.GetResource("old-label"); !ok || res.ResourceID != "vm-old" {+ t.Fatal("legacy alias was not retained")+ }+}diff --git a/internal/ai/tools/current_resource.go b/internal/ai/tools/current_resource.goindex 4311c16765..809c630c29 100644--- a/internal/ai/tools/current_resource.go+++ b/internal/ai/tools/current_resource.go@@ -6,6 +6,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")const currentResourceHandle = agentcapabilities.CurrentResourceHandle@@ -86,8 +87,8 @@ func canonicalQueryIDForResolvedResource(resource ResolvedResourceInfo) string {return ""}for _, candidate := range []string{- resource.GetProviderUID(),resource.GetResourceID(),+ resource.GetProviderUID(),} {if candidate = strings.TrimSpace(candidate); candidate != "" {return candidate@@ -126,38 +127,24 @@ func (e *PulseToolExecutor) commandTargetForResolvedResource(resource ResolvedRereturn "", fmt.Errorf("%s is unavailable because no Pulse resource context is attached to this chat turn", currentResourceHandle)}- candidates := append([]string(nil), resource.GetAliases()...)- candidates = append(candidates,- resource.GetProviderUID(),- resource.GetResourceID(),- resource.GetTargetHost(),- )- seen := make(map[string]struct{}, len(candidates))- for _, candidate := range candidates {- candidate = strings.TrimSpace(candidate)- if candidate == "" {- continue+ if id := strings.TrimSpace(resource.GetResourceID()); id != "" {+ rs, err := e.readStateForControl()+ if err != nil {+ return "", err}- key := strings.ToLower(candidate)- if _, ok := seen[key]; ok {- continue+ loc := unifiedresources.ResolveResourceReferenceContext(rs, id).Location+ if loc.Found && resolvedResourceKindMatchesLocation(resource, loc.ResourceType) {+ return id, nil}- seen[key] = struct{}{}+ return "", fmt.Errorf("%s no longer resolves to its registered resource", currentResourceHandle)+ }+ for _, candidate := range resource.GetAliases() {loc := e.resolveResourceLocation(candidate)- if loc.Found && resolvedResourceKindMatchesLocation(resource, loc.ResourceType) {+ if loc.Found && !loc.Ambiguous && resolvedResourceKindMatchesLocation(resource, loc.ResourceType) {return candidate, nil}}- switch canonicalQueryTypeForResolvedResource(resource) {- case "vm", "system-container":- if providerUID := strings.TrimSpace(resource.GetProviderUID()); providerUID != "" {- return providerUID, nil- }- }- if targetHost := strings.TrimSpace(resource.GetTargetHost()); targetHost != "" {- return targetHost, nil- }return "", fmt.Errorf("%s does not expose a command-capable target", currentResourceHandle)}diff --git a/internal/ai/tools/current_resource_canonquery_test.go b/internal/ai/tools/current_resource_canonquery_test.goindex 941a16cfb8..900eabdeac 100644--- a/internal/ai/tools/current_resource_canonquery_test.go+++ b/internal/ai/tools/current_resource_canonquery_test.go@@ -66,12 +66,12 @@ func TestCanonicalQueryIDForResolvedResource(t *testing.T) {// nil guard.{"nil resource returns empty", nil, ""},- // provider-uid wins.- {"provider uid wins over resource id", &mockResource{+ // Registry identity wins over native provider coordinates.+ {"resource id wins over provider uid", &mockResource{providerUID: "pve1/lxc/141",resourceID: "res-141",aliases: []string{"homepage"},- }, "pve1/lxc/141"},+ }, "res-141"},// falls through to resource-id.{"falls through to resource id when provider uid blank", &mockResource{@@ -110,7 +110,7 @@ func TestCanonicalQueryIDForResolvedResource(t *testing.T) {// trim applied to returned provider uid.{"trims whitespace from provider uid", &mockResource{providerUID: " uid-with-space ",- resourceID: "ignored",+ resourceID: "",}, "uid-with-space"},// trim applied to returned resource id.diff --git a/internal/ai/tools/current_resource_identity_test.go b/internal/ai/tools/current_resource_identity_test.gonew file mode 100644index 0000000000..17eb37ada0--- /dev/null+++ b/internal/ai/tools/current_resource_identity_test.go@@ -0,0 +1,29 @@+package tools++import (+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "testing"+)++func TestCurrentResourceAddressingKeepsTheSelectedCanonicalOwner(t *testing.T) {+ rr := unifiedresources.NewRegistry(nil)+ rr.IngestSnapshot(models.StateSnapshot{VMs: []models.VM{+ {ID: "a:node1:101", Instance: "a", Node: "node1", VMID: 101, Name: "first", Type: "qemu"},+ {ID: "b:node1:101", Instance: "b", Node: "node1", VMID: 101, Name: "second", Type: "qemu"},+ }})+ selected := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeVM, "b", 101)+ resource := &mockResource{resourceID: selected, providerUID: "101", kind: "vm", aliases: []string{"first"}, targetHost: "node1"}+ executor := NewPulseToolExecutor(ExecutorConfig{ReadState: rr})+ target, err := executor.commandTargetForResolvedResource(resource)+ if err != nil || target != selected {+ t.Fatalf("selected owner rebound through provider UID or alias: %q %v", target, err)+ }+ if got := canonicalQueryIDForResolvedResource(resource); got != selected {+ t.Fatalf("selected read uses unscoped ID %s", got)+ }+ resource.resourceID = "vm-unknown"+ if target, err := executor.commandTargetForResolvedResource(resource); err == nil {+ t.Fatalf("missing owner rebound to %s", target)+ }+}diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.goindex d0a1e0a01b..874846cf6e 100644--- a/internal/ai/tools/executor.go+++ b/internal/ai/tools/executor.go@@ -395,6 +395,7 @@ type ResolvedResourceInfo interface {// This structured approach replaces the long parameter list for clarity.type ResourceRegistration struct {// Identity+ ResourceID string // Canonical registry ID, independent of names and native executor coordinatesKind string // Technology/transport kind: "node", "vm", "system-container", "app-container", etc. (drives routing)ProviderUID string // Stable provider ID (container ID, VMID, pod UID)Name string // Primary display name@@ -417,6 +418,26 @@ type ResourceRegistration struct {Executors []ExecutorRegistration}+// ResolvedID preserves the registry identity. The scoped format is retained only+// for legacy discovery providers that do not supply a canonical registry record.+func (reg ResourceRegistration) ResolvedID() string {+ if id := strings.TrimSpace(reg.ResourceID); id != "" {+ return id+ }+ uid := strings.TrimSpace(reg.ProviderUID)+ if uid == "" {+ uid = strings.TrimSpace(reg.Name)+ }+ host := strings.TrimSpace(reg.HostUID)+ if host == "" {+ host = strings.TrimSpace(reg.HostName)+ }+ if host != "" {+ return reg.Kind + ":" + host + ":" + uid+ }+ return reg.Kind + ":" + uid+}+// ExecutorRegistration describes how an executor can reach a resource.type ExecutorRegistration struct {ExecutorID stringdiff --git a/internal/ai/tools/internal_routing.go b/internal/ai/tools/internal_routing.goindex a6e23d1185..503611b26c 100644--- a/internal/ai/tools/internal_routing.go+++ b/internal/ai/tools/internal_routing.go@@ -5,216 +5,13 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")-func (e *PulseToolExecutor) resolveResourceLocation(name string) models.ResourceLocation {+func (e *PulseToolExecutor) resolveResourceLocation(reference string) models.ResourceLocation {rs, err := e.readStateForControl()if err != nil {- return models.ResourceLocation{Found: false, Name: name}+ return models.ResourceLocation{Name: reference}}-- for _, node := range rs.Nodes() {- nodeName := node.Name()- if nodeName == "" {- nodeName = node.NodeName()- }- if unifiedresources.HostnamesEquivalent(nodeName, name) || node.ID() == name {- return models.ResourceLocation{- Found: true,- Name: name,- ResourceType: "node",- Node: nodeName,- TargetHost: nodeName,- }- }- }-- for _, vm := range rs.VMs() {- if vm.Name() == name || vm.ID() == name {- return models.ResourceLocation{- Found: true,- Name: name,- ResourceType: "vm",- VMID: vm.VMID(),- Node: vm.Node(),- TargetHost: vm.Name(),- }- }- }-- for _, lxc := range rs.Containers() {- if lxc.Name() == name || lxc.ID() == name {- return models.ResourceLocation{- Found: true,- Name: name,- ResourceType: "system-container",- VMID: lxc.VMID(),- Node: lxc.Node(),- TargetHost: lxc.Name(),- }- }- }-- for _, dh := range rs.DockerHosts() {- dhName := dh.Hostname()- if unifiedresources.HostnamesEquivalent(dhName, name) || dh.ID() == name {- loc := models.ResourceLocation{- Found: true,- Name: dhName,- ResourceType: "docker-host",- DockerHostName: dhName,- TargetHost: dhName,- }-- // Resolve Docker host parent (system-container or VM)- for _, lxc := range rs.Containers() {- if lxc.Name() == dhName || lxc.ID() == dh.ID() {- loc.DockerHostType = "system-container"- loc.DockerHostVMID = lxc.VMID()- loc.Node = lxc.Node()- break- }- }- if loc.DockerHostType == "" {- for _, vm := range rs.VMs() {- if vm.Name() == dhName || vm.ID() == dh.ID() {- loc.DockerHostType = "vm"- loc.DockerHostVMID = vm.VMID()- loc.Node = vm.Node()- break- }- }- }- if loc.DockerHostType == "" {- loc.DockerHostType = "standalone"- }- return loc- }- }-- for _, dc := range rs.DockerContainers() {- if dc.Name() == name || dc.ID() == name {- dhID := dc.ParentID()- var dhName string- for _, dh := range rs.DockerHosts() {- if dh.ID() == dhID {- dhName = dh.Hostname()- if dhName == "" {- dhName = dh.Name()- }- break- }- }- loc := models.ResourceLocation{- Found: true,- Name: name,- ResourceType: "app-container",- DockerHostName: dhName,- TargetHost: dhName,- }-- // Resolve docker host parent (system-container or VM)- for _, lxc := range rs.Containers() {- if lxc.Name() == dhName || lxc.ID() == dhID || lxc.ID() == dhName {- loc.DockerHostType = "system-container"- loc.DockerHostVMID = lxc.VMID()- loc.Node = lxc.Node()- loc.TargetHost = lxc.Name()- break- }- }- if loc.DockerHostType == "" {- for _, vm := range rs.VMs() {- if vm.Name() == dhName || vm.ID() == dhID || vm.ID() == dhName {- loc.DockerHostType = "vm"- loc.DockerHostVMID = vm.VMID()- loc.Node = vm.Node()- loc.TargetHost = vm.Name()- break- }- }- }- if loc.DockerHostType == "" {- loc.DockerHostType = "standalone"- }- return loc- }- }-- for _, host := range rs.Hosts() {- if unifiedresources.HostnamesEquivalent(host.Hostname(), name) || host.ID() == name {- return models.ResourceLocation{- Found: true,- Name: host.Hostname(),- ResourceType: "agent",- TargetID: host.ID(),- Platform: host.Platform(),- TargetHost: host.Hostname(),- }- }- }-- for _, cluster := range rs.K8sClusters() {- if cluster.Name() == name || cluster.ID() == name {- return models.ResourceLocation{- Found: true,- Name: cluster.Name(),- ResourceType: "k8s-cluster",- K8sClusterName: cluster.Name(),- K8sAgentID: cluster.AgentID(),- TargetHost: cluster.Name(),- AgentID: cluster.AgentID(),- }- }- }-- for _, pod := range rs.Pods() {- if pod.Name() == name || pod.ID() == name {- clusterName := pod.ClusterName()-- agentID := ""- for _, c := range rs.K8sClusters() {- if c.Name() == clusterName {- agentID = c.AgentID()- break- }- }-- return models.ResourceLocation{- Found: true,- Name: pod.Name(),- ResourceType: "k8s-pod",- K8sClusterName: clusterName,- K8sNamespace: pod.Namespace(),- K8sAgentID: agentID,- TargetHost: clusterName,- AgentID: agentID,- }- }- }-- for _, deploy := range rs.K8sDeployments() {- if deploy.Name() == name || deploy.ID() == name {- clusterName := deploy.ClusterName()-- agentID := ""- for _, c := range rs.K8sClusters() {- if c.Name() == clusterName {- agentID = c.AgentID()- break- }- }-- return models.ResourceLocation{- Found: true,- Name: deploy.Name(),- ResourceType: "k8s-deployment",- K8sClusterName: clusterName,- K8sNamespace: deploy.Namespace(),- K8sAgentID: agentID,- TargetHost: clusterName,- AgentID: agentID,- }- }+ if selected := unifiedresources.ResolveResourceReferenceContext(rs, reference); selected.Resource != nil {+ return selected.Location}-- return models.ResourceLocation{Found: false, Name: name}+ return unifiedresources.ResolveResourceContext(rs, reference).Location}diff --git a/internal/ai/tools/internal_routing_identity_test.go b/internal/ai/tools/internal_routing_identity_test.gonew file mode 100644index 0000000000..06b32376ee--- /dev/null+++ b/internal/ai/tools/internal_routing_identity_test.go@@ -0,0 +1,60 @@+package tools++import (+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+ "testing"+)++func TestCanonicalCommandTargetKeepsProviderScopedParent(t *testing.T) {+ rr := unifiedresources.NewRegistry(nil)+ records := []unifiedresources.Resource{}+ for _, instance := range []string{"cluster-a", "cluster-b"} {+ nodeID := "node-" + instance+ guestID := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeVM, instance, 101)+ records = append(records,+ unifiedresources.Resource{ID: nodeID, Type: unifiedresources.ResourceTypeAgent, Name: "node1", Sources: []unifiedresources.DataSource{unifiedresources.SourceProxmox, unifiedresources.SourceAgent}, Proxmox: &unifiedresources.ProxmoxData{Instance: instance, NodeName: "node1", SourceID: instance + ":node1"}, Agent: &unifiedresources.AgentData{AgentID: "native-" + instance, Hostname: "node1", CommandsEnabled: true}},+ unifiedresources.Resource{ID: guestID, Type: unifiedresources.ResourceTypeVM, Name: "duplicate", Sources: []unifiedresources.DataSource{unifiedresources.SourceProxmox}, ParentID: &nodeID, Proxmox: &unifiedresources.ProxmoxData{Instance: instance, NodeName: "node1", VMID: 101, SourceID: instance + ":node1:101"}},+ )+ }+ rr.IngestResources(records)+ if len(rr.VMs()) != 2 || len(rr.Nodes()) != 2 {+ t.Fatalf("fixture conflated provider scopes: VMs=%d nodes=%d", len(rr.VMs()), len(rr.Nodes()))+ }+ server := &mockAgentServer{agents: []agentexec.ConnectedAgent{{AgentID: "native-cluster-a", Hostname: "node1"}, {AgentID: "native-cluster-b", Hostname: "node1"}}}+ executor := NewPulseToolExecutor(ExecutorConfig{ReadState: rr, AgentServer: server})+ for _, instance := range []string{"cluster-a", "cluster-b"} {+ id := unifiedresources.ProxmoxGuestCanonicalID(unifiedresources.ResourceTypeVM, instance, 101)+ result := executor.resolveTargetForCommandFull(id)+ if result.AgentID != "native-"+instance || result.TargetID != "101" || result.Transport != "qm_guest_exec" {+ t.Fatalf("canonical guest routed through another provider: %s %+v", instance, result)+ }+ }+ if id := executor.findAgentForNode("node1"); id != "" {+ t.Fatalf("ambiguous legacy node name selected %s", id)+ }+}++func TestAmbiguousResourceNameCannotFallBackToConnectedHostname(t *testing.T) {+ rr := unifiedresources.NewRegistry(nil)+ rr.IngestSnapshot(models.StateSnapshot{VMs: []models.VM{+ {ID: "cluster-a:node1:101", Instance: "cluster-a", Node: "node1", VMID: 101, Name: "duplicate", Type: "qemu"},+ {ID: "cluster-b:node1:101", Instance: "cluster-b", Node: "node1", VMID: 101, Name: "duplicate", Type: "qemu"},+ }})+ executor := NewPulseToolExecutor(ExecutorConfig{ReadState: rr, AgentServer: &mockAgentServer{agents: []agentexec.ConnectedAgent{{AgentID: "other", Hostname: "duplicate"}}}})+ result := executor.resolveTargetForCommandFull("duplicate")+ if result.AgentID != "" || result.ResolvedKind != "ambiguous" {+ t.Fatalf("known ambiguity escaped topology ownership: %+v", result)+ }+}++func TestKnownAgentIDCannotRouteToAnImpostorHostname(t *testing.T) {+ rr := unifiedresources.NewRegistry(nil)+ rr.IngestSnapshot(models.StateSnapshot{Hosts: []models.Host{{ID: "native-target", Hostname: "target", CommandsEnabled: true}}})+ executor := NewPulseToolExecutor(ExecutorConfig{ReadState: rr, AgentServer: &mockAgentServer{agents: []agentexec.ConnectedAgent{{AgentID: "different-agent", Hostname: "target"}}}})+ result := executor.resolveTargetForCommandFull(rr.Hosts()[0].ID())+ if result.AgentID != "" || result.ResolvedKind != "agent" {+ t.Fatalf("a known agent ID was rebound by hostname: %+v", result)+ }+}diff --git a/internal/ai/tools/strict_resolution_test.go b/internal/ai/tools/strict_resolution_test.goindex 73d22c80d7..99d13377e3 100644--- a/internal/ai/tools/strict_resolution_test.go+++ b/internal/ai/tools/strict_resolution_test.go@@ -326,6 +326,10 @@ func (m *mockResolvedContext) AddResolvedResource(reg ResourceRegistration) {resourceID = strings.TrimSpace(reg.Name)}+ if reg.ResourceID != "" {+ resourceID = reg.ResourceID+ }+resource := &mockResource{resourceID: resourceID,resourceType: reg.Kind,diff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.goindex d16abbae78..22fb7daeb0 100644--- a/internal/ai/tools/tools_control.go+++ b/internal/ai/tools/tools_control.go@@ -193,23 +193,52 @@ func (e *PulseToolExecutor) resolveTargetForCommandFull(targetHost string) Comma// This prevents hostname collisions from masquerading as host targets.loc := e.resolveResourceLocation(targetHost)+ if loc.Ambiguous {+ result.ResolvedKind = "ambiguous"+ return result+ }+ nodeAgent := func() string {+ if loc.AgentID != "" {+ for _, agent := range agents {+ if agent.AgentID == loc.AgentID {+ return agent.AgentID+ }+ }+ return ""+ }+ reference := loc.NodeResourceID+ if reference == "" {+ reference = loc.Node+ }+ return e.findAgentForNode(reference)+ }if loc.Found {result.ResolvedKind = loc.ResourceType// Route based on resource typeswitch loc.ResourceType {case "agent":- for _, agent := range agents {- if unifiedresources.HostnamesEquivalent(agent.Hostname, loc.TargetHost) || agent.AgentID == loc.TargetID {- result.AgentID = agent.AgentID- result.AgentHostname = agent.Hostname- result.ResolvedKind = "agent"- return result- }+ reference := loc.AgentID+ if reference == "" {+ reference = loc.TargetID+ }+ if reference == "" {+ reference = loc.TargetHost+ }+ var agent agentexec.ConnectedAgent+ var ok bool+ if loc.AgentID != "" || loc.TargetID != "" {+ agent, ok = connectedAgentByID(agents, reference)+ } else {+ agent, ok = uniqueConnectedAgent(agents, reference)}+ if ok {+ result.AgentID, result.AgentHostname = agent.AgentID, agent.Hostname+ }+ return resultcase "node":// Direct hypervisor node- nodeAgentID := e.findAgentForNode(loc.Node)+ nodeAgentID := nodeAgent()result.AgentID = nodeAgentIDresult.ResolvedKind = "node"result.ResolvedNode = loc.Node@@ -223,7 +252,7 @@ func (e *PulseToolExecutor) resolveTargetForCommandFull(targetHost string) Commacase "system-container":// System container - route through node agent via pct exec- nodeAgentID := e.findAgentForNode(loc.Node)+ nodeAgentID := nodeAgent()result.ResolvedKind = "system-container"result.ResolvedNode = loc.Noderesult.TargetType = "container"@@ -242,7 +271,7 @@ func (e *PulseToolExecutor) resolveTargetForCommandFull(targetHost string) Commacase "vm":// VM - route through node agent via qm guest exec- nodeAgentID := e.findAgentForNode(loc.Node)+ nodeAgentID := nodeAgent()result.ResolvedKind = "vm"result.ResolvedNode = loc.Noderesult.TargetType = "vm"@@ -265,7 +294,7 @@ func (e *PulseToolExecutor) resolveTargetForCommandFull(targetHost string) Commaresult.ResolvedNode = loc.Nodeif loc.DockerHostType == "system-container" {- nodeAgentID := e.findAgentForNode(loc.Node)+ nodeAgentID := nodeAgent()result.TargetType = "container"result.TargetID = fmt.Sprintf("%d", loc.DockerHostVMID)result.Transport = "pct_exec"@@ -281,7 +310,7 @@ func (e *PulseToolExecutor) resolveTargetForCommandFull(targetHost string) Commareturn result}if loc.DockerHostType == "vm" {- nodeAgentID := e.findAgentForNode(loc.Node)+ nodeAgentID := nodeAgent()result.TargetType = "vm"result.TargetID = fmt.Sprintf("%d", loc.DockerHostVMID)result.Transport = "qm_guest_exec"@@ -296,29 +325,30 @@ func (e *PulseToolExecutor) resolveTargetForCommandFull(targetHost string) Comma}return result}- // Standalone Docker host - find agent directly- for _, agent := range agents {- if unifiedresources.HostnamesEquivalent(agent.Hostname, loc.TargetHost) || agent.AgentID == loc.TargetHost {- result.AgentID = agent.AgentID- result.AgentHostname = agent.Hostname- return result- }+ // Standalone parents keep an explicit agent identity when available.+ reference := loc.AgentID+ if reference == "" {+ reference = loc.TargetHost+ }+ var agent agentexec.ConnectedAgent+ var ok bool+ if loc.AgentID != "" {+ agent, ok = connectedAgentByID(agents, reference)+ } else {+ agent, ok = uniqueConnectedAgent(agents, reference)}+ if ok {+ result.AgentID, result.AgentHostname = agent.AgentID, agent.Hostname+ }+}// A known resource must never fall through to a different hostname match.return result}- // STEP 2: FALLBACK — agent hostname match.- // Only used when the state doesn't know about this resource at all.- // This handles standalone hosts without Proxmox topology.- for _, agent := range agents {- if unifiedresources.HostnamesEquivalent(agent.Hostname, targetHost) || agent.AgentID == targetHost {- result.AgentID = agent.AgentID- result.AgentHostname = agent.Hostname- result.ResolvedKind = "agent"- return result- }+ // A connected agent absent from the inventory is a bounded legacy boundary.+ if agent, ok := uniqueConnectedAgent(agents, targetHost); ok {+ result.AgentID, result.AgentHostname, result.ResolvedKind = agent.AgentID, agent.Hostname, "agent"}return result@@ -356,50 +386,121 @@ func (e *PulseToolExecutor) readStateForControl() (unifiedresources.ReadState, ereturn nil, fmt.Errorf("read state not available")}-func (e *PulseToolExecutor) findAgentForNode(nodeName string) string {- if e.agentServer == nil {- return ""+func connectedAgentByID(agents []agentexec.ConnectedAgent, id string) (agentexec.ConnectedAgent, bool) {+ if id != "" {+ for _, agent := range agents {+ if agent.AgentID == id {+ return agent, true+ }+ }}+ return agentexec.ConnectedAgent{}, false+}- agents := e.agentServer.GetConnectedAgents()+func uniqueConnectedAgent(agents []agentexec.ConnectedAgent, reference string) (agentexec.ConnectedAgent, bool) {+ if strings.TrimSpace(reference) == "" {+ return agentexec.ConnectedAgent{}, false+ }for _, agent := range agents {- if unifiedresources.HostnamesEquivalent(agent.Hostname, nodeName) {- return agent.AgentID+ if agent.AgentID == reference {+ return agent, true}}+ var result agentexec.ConnectedAgent+ found := false+ for _, agent := range agents {+ if !unifiedresources.HostnamesEquivalent(agent.Hostname, reference) {+ continue+ }+ if found && result.AgentID != agent.AgentID {+ return agentexec.ConnectedAgent{}, false+ }+ result, found = agent, true+ }+ return result, found+}+func (e *PulseToolExecutor) findAgentForNode(reference string) string {+ if e.agentServer == nil {+ return ""+ }+ agents := e.agentServer.GetConnectedAgents()rs, err := e.readStateForControl()if err != nil {+ if agent, found := uniqueConnectedAgent(agents, reference); found {+ return agent.AgentID+ }return ""}-- // Map linked node IDs to node names for quick lookup.- nodeNamesByID := make(map[string]string)+ var nodeID, hostname stringfor _, node := range rs.Nodes() {- name := node.Name()- if name == "" {- name = node.NodeName()+ if node != nil && node.ID() == reference {+ nodeID, hostname = node.ID(), node.NodeName()+ break}- if node.ID() != "" {- nodeNamesByID[node.ID()] = name+ }+ if nodeID == "" {+ for _, node := range rs.Nodes() {+ if node == nil || !unifiedresources.HostnamesEquivalent(node.NodeName(), reference) {+ continue+ }+ if nodeID != "" && nodeID != node.ID() {+ return ""+ }+ nodeID, hostname = node.ID(), node.NodeName()}}-+ if nodeID == "" {+ if agent, found := uniqueConnectedAgent(agents, reference); found {+ return agent.AgentID+ }+ return ""+ }+ owned := unifiedresources.ResolveResourceContext(rs, nodeID)+ if owned.Resource != nil && owned.Resource.Agent != nil && owned.Resource.Agent.AgentID != "" {+ for _, agent := range agents {+ if agent.AgentID == owned.Resource.Agent.AgentID {+ return agent.AgentID+ }+ }+ return ""+ }+ candidate := ""for _, host := range rs.Hosts() {- linked := host.LinkedNodeID()- if linked == "" {+ if host == nil || host.LinkedNodeID() == "" {continue}- if !unifiedresources.HostnamesEquivalent(nodeNamesByID[linked], nodeName) {+ linkedID := host.LinkedNodeID()+ if resolver, ok := rs.(unifiedresources.ReferenceReadState); ok {+ _, id, found := resolver.GetByReference(linkedID)+ if found {+ linkedID = id+ }+ }+ if linkedID != nodeID {continue}- for _, agent := range agents {- if unifiedresources.HostnamesEquivalent(agent.Hostname, host.Hostname()) || agent.AgentID == host.ID() {- return agent.AgentID- }+ agent, found := connectedAgentByID(agents, host.AgentID())+ if !found {+ continue+ }+ if candidate != "" && candidate != agent.AgentID {+ return ""}+ candidate = agent.AgentID+ }+ if candidate != "" {+ return candidate+ }+ // A hostname can route an old unlinked node only when both sides are unique.+ for _, node := range rs.Nodes() {+ if node != nil && node.ID() != nodeID && unifiedresources.HostnamesEquivalent(node.NodeName(), hostname) {+ return ""+ }+ }+ if agent, found := uniqueConnectedAgent(agents, hostname); found {+ return agent.AgentID}-return ""}diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.goindex b0cf532ecb..4d178151bb 100644--- a/internal/ai/tools/tools_query.go+++ b/internal/ai/tools/tools_query.go@@ -1731,32 +1731,7 @@ func (e *PulseToolExecutor) registerResolvedResourceWithExplicitAccess(reg Resou}e.resolvedContext.AddResolvedResource(reg)- // Build the resource ID to mark explicit access (must match AddResolvedResource format)- // Format: {kind}:{host}:{provider_uid} for scoped resources- // {kind}:{provider_uid} for global resources- var resourceID string- if reg.ProviderUID != "" {- if reg.HostUID != "" || reg.HostName != "" {- hostScope := reg.HostUID- if hostScope == "" {- hostScope = reg.HostName- }- resourceID = reg.Kind + ":" + hostScope + ":" + reg.ProviderUID- } else {- resourceID = reg.Kind + ":" + reg.ProviderUID- }- } else {- if reg.HostUID != "" || reg.HostName != "" {- hostScope := reg.HostUID- if hostScope == "" {- hostScope = reg.HostName- }- resourceID = reg.Kind + ":" + hostScope + ":" + reg.Name- } else {- resourceID = reg.Kind + ":" + reg.Name- }- }- e.resolvedContext.MarkExplicitAccess(resourceID)+ e.resolvedContext.MarkExplicitAccess(reg.ResolvedID())}// ValidationResult holds the result of resource validation.@@ -2646,6 +2621,7 @@ func canonicalAgentRegistration(resource unifiedresources.Resource) (ResourceRegadapter = "direct"}return ResourceRegistration{+ ResourceID: resource.ID,Kind: "agent",ProviderUID: providerUID,Name: name,@@ -2711,6 +2687,7 @@ func canonicalStorageRegistration(resource unifiedresources.Resource) (ResourceRexecutorID := firstNonEmptyString(canonicalStorageHost(resource), name, providerUID)return ResourceRegistration{+ ResourceID: resource.ID,Kind: "storage",ProviderUID: providerUID,Name: name,@@ -2735,44 +2712,57 @@ func canonicalHandoffUnifiedResource(provider UnifiedResourceProvider, resourceIif provider == nil {return unifiedresources.Resource{}, "", false}-- refs := appendUniqueStrings(nil, resourceID, resourceName)- normalizedType := strings.TrimSpace(strings.ToLower(resourceType))- switch normalizedType {- case "node":- normalizedType = "agent"- case "physical-disk":- normalizedType = "physical_disk"- }-- switch normalizedType {- case "agent", "docker-host":- refs = appendUniqueStrings(refs, node)- if resource, ok := findCanonicalResourceByReference(provider.GetByType(unifiedresources.ResourceTypeAgent), refs...); ok {- return resource, normalizedType, true- }- case "vm":- if resource, ok := findCanonicalGuestResourceByReferences(provider, "vm", refs...); ok {- return resource, normalizedType, true- }- case "system-container", "lxc":- if resource, ok := findCanonicalGuestResourceByReferences(provider, "system-container", refs...); ok {- return resource, normalizedType, true+ resourceID = strings.TrimSpace(resourceID)+ if rs, ok := provider.(unifiedresources.ReferenceReadState); ok {+ var resolved unifiedresources.ResolvedResourceContext+ if resourceID != "" {+ resolved = unifiedresources.ResolveResourceReferenceContext(rs, resourceID)+ } else {+ resolved = unifiedresources.ResolveResourceContext(rs, resourceName)}- case "app-container":- if resource, ok := findCanonicalAppContainerResourceByReferences(provider, refs...); ok {- return resource, normalizedType, true+ if resolved.Resource != nil {+ return *resolved.Resource, string(unifiedresources.ContractResourceType(*resolved.Resource)), true}- case "storage":- if resource, ok := findCanonicalResourceByReference(canonicalStoragePoolResources(provider), refs...); ok {- return resource, normalizedType, true+ }+ // Minimal read providers have no reference index. Match an explicit ID exactly+ // across their records and never substitute a client label or node.+ ref := resourceID+ if ref == "" {+ ref = strings.TrimSpace(resourceName)+ }+ if ref == "" {+ return unifiedresources.Resource{}, "", false+ }+ var found *unifiedresources.Resource+ for _, kind := range canonicalHandoffFallbackResourceTypes {+ for _, resource := range provider.GetByType(kind) {+ matches := resource.ID == ref+ if resource.Proxmox != nil && strings.TrimSpace(resource.Proxmox.SourceID) == ref {+ matches = true+ }+ if reg, ok := canonicalResourceRegistration(resource); ok {+ reg.ResourceID = ""+ if reg.ResolvedID() == ref {+ matches = true+ }+ }+ if resourceID == "" {+ matches = strings.EqualFold(resourceDisplayName(resource), ref) || strings.EqualFold(resource.Name, ref)+ }+ if !matches {+ continue+ }+ if found != nil && found.ID != resource.ID {+ return unifiedresources.Resource{}, "", false+ }+ copy := resource+ found = ©}}- if resource, ok := findCanonicalHandoffResourceByAnyType(provider, refs...); ok {- return resource, string(unifiedresources.ContractResourceType(resource)), true+ if found == nil {+ return unifiedresources.Resource{}, "", false}-- return unifiedresources.Resource{}, normalizedType, false+ return *found, string(unifiedresources.ContractResourceType(*found)), true}var canonicalHandoffFallbackResourceTypes = []unifiedresources.ResourceType{@@ -2842,17 +2832,21 @@ func findCanonicalHandoffResourceByAnyType(provider UnifiedResourceProvider, ref// unified provider, because invented registrations would bypass capability and// executor policy.func CanonicalHandoffResourceRegistration(provider UnifiedResourceProvider, resourceID, resourceName, resourceType, node string) (ResourceRegistration, bool) {- resource, normalizedType, ok := canonicalHandoffUnifiedResource(provider, resourceID, resourceName, resourceType, node)+ resource, _, ok := canonicalHandoffUnifiedResource(provider, resourceID, resourceName, resourceType, node)if !ok {return ResourceRegistration{}, false}- switch normalizedType {- case "agent", "docker-host":+ return canonicalResourceRegistration(resource)+}++func canonicalResourceRegistration(resource unifiedresources.Resource) (ResourceRegistration, bool) {+ switch string(unifiedresources.ContractResourceType(resource)) {+ case "agent":return canonicalAgentRegistration(resource)case "vm":return canonicalGuestRegistration("vm", resource)- case "system-container", "lxc":+ case "system-container":return canonicalGuestRegistration("system-container", resource)case "app-container":return resolvedAppContainerRegistration(resource)@@ -3101,6 +3095,7 @@ func guestViewGetResult[V queryGuestView](e *PulseToolExecutor, guests []V, kind// Register in resolved context WITH explicit access (single-resource get operation)e.registerResolvedResourceWithExplicitAccess(ResourceRegistration{+ ResourceID: g.ID(),Kind: kind,ProviderUID: fmt.Sprintf("%d", g.VMID()), // VMID is the stable provider IDName: g.Name(),@@ -3240,6 +3235,7 @@ func canonicalGuestRegistration(kind string, resource unifiedresources.Resource)host := canonicalGuestTarget(resource)aliases := appendUniqueStrings(nil, canonicalGuestSearchCandidates(kind, resource)...)reg := ResourceRegistration{+ ResourceID: resource.ID,Kind: kind,ProviderUID: providerUID,Name: name,@@ -3483,6 +3479,7 @@ func resolvedAppContainerRegistration(resource unifiedresources.Resource) (Resou}reg := ResourceRegistration{+ ResourceID: resource.ID,Kind: "app-container",ProviderUID: containerID,Name: name,diff --git a/internal/models/state_snapshot.go b/internal/models/state_snapshot.goindex 7c7c26ad70..1486d5540c 100644--- a/internal/models/state_snapshot.go+++ b/internal/models/state_snapshot.go@@ -373,6 +373,10 @@ func (s *State) GetLastUpdate() time.Time {// ResourceLocation describes where a resource lives in the infrastructure hierarchy.// This is the authoritative source of truth for routing commands to resources.type ResourceLocation struct {+ // Ambiguous refuses a known label shared by different resource identities.+ Ambiguous bool+ // NodeResourceID keeps command routing scoped to the owned parent node.+ NodeResourceID string// What was foundFound bool // True if the resource was foundName string // The resource namediff --git a/internal/unifiedresources/monitor_adapter.go b/internal/unifiedresources/monitor_adapter.goindex e826bd1e72..732e1de1c9 100644--- a/internal/unifiedresources/monitor_adapter.go+++ b/internal/unifiedresources/monitor_adapter.go@@ -229,6 +229,15 @@ func (a *MonitorAdapter) currentRegistry() *ResourceRegistry {return registry}+// GetByReference delegates identity and alias resolution to the current registry.+func (a *MonitorAdapter) GetByReference(reference string) (*Resource, string, bool) {+ registry := a.currentRegistry()+ if registry == nil {+ return nil, "", false+ }+ return registry.GetByReference(reference)+}+// RecordChange forwards canonical resource-history events into the underlying// resource store when monitoring has a durable store attached. Alert lifecycle// events carry source-native references (Proxmox node and guest IDs, agentdiff --git a/internal/unifiedresources/monitor_adapter_read_state_test.go b/internal/unifiedresources/monitor_adapter_read_state_test.goindex 477db0bb98..409db9ff6e 100644--- a/internal/unifiedresources/monitor_adapter_read_state_test.go+++ b/internal/unifiedresources/monitor_adapter_read_state_test.go@@ -1328,3 +1328,29 @@ func TestMonitorRebuildJudgesLinkChainsOverTheAssembledEstate(t *testing.T) {t.Fatalf("staged ingest kept the TrueNAS VM, so this fixture no longer separates the rebuild from per-call passes")}}++func TestMonitorAdapterReferenceTracksPublishedRegistry(t *testing.T) {+ adapter := NewMonitorAdapter(NewRegistry(NewMemoryStore()))+ adapter.PopulateFromSnapshot(models.StateSnapshot{VMs: []models.VM{+ {ID: "site-a:node1:101", Instance: "site-a", Node: "node1", VMID: 101, Name: "before", Type: "qemu"},+ }})+ ownerID := adapter.VMs()[0].ID()+ previous := adapter.currentRegistry()+ adapter.PopulateFromSnapshot(models.StateSnapshot{VMs: []models.VM{+ {ID: "site-a:node2:101", Instance: "site-a", Node: "node2", VMID: 101, Name: "shared-name", Type: "qemu"},+ {ID: "site-b:node2:101", Instance: "site-b", Node: "node2", VMID: 101, Name: "shared-name", Type: "qemu"},+ }})+ if adapter.currentRegistry() == previous {+ t.Fatal("snapshot did not publish a new registry generation")+ }+ resource, resolvedID, ok := adapter.GetByReference(ownerID)+ if !ok || resource == nil || resolvedID != ownerID {+ t.Fatalf("selected owner lost after publication: resource=%+v id=%q ok=%v", resource, resolvedID, ok)+ }+ if resource.Name != "shared-name" || resource.Proxmox == nil || resource.Proxmox.Instance != "site-a" || resource.Proxmox.NodeName != "node2" {+ t.Fatalf("selected owner has stale or cross-site facts: %+v", resource)+ }+ if _, _, ok := adapter.GetByReference("missing-owner"); ok {+ t.Fatal("unknown selection acquired an owner")+ }+}diff --git a/internal/unifiedresources/read_state.go b/internal/unifiedresources/read_state.goindex 79d640bb08..190b9c07e0 100644--- a/internal/unifiedresources/read_state.go+++ b/internal/unifiedresources/read_state.go@@ -4,8 +4,8 @@ package unifiedresources//// This is the interface that internal consumers (AI, Patrol, API handlers)// should depend on instead of models.StateSnapshot. It exposes only typed-// view accessors — generic methods (ListByType, List, Get) remain on-// ResourceRegistry only.+// view accessors. Explicit selection uses the ReferenceReadState capability;+// raw enumeration methods (ListByType, List, Get) remain on ResourceRegistry.//// All accessor methods return cached, pre-sorted slices that are O(1) to// read. The cache is invalidated and lazily rebuilt after each@@ -40,3 +40,14 @@ type ReadState interface {Workloads() []*WorkloadView // Canonical runtime workloads (VMs, system containers, app containers)Infrastructure() []*InfrastructureView // All infrastructure parent resources}++// ReferenceReadState resolves explicit resource references through the registry.+// It preserves declared successions and refuses ambiguous aliases. Production+// read-state providers implement this capability without exposing a raw list.+type ReferenceReadState interface {+ ReadState+ GetByReference(string) (*Resource, string, bool)+}++var _ ReferenceReadState = (*ResourceRegistry)(nil)+var _ ReferenceReadState = (*MonitorAdapter)(nil)diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.goindex c9f6b6b59c..00cc540bec 100644--- a/internal/unifiedresources/registry.go+++ b/internal/unifiedresources/registry.go@@ -4227,9 +4227,16 @@ func (rr *ResourceRegistry) mergeInto(existing *Resource, incoming Resource, souexisting.Metrics = mergeMetrics(existing, existing.Metrics, incoming.Metrics, source, now, existing.SourceStatus, rr.ingestStaleThresholds)existing.Metrics = clearUnavailableSourceMemoryMetric(existing.Metrics, &incoming, source)- // Prefer agent naming when available+ // The current highest-priority source owns the name. Agent naming wins+ // when an agent is present, while standalone provider names keep refreshing.if incoming.Name != "" {- if existing.Name == "" || sourcePriority(source) >= sourcePriority(SourceAgent) {+ namingPriority := 0+ for _, existingSource := range existing.Sources {+ if priority := sourcePriority(existingSource); priority > namingPriority {+ namingPriority = priority+ }+ }+ if existing.Name == "" || sourcePriority(source) >= namingPriority {existing.Name = incoming.Name}}diff --git a/internal/unifiedresources/registry_materialization_test.go b/internal/unifiedresources/registry_materialization_test.goindex daa5ac0cde..4211ce25ad 100644--- a/internal/unifiedresources/registry_materialization_test.go+++ b/internal/unifiedresources/registry_materialization_test.go@@ -221,10 +221,9 @@ func TestRegistryMaterializedMetadataViewsKeepFreshness(t *testing.T) {// No batch epilogue has run here; source mapping and typed view must already// reflect the resource visible to List and point reads.current := rr.VMs()[0]- // Proxmox naming does not displace an existing non-empty name under the- // established source-priority rule. Pin the actual fresh status and CPU,- // not an invented rename guarantee.- if current.ID() != before.ID() || current.Status() != StatusOnline || current.CPUPercent() != 73.25 || current.Name() != before.Name() {+ // The standalone provider owns its current name, status and CPU sample.+ // Detached older views stay unchanged while fresh readers see the rename.+ if current.ID() != before.ID() || current.Status() != StatusOnline || current.CPUPercent() != 73.25 || current.Name() != "renamed-vm" {t.Fatalf("mid-batch view: id=%q status=%s cpu=%v name=%q", current.ID(), current.Status(), current.CPUPercent(), current.Name())}assertRegistryMetadataOracle(t, rr)diff --git a/internal/unifiedresources/registry_name_authority_test.go b/internal/unifiedresources/registry_name_authority_test.gonew file mode 100644index 0000000000..90d170e7c7--- /dev/null+++ b/internal/unifiedresources/registry_name_authority_test.go@@ -0,0 +1,46 @@+package unifiedresources++import (+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "testing"+)++func TestProviderRenameKeepsCanonicalIdentityAndRefreshesName(t *testing.T) {+ rr := NewRegistry(nil)+ rr.IngestSnapshot(models.StateSnapshot{VMs: []models.VM{{ID: "cluster-a:old-node:101", Instance: "cluster-a", Node: "old-node", VMID: 101, Name: "before", Type: "qemu"}}})+ id := rr.VMs()[0].ID()+ rr.IngestSnapshot(models.StateSnapshot{VMs: []models.VM{{ID: "cluster-a:new-node:101", Instance: "cluster-a", Node: "new-node", VMID: 101, Name: "after", Type: "qemu"}}})+ resource, ownedID, found := rr.GetByReference(id)+ if !found || ownedID != id || resource.Name != "after" || resource.Proxmox.NodeName != "new-node" {+ t.Fatalf("provider rename lost current owned identity: resource=%+v id=%s found=%v", resource, ownedID, found)+ }+ if resource.Canonical == nil || resource.Canonical.DisplayName != "after" {+ t.Fatalf("canonical display did not refresh: %+v", resource.Canonical)+ }+}++func TestProviderRenamePreservesPresentAgentNameAuthority(t *testing.T) {+ store := NewMemoryStore()+ rr := NewRegistry(nil)+ snapshot := models.StateSnapshot{+ VMs: []models.VM{{ID: "cluster-a:node1:101", Instance: "cluster-a", Node: "node1", VMID: 101, Name: "provider-name", Type: "qemu"}},+ Hosts: []models.Host{{ID: "native-agent", Hostname: "agent-name", Status: "online", Platform: "linux"}},+ }+ rr.IngestSnapshot(snapshot)+ guestID, agentID := rr.VMs()[0].ID(), rr.Hosts()[0].ID()+ if err := store.AddLink(ResourceLink{ResourceA: guestID, ResourceB: agentID, PrimaryID: guestID}); err != nil {+ t.Fatal(err)+ }+ rr = NewRegistry(store)+ rr.IngestSnapshot(snapshot)+ before, _, found := rr.GetByReference(guestID)+ if !found || before.Agent == nil {+ t.Fatal("fixture did not attach an agent to the guest")+ }+ provider, _ := resourceFromVM(models.VM{ID: "cluster-a:node1:101", Instance: "cluster-a", Node: "node1", VMID: 101, Name: "provider-renamed", Type: "qemu"})+ rr.IngestRecords(SourceProxmox, []IngestRecord{{SourceID: "cluster-a:node1:101", Resource: provider}})+ after, _, found := rr.GetByReference(guestID)+ if !found || after.ID != guestID || after.Agent == nil || after.Name != before.Name {+ t.Fatalf("provider rename displaced present agent authority: before=%+v after=%+v", before, after)+ }+}diff --git a/internal/unifiedresources/resolve.go b/internal/unifiedresources/resolve.goindex 1daa8d67c4..fe68106451 100644--- a/internal/unifiedresources/resolve.go+++ b/internal/unifiedresources/resolve.go@@ -11,219 +11,7 @@ import (// of models.StateSnapshot.ResolveResource and is the preferred path for// consumer packages that have been migrated away from direct state access.func ResolveResource(rs ReadState, name string) models.ResourceLocation {- name = strings.TrimSpace(name)- if rs == nil {- return models.ResourceLocation{Found: false, Name: name}- }- if name == "" {- return models.ResourceLocation{Found: false, Name: name}- }-- // Check Proxmox nodes first.- // Match on NodeName() (raw Proxmox name) for parity with state.Nodes[].Name.- for _, node := range rs.Nodes() {- if node == nil {- continue- }- nodeName := node.NodeName()- if nodeName == name {- return models.ResourceLocation{- Found: true,- Name: name,- ResourceType: "node",- Node: nodeName,- TargetHost: nodeName,- }- }- }-- // Check VMs.- for _, vm := range rs.VMs() {- if vm == nil {- continue- }- if vm.Name() == name {- return models.ResourceLocation{- Found: true,- Name: name,- ResourceType: "vm",- VMID: vm.VMID(),- Node: vm.Node(),- TargetHost: vm.Name(),- }- }- }-- // Check system containers (LXC/Incus).- for _, ct := range rs.Containers() {- if ct == nil {- continue- }- if ct.Name() == name {- return models.ResourceLocation{- Found: true,- Name: name,- ResourceType: "system-container",- VMID: ct.VMID(),- Node: ct.Node(),- TargetHost: ct.Name(),- }- }- }-- // Check Docker hosts (system-containers/VMs/standalone hosts running Docker).- // Match on Hostname() or HostSourceID() for parity with state.DockerHosts[].Hostname/ID.- // Note: Docker HOST lookups do NOT rewrite TargetHost — it stays as hostname.- for _, dh := range rs.DockerHosts() {- if dh == nil {- continue- }- if dh.Hostname() == name || dh.HostSourceID() == name {- loc := models.ResourceLocation{- Found: true,- Name: dh.Hostname(),- ResourceType: "docker-host",- DockerHostName: dh.Hostname(),- TargetHost: dh.Hostname(),- }- resolveDockerHostParent(rs, dh.Hostname(), dh.HostSourceID(), false, &loc)- return loc- }- }-- // Check Docker containers — flat list, resolve parent host.- // Docker CONTAINER lookups DO rewrite TargetHost to the backing guest name.- for _, resource := range appContainerResourcesFromReadState(rs) {- if !appContainerResourceMatches(resource, name) {- continue- }- loc := models.ResourceLocation{- Found: true,- Name: name,- ResourceType: "app-container",- }- populateAppContainerLocation(rs, resource, &loc)- return loc- }-- // Check storage pools, including VMware datastores and shared platform storage.- for _, pool := range rs.StoragePools() {- if pool == nil {- continue- }- if !storagePoolMatches(pool, name) {- continue- }- targetID := storagePoolTarget(pool)- return models.ResourceLocation{- Found: true,- Name: pool.Name(),- ResourceType: "storage",- TargetID: targetID,- TargetHost: targetID,- }- }-- // Check generic Hosts (Windows/Linux via Pulse Unified Agent).- // Match on Hostname() or AgentID() for parity with state.Hosts[].Hostname/ID.- // Use AgentID() as canonical target ID for host resources.- for _, host := range rs.Hosts() {- if host == nil {- continue- }- agentID := host.AgentID()- if host.Hostname() == name || agentID == name {- return models.ResourceLocation{- Found: true,- Name: host.Hostname(),- ResourceType: "agent",- TargetID: agentID,- Platform: host.Platform(),- TargetHost: host.Hostname(),- }- }- }-- // Check Kubernetes clusters, pods, and deployments.- // Build a map from cluster resource ID → cluster view for pod/deployment resolution.- clusterByID := make(map[string]*K8sClusterView, len(rs.K8sClusters()))- for _, cluster := range rs.K8sClusters() {- if cluster == nil {- continue- }- clusterByID[cluster.ID()] = cluster-- // Match by SourceName (original cluster.Name), ClusterID (original cluster.ID),- // or unified Name (display name) for parity with state.KubernetesClusters[].Name/ID/DisplayName.- sourceName := cluster.SourceName()- clusterName := cluster.Name()- if sourceName == name || cluster.ClusterID() == name || clusterName == name {- // Return fields use SourceName() for Name/K8sClusterName/TargetHost- // to match old resolver which used cluster.Name (raw source name).- // Fall back to display name if source name is empty.- returnName := sourceName- if returnName == "" {- returnName = clusterName- }- return models.ResourceLocation{- Found: true,- Name: returnName,- ResourceType: "k8s-cluster",- K8sClusterName: returnName,- K8sAgentID: cluster.AgentID(),- TargetHost: returnName,- AgentID: cluster.AgentID(),- }- }- }-- // Check pods.- for _, pod := range rs.Pods() {- if pod == nil {- continue- }- if pod.Name() == name {- loc := models.ResourceLocation{- Found: true,- Name: pod.Name(),- ResourceType: "k8s-pod",- K8sNamespace: pod.Namespace(),- }- if cluster := clusterByID[pod.ParentID()]; cluster != nil {- cn := clusterSourceOrDisplayName(cluster)- loc.K8sClusterName = cn- loc.K8sAgentID = cluster.AgentID()- loc.TargetHost = cn- loc.AgentID = cluster.AgentID()- }- return loc- }- }-- // Check deployments.- for _, deploy := range rs.K8sDeployments() {- if deploy == nil {- continue- }- if deploy.Name() == name {- loc := models.ResourceLocation{- Found: true,- Name: deploy.Name(),- ResourceType: "k8s-deployment",- K8sNamespace: deploy.Namespace(),- }- if cluster := clusterByID[deploy.ParentID()]; cluster != nil {- cn := clusterSourceOrDisplayName(cluster)- loc.K8sClusterName = cn- loc.K8sAgentID = cluster.AgentID()- loc.TargetHost = cn- loc.AgentID = cluster.AgentID()- }- return loc- }- }-- return models.ResourceLocation{Found: false, Name: name}+ return ResolveResourceContext(rs, name).Location}// clusterSourceOrDisplayName returns SourceName() (raw cluster.Name) when@@ -242,37 +30,70 @@ func clusterSourceOrDisplayName(c *K8sClusterView) string {// to the backing guest name. When false (docker host lookups), TargetHost stays// as the docker hostname — matching StateSnapshot.ResolveResource parity.func resolveDockerHostParent(rs ReadState, hostname, sourceID string, rewriteTarget bool, loc *models.ResourceLocation) {- // Check if the Docker host is a system container.- for _, ct := range rs.Containers() {- if ct == nil {- continue- }- if ct.Name() == hostname || ct.Name() == sourceID {- loc.DockerHostType = "system-container"- loc.DockerHostVMID = ct.VMID()- loc.Node = ct.Node()- if rewriteTarget {- loc.TargetHost = ct.Name()+ var guest *Resource+ if resolver, ok := rs.(ReferenceReadState); ok && sourceID != "" {+ resource, _, found := resolver.GetByReference(sourceID)+ visited := map[string]bool{}+ for found && resource != nil && !visited[resource.ID] {+ visited[resource.ID] = true+ if resource.Type == ResourceTypeVM || resource.Type == ResourceTypeSystemContainer {+ guest = resource+ break+ }+ if resource.Agent != nil {+ loc.AgentID = resource.Agent.AgentID+ }+ if resource.ParentID == nil {+ break+ }+ resource, _, found = resolver.GetByReference(*resource.ParentID)+ if !found {+ loc.TargetHost = ""+ return}- return}}- // Check if the Docker host is a VM.- for _, vm := range rs.VMs() {- if vm == nil {- continue+ if guest == nil {+ add := func(resource *Resource) bool {+ if resource == nil || (resource.Name != hostname && resource.Name != sourceID) {+ return true+ }+ if resolver, ok := rs.(ReferenceReadState); ok {+ owned, _, found := resolver.GetByReference(resource.ID)+ if !found || owned == nil {+ return true+ }+ resource = owned+ }+ if guest != nil && guest.ID != resource.ID {+ return false+ }+ guest = resource+ return true}- if vm.Name() == hostname || vm.Name() == sourceID {- loc.DockerHostType = "vm"- loc.DockerHostVMID = vm.VMID()- loc.Node = vm.Node()- if rewriteTarget {- loc.TargetHost = vm.Name()+ for _, view := range rs.Containers() {+ if view != nil && !add(view.r) {+ loc.TargetHost = ""+ return}- return}+ for _, view := range rs.VMs() {+ if view != nil && !add(view.r) {+ loc.TargetHost = ""+ return+ }+ }+ }+ if guest == nil {+ loc.DockerHostType = "standalone"+ return+ }+ owned := resourceContext(rs, guest).Location+ loc.DockerHostType, loc.DockerHostVMID, loc.Node = owned.ResourceType, owned.VMID, owned.Node+ loc.NodeResourceID, loc.AgentID = owned.NodeResourceID, owned.AgentID+ if rewriteTarget {+ loc.TargetHost = owned.TargetHost}- loc.DockerHostType = "standalone"}type appContainerResourceGetter interface {diff --git a/internal/unifiedresources/resolve_context.go b/internal/unifiedresources/resolve_context.goindex 61e1b8a1cb..97fa490662 100644--- a/internal/unifiedresources/resolve_context.go+++ b/internal/unifiedresources/resolve_context.go@@ -1,140 +1,295 @@package unifiedresourcesimport (+ "fmt""strings""github.com/rcourtman/pulse-go-rewrite/internal/models")-// ResolvedResourceContext combines canonical routing coordinates with the-// matching unified resource record so downstream consumers can apply canonical-// policy metadata without rescanning unrelated resource state.+// ResolvedResourceContext keeps identity, routing and policy on one owned record.type ResolvedResourceContext struct {Location models.ResourceLocationResource *Resource}-// ResolveResourceContext performs canonical name-based resolution and returns-// both the resolved location and the matching unified resource record.-func ResolveResourceContext(rs ReadState, name string) ResolvedResourceContext {- loc := ResolveResource(rs, name)- if !loc.Found {- return ResolvedResourceContext{Location: loc}+// ResolveResourceReferenceContext resolves an explicit selection without using+// its display label as a fallback. Unknown or ambiguous references fail closed.+func ResolveResourceReferenceContext(rs ReadState, reference string) ResolvedResourceContext {+ reference = strings.TrimSpace(reference)+ resolver, ok := rs.(ReferenceReadState)+ if !ok || reference == "" {+ return ResolvedResourceContext{}}-- return ResolvedResourceContext{- Location: loc,- Resource: lookupResolvedResource(rs, loc),+ resource, _, found := resolver.GetByReference(reference)+ if !found {+ resource = legacySelectedResource(rs, reference)+ }+ if resource == nil {+ return ResolvedResourceContext{}}+ return resourceContext(rs, resource)}-func lookupResolvedResource(rs ReadState, loc models.ResourceLocation) *Resource {- if rs == nil || !loc.Found {- return nil+// ResolveResourceContext retains the name-based read boundary for callers that+// have no explicit selection. A duplicated label cannot identify a resource.+func ResolveResourceContext(rs ReadState, name string) ResolvedResourceContext {+ name = strings.TrimSpace(name)+ if rs == nil || name == "" {+ return ResolvedResourceContext{Location: models.ResourceLocation{Name: name}}}-- name := strings.TrimSpace(loc.Name)- switch loc.ResourceType {- case "node":- for _, node := range rs.Nodes() {- if node == nil {- continue- }- if node.NodeName() == name {- return cloneResourcePtr(node.r)- }+ if resolver, ok := rs.(ReferenceReadState); ok {+ resource, _, found := resolver.GetByReference(name)+ if found && resource != nil {+ return resourceContext(rs, resource)}+ }+ resource, ambiguous := resourceByName(rs, name)+ if resource == nil {+ return ResolvedResourceContext{Location: models.ResourceLocation{Name: name, Ambiguous: ambiguous}}+ }+ return resourceContext(rs, resource)+}- case "vm":- for _, vm := range rs.VMs() {- if vm == nil {- continue- }- if vm.Name() == name {- return cloneResourcePtr(vm.r)+func resourceContext(rs ReadState, resource *Resource) ResolvedResourceContext {+ resource = cloneResourcePtr(resource)+ loc := models.ResourceLocation{Found: true, Name: resource.Name, ResourceType: string(resource.Type)}+ switch resource.Type {+ case ResourceTypeVM:+ view := NewVMView(resource)+ loc.VMID, loc.Node, loc.TargetHost = view.VMID(), view.Node(), view.Name()+ setParentNodeLocation(rs, resource, &loc)+ case ResourceTypeSystemContainer:+ view := NewContainerView(resource)+ loc.VMID, loc.Node, loc.TargetHost = view.VMID(), view.Node(), view.Name()+ setParentNodeLocation(rs, resource, &loc)+ case ResourceTypeAppContainer:+ populateAppContainerLocation(rs, *resource, &loc)+ case ResourceTypeStorage:+ view := NewStoragePoolView(resource)+ loc.TargetID = storagePoolTarget(&view)+ loc.TargetHost = loc.TargetID+ case ResourceTypeAgent:+ switch {+ case resource.Proxmox != nil && NewNodeView(resource).NodeName() != "":+ view := NewNodeView(resource)+ loc.ResourceType = "node"+ loc.Name, loc.Node, loc.TargetHost = view.NodeName(), view.NodeName(), view.NodeName()+ loc.NodeResourceID = resource.ID+ if resource.Agent != nil {+ loc.AgentID = resource.Agent.AgentID}+ case resource.Docker != nil && NewDockerHostView(resource).Hostname() != "":+ view := NewDockerHostView(resource)+ loc.ResourceType = "docker-host"+ loc.Name, loc.DockerHostName, loc.TargetHost = view.Hostname(), view.Hostname(), view.Hostname()+ resolveDockerHostParent(rs, view.Hostname(), view.HostSourceID(), false, &loc)+ default:+ view := NewHostView(resource)+ loc.Name, loc.TargetID, loc.Platform, loc.TargetHost = view.Hostname(), view.AgentID(), view.Platform(), view.Hostname()+ loc.AgentID = view.AgentID()}-- case "system-container":- for _, container := range rs.Containers() {- if container == nil {- continue- }- if container.Name() == name {- return cloneResourcePtr(container.r)- }+ case ResourceTypeK8sCluster:+ view := NewK8sClusterView(resource)+ loc.Name = clusterSourceOrDisplayName(&view)+ loc.K8sClusterName, loc.TargetHost = loc.Name, loc.Name+ loc.K8sAgentID, loc.AgentID = view.AgentID(), view.AgentID()+ case ResourceTypePod, ResourceTypeK8sDeployment:+ if resource.Type == ResourceTypePod {+ view := NewPodView(resource)+ loc.ResourceType, loc.K8sNamespace = "k8s-pod", view.Namespace()+ } else {+ view := NewK8sDeploymentView(resource)+ loc.K8sNamespace = view.Namespace()}-- case "docker-host":- for _, dockerHost := range rs.DockerHosts() {- if dockerHost == nil {- continue- }- if dockerHost.Hostname() == name || dockerHost.HostSourceID() == name {- return cloneResourcePtr(dockerHost.r)+ if resource.ParentID != nil {+ for _, cluster := range rs.K8sClusters() {+ if cluster != nil && cluster.ID() == *resource.ParentID {+ loc.K8sClusterName = clusterSourceOrDisplayName(cluster)+ loc.TargetHost = loc.K8sClusterName+ loc.K8sAgentID, loc.AgentID = cluster.AgentID(), cluster.AgentID()+ break+ }}}+ }+ return ResolvedResourceContext{Location: loc, Resource: resource}+}- case "app-container":- for _, resource := range appContainerResourcesFromReadState(rs) {- if appContainerResourceMatches(resource, name) {- return cloneResourcePtr(&resource)- }+func resourceByName(rs ReadState, name string) (*Resource, bool) {+ var result *Resource+ ambiguous := false+ add := func(resource *Resource, matches bool) {+ if !matches || resource == nil {+ return}-- case "storage":- for _, pool := range rs.StoragePools() {- if pool == nil {- continue- }- if storagePoolMatches(pool, name) {- return cloneResourcePtr(pool.r)+ if resolver, ok := rs.(ReferenceReadState); ok {+ owned, _, found := resolver.GetByReference(resource.ID)+ if !found || owned == nil {+ return}+ resource = owned+ }+ if result != nil && result.ID != resource.ID {+ ambiguous = true+ }+ result = resource+ }+ for _, view := range rs.Nodes() {+ if view != nil {+ add(view.r, view.NodeName() == name || view.ID() == name)+ }+ }+ for _, view := range rs.VMs() {+ if view != nil {+ add(view.r, view.Name() == name || view.ID() == name)}+ }+ for _, view := range rs.Containers() {+ if view != nil {+ add(view.r, view.Name() == name)+ }+ }+ for _, view := range rs.DockerHosts() {+ if view != nil {+ add(view.r, HostnamesEquivalent(view.Hostname(), name) || view.HostSourceID() == name || view.ID() == name)+ }+ }+ for _, resource := range appContainerResourcesFromReadState(rs) {+ add(cloneResourcePtr(&resource), appContainerResourceMatches(resource, name))+ }+ for _, view := range rs.StoragePools() {+ if view != nil {+ add(view.r, storagePoolMatches(view, name))+ }+ }+ for _, view := range rs.Hosts() {+ if view != nil {+ add(view.r, HostnamesEquivalent(view.Hostname(), name) || view.AgentID() == name || view.ID() == name)+ }+ }+ for _, view := range rs.K8sClusters() {+ if view != nil {+ add(view.r, view.SourceName() == name || view.Name() == name || view.ClusterID() == name)+ }+ }+ for _, view := range rs.Pods() {+ if view != nil {+ add(view.r, view.Name() == name)+ }+ }+ for _, view := range rs.K8sDeployments() {+ if view != nil {+ add(view.r, view.Name() == name)+ }+ }+ if ambiguous {+ return nil, true+ }+ return result, false+}- case "agent":- for _, host := range rs.Hosts() {- if host == nil {- continue+// legacySelectedResource bounds the pre-canonical mention wire formats to a+// unique current owner. The label and caller-supplied node never select a row.+func legacySelectedResource(rs ReadState, reference string) *Resource {+ var result *Resource+ ambiguous := false+ add := func(resource *Resource, native string) {+ if resource == nil || native != reference {+ return+ }+ if resolver, ok := rs.(ReferenceReadState); ok {+ owned, _, found := resolver.GetByReference(resource.ID)+ if !found || owned == nil {+ return}- if host.Hostname() == name || host.AgentID() == name {- return cloneResourcePtr(host.r)+ resource = owned+ }+ if result != nil && result.ID != resource.ID {+ ambiguous = true+ }+ result = resource+ }+ for _, view := range rs.VMs() {+ if view != nil && view.VMID() > 0 {+ add(view.r, fmt.Sprintf("vm:%s:%d", view.Node(), view.VMID()))+ }+ }+ for _, view := range rs.Containers() {+ if view != nil && view.VMID() > 0 {+ add(view.r, fmt.Sprintf("system-container:%s:%d", view.Node(), view.VMID()))+ }+ }+ for _, resource := range appContainerResourcesFromReadState(rs) {+ host := appContainerResourceHost(resource)+ uid := ""+ if resource.Docker != nil {+ uid = strings.TrimSpace(resource.Docker.ContainerID)+ }+ if uid == "" && resource.Canonical != nil {+ uid = strings.TrimSpace(resource.Canonical.PrimaryID)+ }+ if host != "" && uid != "" {+ add(&resource, "app-container:"+host+":"+uid)+ }+ if resource.Docker != nil && uid != "" && resource.Docker.HostSourceID != "" {+ add(&resource, "docker:"+resource.Docker.HostSourceID+":"+uid)+ }+ }+ for _, view := range rs.Hosts() {+ if view != nil && view.AgentID() != "" {+ add(view.r, "agent:"+view.AgentID())+ }+ }+ for _, view := range rs.DockerHosts() {+ if view != nil && view.HostSourceID() != "" {+ add(view.r, "agent:"+view.HostSourceID())+ }+ }+ for _, view := range rs.Nodes() {+ if view != nil && view.r.Proxmox != nil {+ for _, instance := range []string{view.r.Proxmox.Instance, view.r.Proxmox.SourceID, ""} {+ add(view.r, "node:"+instance+":"+view.NodeName())}}+ }+ if ambiguous {+ return nil+ }+ return cloneResourcePtr(result)+}- case "k8s-cluster":- for _, cluster := range rs.K8sClusters() {- if cluster == nil {- continue- }- sourceName := strings.TrimSpace(cluster.SourceName())- clusterName := strings.TrimSpace(cluster.Name())- clusterID := strings.TrimSpace(cluster.ClusterID())- if sourceName == name || clusterName == name || clusterID == name {- return cloneResourcePtr(cluster.r)+func setParentNodeLocation(rs ReadState, resource *Resource, loc *models.ResourceLocation) {+ if resource.Proxmox == nil {+ return+ }+ var node *Resource+ if resource.ParentID != nil {+ if resolver, ok := rs.(ReferenceReadState); ok {+ parent, _, found := resolver.GetByReference(*resource.ParentID)+ if found && parent != nil && parent.Type == ResourceTypeAgent && parent.Proxmox != nil {+ node = parent}}-- case "k8s-pod":- for _, pod := range rs.Pods() {- if pod == nil {+ }+ if node == nil {+ for _, view := range rs.Nodes() {+ if view == nil || view.r.Proxmox == nil || view.NodeName() != resource.Proxmox.NodeName {continue}- if pod.Name() == name {- return cloneResourcePtr(pod.r)- }- }-- case "k8s-deployment":- for _, deployment := range rs.K8sDeployments() {- if deployment == nil {+ if resource.Proxmox.Instance != "" && view.r.Proxmox.Instance != resource.Proxmox.Instance {continue}- if deployment.Name() == name {- return cloneResourcePtr(deployment.r)+ if node != nil && node.ID != view.ID() {+ return}+ node = view.r+ }+ }+ if node != nil {+ loc.NodeResourceID = node.ID+ if node.Agent != nil {+ loc.AgentID = node.Agent.AgentID}}-- return nil}diff --git a/internal/unifiedresources/resolve_test.go b/internal/unifiedresources/resolve_test.goindex 7c305f7dd9..ea114eb1e2 100644--- a/internal/unifiedresources/resolve_test.go+++ b/internal/unifiedresources/resolve_test.go@@ -149,9 +149,8 @@ func TestResolveResource_DockerContainerTargetHostRewrite(t *testing.T) {// Docker HOST lookup must NOT rewrite TargetHost.locHost := ResolveResource(rr, "docker-host-lxc")- if !locHost.Found || locHost.ResourceType != "system-container" {- // Should match as system-container first (earlier in resolution order)- t.Fatalf("expected system-container, got found=%v type=%q", locHost.Found, locHost.ResourceType)+ if !locHost.Found || locHost.ResourceType != "docker-host" || locHost.DockerHostType != "system-container" || locHost.DockerHostVMID != 100 {+ t.Fatalf("expected the registered Docker host source reference to keep its current guest parent, got %+v", locHost)}}@@ -229,11 +228,10 @@ func TestResolveResource_VMwareStorage(t *testing.T) {}}-func TestLookupResolvedResource_TrueNASAppUsesCanonicalAppContainerSet(t *testing.T) {+func TestResolveResourceContext_TrueNASAppUsesCanonicalAppContainerSet(t *testing.T) {rr := newTrueNASAppRegistryFixture()- loc := ResolveResource(rr, "Nextcloud")- resource := lookupResolvedResource(rr, loc)+ resource := ResolveResourceContext(rr, "Nextcloud").Resourceif resource == nil {t.Fatal("expected resolved resource for TrueNAS app")}