Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Surface Patrol investigation records in Assistant context

rcourtman87ba22b0fc60
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index e4e54d1dea..925f0023b8 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -353,7 +353,10 @@ profile and assignment columns, but embedded table framing must route through
through shared AI intelligence handlers and `internal/api/router.go`:
lifecycle surfaces may observe the resulting resource context, but they must
not reinterpret `investigation_record` as agent enrollment, installer,
- command policy, or fleet-control authority.
+ command policy, or fleet-control authority. Assistant chat enrichment from
+ `finding_id` follows the same rule: lifecycle-owned command execution and
+ agent auto-approval policy stay canonical in the agent/runtime owners, not
+ in Patrol investigation-record prompt text.
The same isolation rule applies to CSRF token-store behavior in
`internal/api/csrf_store.go`: lifecycle-adjacent browser flows may rely on
the shared API/security layer to keep parallel replacement-token retries
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 0f2db34097..1289302608 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -173,7 +173,10 @@ runtime cost control, and shared AI transport surfaces.
`InvestigationSession` as execution detail, but Assistant handoff,
unified findings, persistence, and approval/remediation context must use
the durable investigation record when they need operator-facing
- investigation context.
+ investigation context. When `/api/ai/chat` receives `finding_id`, the
+ runtime must enrich the prompt from that durable record before provider
+ transport while keeping proposed-fix command text out of the chat prompt;
+ command payloads remain approval-context data, not conversational copy.
## Current State
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index c8aed21de7..41b0e11512 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -743,7 +743,11 @@ the canonical monitored-system blocked payload.
and the structured investigation-record contract, so unified findings may
expose `investigation_record` only through the shared
`aicontracts.InvestigationRecord` payload shape, with frontend API types
- and backend contract tests updated in the same slice as any field change.
+ and backend contract tests updated in the same slice as any field change
+ and the Assistant finding-context request contract, so `/api/ai/chat`
+ payloads carrying `finding_id` may hydrate a structured investigation
+ summary from the unified finding, but raw proposed-fix commands must stay
+ out of the prompt and inside governed approval/remediation context.
7. Keep Patrol summary payload consumers aligned on one assessment hierarchy: transport-driven Patrol summary surfaces may show supporting counts and outcomes, but the canonical assessment and verification states must remain singular and not be repeated as a second compact verdict strip
8. Keep Patrol verification and activity facts unified on one transport-backed secondary status area: when frontend consumers combine Patrol status payloads (`runtime_state`, `last_patrol_at`, `last_activity_at`, `trigger_status`) with run-history transport, the latest run result, activity mix, scoped-trigger state, and circuit-breaker context must read as one supporting explanation beneath the primary assessment instead of being re-expanded into a separate full-width status strip plus duplicate summary layers
and the main Patrol page composition boundary, so once that governed
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 0feba55e89..97313ffb66 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -805,7 +805,11 @@ frontend primitive boundary.
Assistant drawer with a pre-filled prompt, context, and
`autonomousMode:false`, but they must not mutate persistent AI control-level
settings or trigger background Assistant settings/model bootstrap before
- the drawer is open.
+ the drawer is open. Patrol finding handoffs that add structured
+ investigation-record framing must derive that prompt copy through
+ `frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts`
+ so shared drawer primitives stay shell-owned rather than becoming a
+ Patrol-specific prompt formatter.
11. Keep shared filter primitives coherent with route-owned option hydration.
Feature shells such as `frontend-modern/src/features/infrastructure/`
must keep a route-owned canonical option visible in shared selects like
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index de22e074aa..20c0d95905 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -96,9 +96,9 @@ Patrol-specific presentation helpers.
not as a broad automation promise.
8. Keep the Patrol store aligned with the shared structured investigation
record when transport carries one. `frontend-modern/src/stores/aiIntelligence.ts`
- may retain `investigationRecord` as data for Assistant handoff and future
- Patrol presentation, but visible Patrol copy must still flow through the
- governed Patrol presentation helpers before the record becomes UI.
+ may retain `investigationRecord` as data for Assistant handoff and Patrol
+ presentation, but visible Patrol copy and Assistant handoff prompt framing
+ must flow through the governed Patrol investigation-context helpers.
## Current State
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c433e8c7ef..658e2d6794 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -408,7 +408,10 @@ bypass the API fail-closed execution gate.
rule. Storage and recovery surfaces may consume the resource context in a
shared `investigation_record`, but they must not reinterpret that record as
recovery freshness, restore support, backup cadence, or storage-local
- action authority.
+ action authority. Assistant chat summaries built from `finding_id` remain
+ AI/runtime context; storage and recovery may read the resulting guidance
+ only as adjacent investigation context, not as a recovery support verdict
+ or restore execution contract.
That same adjacent `internal/api/` boundary still carries Patrol-run
execution identity. Storage and recovery may observe shared Patrol
transport through `internal/api/chat_service_adapter.go`, but they must not
diff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.ts
index 1cd2ddb3c2..c6b697aacd 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -109,4 +109,38 @@ describe('AIChatAPI', () => {
}),
);
});
+
+ it('includes a Patrol finding id when supplied for Assistant context', async () => {
+ const read = vi.fn().mockResolvedValueOnce({ done: true, value: undefined });
+ const releaseLock = vi.fn();
+
+ apiFetchMock.mockResolvedValueOnce({
+ ok: true,
+ body: {
+ getReader: () => ({ read, releaseLock }),
+ },
+ } as unknown as Response);
+
+ await AIChatAPI.chat(
+ 'inspect this finding',
+ 'session-2',
+ undefined,
+ vi.fn(),
+ undefined,
+ undefined,
+ 'finding-123',
+ );
+
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/ai/chat',
+ expect.objectContaining({
+ body: JSON.stringify({
+ prompt: 'inspect this finding',
+ session_id: 'session-2',
+ model: undefined,
+ finding_id: 'finding-123',
+ }),
+ }),
+ );
+ });
});
diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsx
index 11e7104b47..d1a0d9879b 100644
--- a/frontend-modern/src/components/AI/FindingsPanel.tsx
+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx
@@ -17,6 +17,7 @@ import { FormSelect } from '@/components/shared/FormSelect';
import { aiIntelligenceStore, type UnifiedFinding } from '@/stores/aiIntelligence';
import { notificationStore } from '@/stores/notifications';
import { aiChatStore } from '@/stores/aiChat';
+import { buildPatrolAssistantFindingPrompt } from '@/features/patrol/patrolInvestigationContextModel';
import { useResources } from '@/hooks/useResources';
import { InvestigationSection, ApprovalSection } from '@/components/patrol';
import type { RemediationPlan } from '@/api/ai';
@@ -417,10 +418,17 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
e.stopPropagation();
const subject = getFindingSubjectPresentation(finding).label;
const title = getFindingTitlePresentation(finding).label;
- aiChatStore.openWithPrompt(
- `I'd like to discuss this Patrol finding: "${title}" on ${subject}.\n\n${finding.description}`,
- { targetType: finding.resourceType, targetId: finding.resourceId, findingId: finding.id },
- );
+ const prompt = buildPatrolAssistantFindingPrompt({
+ title,
+ subject,
+ description: finding.description,
+ investigationRecord: finding.investigationRecord,
+ });
+ aiChatStore.openWithPrompt(prompt, {
+ targetType: finding.resourceType,
+ targetId: finding.resourceId,
+ findingId: finding.id,
+ });
};
const handleOpenPlanInAssistant = (finding: UnifiedFinding, plan: RemediationPlan, e: Event) => {
@@ -1032,6 +1040,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
investigationStatus={finding.investigationStatus}
investigationOutcome={finding.investigationOutcome}
investigationAttempts={finding.investigationAttempts}
+ investigationRecord={finding.investigationRecord}
/>
</Show>
diff --git a/frontend-modern/src/components/patrol/InvestigationSection.tsx b/frontend-modern/src/components/patrol/InvestigationSection.tsx
index 5d632fd8ed..017665cc2e 100644
--- a/frontend-modern/src/components/patrol/InvestigationSection.tsx
+++ b/frontend-modern/src/components/patrol/InvestigationSection.tsx
@@ -11,15 +11,12 @@ import {
createSignal,
createResource,
createEffect,
+ createMemo,
onCleanup,
Show,
For,
} from 'solid-js';
-import {
- getInvestigation,
- reinvestigateFinding,
- formatTimestamp,
-} from '@/api/patrol';
+import { getInvestigation, reinvestigateFinding, formatTimestamp } from '@/api/patrol';
import {
getInvestigationOutcomeBadgeClasses,
getInvestigationOutcomeLabel,
@@ -27,9 +24,11 @@ import {
getInvestigationStatusBadgeClasses,
} from '@/utils/aiFindingPresentation';
import { getInvestigationSectionState } from '@/utils/patrolEmptyStatePresentation';
+import { buildPatrolInvestigationRecordPresentation } from '@/features/patrol/patrolInvestigationContextModel';
import { InvestigationMessages } from './InvestigationMessages';
import { notificationStore } from '@/stores/notifications';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
+import type { InvestigationRecord } from '@/api/ai';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
interface InvestigationSectionProps {
@@ -37,12 +36,16 @@ interface InvestigationSectionProps {
investigationStatus?: string;
investigationOutcome?: string;
investigationAttempts?: number;
+ investigationRecord?: InvestigationRecord;
}
export const InvestigationSection: Component<InvestigationSectionProps> = (props) => {
const [showThread, setShowThread] = createSignal(false);
const [reinvestigating, setReinvestigating] = createSignal(false);
const [cooldownUntil, setCooldownUntil] = createSignal(0);
+ const investigationRecord = createMemo(() =>
+ buildPatrolInvestigationRecordPresentation(props.investigationRecord),
+ );
const [investigation, { refetch }] = createResource(
() => props.findingId,
@@ -165,6 +168,100 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
</p>
</Show>
+ <Show when={investigationRecord().hasRecord}>
+ <div class="mb-2 rounded border border-border bg-surface-alt p-2">
+ <div class="flex items-center gap-2 flex-wrap">
+ <span class="text-xs font-medium text-base-content">Patrol record</span>
+ <span class="rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] font-medium text-muted">
+ {investigationRecord().statusLabel}
+ </span>
+ <Show when={investigationRecord().outcomeLabel}>
+ <span class="rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] font-medium text-muted">
+ {investigationRecord().outcomeLabel}
+ </span>
+ </Show>
+ <Show when={investigationRecord().confidenceLabel}>
+ <span class="text-[10px] text-muted">{investigationRecord().confidenceLabel}</span>
+ </Show>
+ </div>
+
+ <Show when={investigationRecord().conclusion}>
+ <p class="mt-2 text-sm text-base-content">{investigationRecord().conclusion}</p>
+ </Show>
+ <Show when={investigationRecord().recommendedAction}>
+ <p class="mt-1 text-xs text-muted">
+ <span class="font-medium text-base-content">Recommended action:</span>{' '}
+ {investigationRecord().recommendedAction}
+ </p>
+ </Show>
+
+ <Show when={investigationRecord().proposedFix}>
+ {(fix) => (
+ <div class="mt-2 rounded border border-border-subtle bg-surface p-2 text-xs">
+ <div class="font-medium text-base-content">{fix().description}</div>
+ <div class="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-muted">
+ <Show when={fix().riskLabel}>
+ <span>{fix().riskLabel} risk</span>
+ </Show>
+ <Show when={fix().targetHost}>
+ <span>target {fix().targetHost}</span>
+ </Show>
+ <Show when={fix().commandSummary}>
+ <span>{fix().commandSummary}</span>
+ </Show>
+ <Show when={fix().destructive}>
+ <span class="text-amber-700 dark:text-amber-300">destructive</span>
+ </Show>
+ </div>
+ <Show when={fix().rationale}>
+ <p class="mt-1 text-muted">{fix().rationale}</p>
+ </Show>
+ </div>
+ )}
+ </Show>
+
+ <Show when={investigationRecord().evidenceSummaries.length > 0}>
+ <div class="mt-2">
+ <div class="text-[10px] font-medium uppercase text-muted">Evidence</div>
+ <ul class="mt-1 space-y-1 text-xs text-muted">
+ <For each={investigationRecord().evidenceSummaries}>
+ {(item) => <li>{item}</li>}
+ </For>
+ </ul>
+ </div>
+ </Show>
+
+ <Show when={investigationRecord().verificationSummaries.length > 0}>
+ <div class="mt-2">
+ <div class="text-[10px] font-medium uppercase text-muted">Verification</div>
+ <ul class="mt-1 space-y-1 text-xs text-muted">
+ <For each={investigationRecord().verificationSummaries}>
+ {(item) => <li>{item}</li>}
+ </For>
+ </ul>
+ </div>
+ </Show>
+
+ <Show when={investigationRecord().toolsUsed.length > 0}>
+ <div class="mt-2 flex flex-wrap gap-1">
+ <For each={investigationRecord().toolsUsed}>
+ {(tool) => (
+ <span class="rounded bg-surface px-1.5 py-0.5 text-[10px] font-medium text-muted">
+ {tool}
+ </span>
+ )}
+ </For>
+ </div>
+ </Show>
+
+ <Show when={investigationRecord().error}>
+ <div class="mt-2 rounded border border-red-200 bg-red-50 p-2 text-xs text-red-700 dark:border-red-800 dark:bg-red-900 dark:text-red-300">
+ {investigationRecord().error}
+ </div>
+ </Show>
+ </div>
+ </Show>
+
{/* Investigation details */}
<Show when={!investigation.loading && investigation()}>
{(inv) => (
diff --git a/frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx b/frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx
index 6d8a57b0f1..85e088109b 100644
--- a/frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/InvestigationSection.test.tsx
@@ -1,5 +1,6 @@
import { cleanup, render, screen } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { InvestigationRecord } from '@/api/ai';
import type { Investigation } from '@/api/patrol';
import {
getInvestigationOutcomeBadgeClasses,
@@ -84,4 +85,43 @@ describe('InvestigationSection', () => {
getInvestigationOutcomeBadgeClasses('needs_attention'),
);
});
+
+ it('renders the durable Patrol investigation record through the inline investigation surface', async () => {
+ getInvestigationMock.mockResolvedValue(undefined as unknown as Investigation);
+
+ const record: InvestigationRecord = {
+ id: 'record-1',
+ finding_id: 'finding-1',
+ subject: { resource_id: 'vm-100', resource_name: 'web', resource_type: 'vm' },
+ trigger: {
+ title: 'High CPU usage',
+ detected_at: '2026-05-06T12:00:00Z',
+ },
+ status: 'completed',
+ outcome: 'fix_queued',
+ confidence: 'high',
+ evidence: [{ kind: 'metrics', summary: 'CPU stayed above 95% for 10 minutes' }],
+ conclusion: 'Backup job saturated CPU.',
+ recommended_action: 'Approve a controlled restart after the backup completes.',
+ proposed_fix: {
+ id: 'fix-1',
+ description: 'Restart the workload service',
+ commands: ['systemctl restart workload.service'],
+ risk_level: 'medium',
+ destructive: false,
+ target_host: 'pve-1',
+ },
+ verification: ['CPU returned below 50%'],
+ tools_used: ['metrics.history'],
+ started_at: '2026-05-06T12:00:00Z',
+ };
+
+ render(() => <InvestigationSection findingId="finding-1" investigationRecord={record} />);
+
+ expect(await screen.findByText('Patrol record')).toBeInTheDocument();
+ expect(screen.getByText('Backup job saturated CPU.')).toBeInTheDocument();
+ expect(screen.getByText('CPU stayed above 95% for 10 minutes')).toBeInTheDocument();
+ expect(screen.getByText('1 command recorded for approval context')).toBeInTheDocument();
+ expect(screen.queryByText('systemctl restart workload.service')).not.toBeInTheDocument();
+ });
});
diff --git a/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
index 59b04d2df4..9d0fa4f98d 100644
--- a/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { buildPatrolInvestigationContextSummary } from '../patrolInvestigationContextModel';
+import {
+ buildPatrolAssistantFindingPrompt,
+ buildPatrolInvestigationContextSummary,
+ buildPatrolInvestigationRecordPresentation,
+} from '../patrolInvestigationContextModel';
describe('patrolInvestigationContextModel', () => {
it('builds the canonical investigation context summary from recent changes, correlations, and policy posture', () => {
@@ -79,4 +83,76 @@ describe('patrolInvestigationContextModel', () => {
summaryText: '',
});
});
+
+ it('builds operator-facing Patrol record presentation without exposing raw commands', () => {
+ const presentation = buildPatrolInvestigationRecordPresentation({
+ id: 'record-1',
+ finding_id: 'finding-1',
+ subject: { resource_id: 'vm-100', resource_name: 'web', resource_type: 'vm' },
+ trigger: {
+ title: 'High CPU usage',
+ detected_at: '2026-05-06T12:00:00Z',
+ },
+ status: 'completed',
+ outcome: 'fix_queued',
+ confidence: 'high',
+ conclusion: 'Backup job saturated CPU.',
+ recommended_action: 'Approve a controlled restart after the backup completes.',
+ evidence: [
+ { kind: 'metrics', summary: 'CPU stayed above 95% for 10 minutes' },
+ { kind: 'logs', summary: 'Backup process held IO wait.' },
+ ],
+ proposed_fix: {
+ id: 'fix-1',
+ description: 'Restart the workload service',
+ commands: ['systemctl restart workload.service'],
+ risk_level: 'medium',
+ destructive: false,
+ target_host: 'pve-1',
+ rationale: 'The process is wedged after backup IO pressure.',
+ },
+ verification: ['CPU returned below 50%'],
+ tools_used: ['metrics.history', 'ssh.exec'],
+ started_at: '2026-05-06T12:00:00Z',
+ });
+
+ expect(presentation).toMatchObject({
+ hasRecord: true,
+ statusLabel: 'Completed',
+ outcomeLabel: 'Fix Queued',
+ confidenceLabel: 'High confidence',
+ conclusion: 'Backup job saturated CPU.',
+ evidenceSummaries: ['CPU stayed above 95% for 10 minutes', 'Backup process held IO wait.'],
+ verificationSummaries: ['CPU returned below 50%'],
+ toolsUsed: ['Metrics history', 'SSH exec'],
+ proposedFix: {
+ description: 'Restart the workload service',
+ riskLabel: 'Medium',
+ targetHost: 'pve-1',
+ commandSummary: '1 command recorded for approval context',
+ },
+ });
+ expect(JSON.stringify(presentation)).not.toContain('systemctl restart workload.service');
+ });
+
+ it('frames Assistant handoff around the structured Patrol record when one exists', () => {
+ expect(
+ buildPatrolAssistantFindingPrompt({
+ title: 'High CPU usage',
+ subject: 'web-server',
+ description: 'CPU stayed above 95%.',
+ investigationRecord: {
+ id: 'record-1',
+ finding_id: 'finding-1',
+ subject: { resource_id: 'vm-100' },
+ trigger: { detected_at: '2026-05-06T12:00:00Z' },
+ status: 'completed',
+ evidence: [],
+ verification: [],
+ tools_used: [],
+ started_at: '2026-05-06T12:00:00Z',
+ },
+ }),
+ ).toContain('Use that record as the main context before suggesting next actions.');
+ });
});
diff --git a/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts b/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
index 2bc57435dd..55458e461c 100644
--- a/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
+++ b/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
@@ -1,4 +1,8 @@
-import type { CorrelationsResponse, IntelligencePolicyPostureSummary } from '@/types/aiIntelligence';
+import type {
+ CorrelationsResponse,
+ IntelligencePolicyPostureSummary,
+} from '@/types/aiIntelligence';
+import type { InvestigationRecord } from '@/api/ai';
export interface PatrolInvestigationContextSummaryInput {
recentChangesCount?: number | null;
@@ -14,6 +18,34 @@ export interface PatrolInvestigationContextSummary {
summaryText: string;
}
+export interface PatrolInvestigationRecordPresentation {
+ hasRecord: boolean;
+ statusLabel: string;
+ outcomeLabel?: string;
+ confidenceLabel?: string;
+ conclusion?: string;
+ recommendedAction?: string;
+ evidenceSummaries: string[];
+ verificationSummaries: string[];
+ toolsUsed: string[];
+ proposedFix?: {
+ description: string;
+ riskLabel?: string;
+ targetHost?: string;
+ rationale?: string;
+ commandSummary?: string;
+ destructive: boolean;
+ };
+ error?: string;
+}
+
+export interface PatrolAssistantFindingPromptInput {
+ title: string;
+ subject: string;
+ description: string;
+ investigationRecord?: InvestigationRecord | null;
+}
+
export function buildPatrolInvestigationContextSummary(
input: PatrolInvestigationContextSummaryInput,
): PatrolInvestigationContextSummary {
@@ -43,6 +75,77 @@ export function buildPatrolInvestigationContextSummary(
};
}
+export function buildPatrolInvestigationRecordPresentation(
+ record?: InvestigationRecord | null,
+): PatrolInvestigationRecordPresentation {
+ if (!record) {
+ return {
+ hasRecord: false,
+ statusLabel: '',
+ evidenceSummaries: [],
+ verificationSummaries: [],
+ toolsUsed: [],
+ };
+ }
+
+ const proposedFix = record.proposed_fix
+ ? {
+ description: normalizeText(record.proposed_fix.description),
+ riskLabel: formatIdentifierLabel(record.proposed_fix.risk_level),
+ targetHost: normalizeText(record.proposed_fix.target_host),
+ rationale: normalizeText(record.proposed_fix.rationale),
+ commandSummary: formatCommandSummary(record.proposed_fix.commands?.length ?? 0),
+ destructive: Boolean(record.proposed_fix.destructive),
+ }
+ : undefined;
+
+ return {
+ hasRecord: true,
+ statusLabel: formatIdentifierLabel(record.status) || 'Investigation recorded',
+ outcomeLabel: formatIdentifierLabel(record.outcome),
+ confidenceLabel: record.confidence
+ ? `${formatIdentifierLabel(record.confidence)} confidence`
+ : undefined,
+ conclusion: normalizeText(record.conclusion),
+ recommendedAction: normalizeText(record.recommended_action),
+ evidenceSummaries: (record.evidence || [])
+ .map((item) => normalizeText(item.summary || item.kind || item.id))
+ .filter(Boolean)
+ .slice(0, 3),
+ verificationSummaries: (record.verification || [])
+ .map(normalizeText)
+ .filter(Boolean)
+ .slice(0, 3),
+ toolsUsed: (record.tools_used || []).map(formatToolLabel).filter(Boolean).slice(0, 4),
+ proposedFix:
+ proposedFix && proposedFix.description
+ ? proposedFix
+ : proposedFix && (proposedFix.commandSummary || proposedFix.rationale)
+ ? proposedFix
+ : undefined,
+ error: normalizeText(record.error),
+ };
+}
+
+export function buildPatrolAssistantFindingPrompt(
+ input: PatrolAssistantFindingPromptInput,
+): string {
+ const title = normalizeText(input.title) || 'Patrol finding';
+ const subject = normalizeText(input.subject) || 'the affected resource';
+ const description = normalizeText(input.description);
+ const hasRecord = Boolean(input.investigationRecord?.id);
+
+ let prompt = `I'd like to discuss this Patrol finding: "${title}" on ${subject}.`;
+ if (hasRecord) {
+ prompt +=
+ '\n\nPulse Patrol has a structured investigation record for this finding. Use that record as the main context before suggesting next actions.';
+ }
+ if (description) {
+ prompt += `\n\n${description}`;
+ }
+ return prompt;
+}
+
function normalizeCorrelationCount(correlations?: CorrelationsResponse | null): number {
if (!correlations) return 0;
if (typeof correlations.count === 'number' && Number.isFinite(correlations.count)) {
@@ -60,3 +163,37 @@ function normalizeNonNegativeCount(value?: number | null): number {
}
return Math.max(0, Math.trunc(value));
}
+
+function formatCommandSummary(count: number): string | undefined {
+ if (!Number.isFinite(count) || count <= 0) return undefined;
+ return count === 1
+ ? '1 command recorded for approval context'
+ : `${count} commands recorded for approval context`;
+}
+
+function formatIdentifierLabel(value?: string | null): string | undefined {
+ const normalized = normalizeText(value);
+ if (!normalized) return undefined;
+ return normalized
+ .replace(/[._-]+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .replace(/\b\w/g, (char) => char.toUpperCase());
+}
+
+function formatToolLabel(value?: string | null): string {
+ const normalized = normalizeText(value);
+ const knownLabel = PATROL_TOOL_LABELS[normalized];
+ if (knownLabel) return knownLabel;
+ return formatIdentifierLabel(normalized) || '';
+}
+
+function normalizeText(value?: string | null): string {
+ if (typeof value !== 'string') return '';
+ return value.trim();
+}
+
+const PATROL_TOOL_LABELS: Record<string, string> = {
+ 'metrics.history': 'Metrics history',
+ 'ssh.exec': 'SSH exec',
+};
diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
index c338fece0e..5789696631 100644
--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
@@ -4342,6 +4342,18 @@ describe('frontend resource type boundaries', () => {
expect(patrolInvestigationContextModelSource).toContain(
'export function buildPatrolInvestigationContextSummary',
);
+ expect(patrolInvestigationContextModelSource).toContain(
+ 'export function buildPatrolInvestigationRecordPresentation',
+ );
+ expect(patrolInvestigationContextModelSource).toContain(
+ 'export function buildPatrolAssistantFindingPrompt',
+ );
+ expect(patrolInvestigationContextModelSource).toContain(
+ 'formatCommandSummary(record.proposed_fix.commands?.length ?? 0)',
+ );
+ expect(patrolInvestigationContextModelSource).not.toContain(
+ 'record.proposed_fix.commands.join',
+ );
expect(patrolInvestigationContextModelSource).toContain('policy-covered resource');
expect(patrolIntelligenceHeaderSource).toContain('buildPatrolScheduleOptions');
expect(patrolIntelligenceHeaderSource).not.toContain('getAIQuickstartCreditsPresentation');
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 19797eb22f..d6e92c1097 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -21,6 +21,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
recoverymanager "github.com/rcourtman/pulse-go-rewrite/internal/recovery/manager"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
"github.com/rs/zerolog/log"
)
@@ -780,6 +781,156 @@ type ChatRequest struct {
AutonomousMode *bool `json:"autonomous_mode,omitempty"`
}
+const findingChatContextListLimit = 5
+
+func buildUnifiedFindingChatContext(f *unified.UnifiedFinding) string {
+ if f == nil {
+ return ""
+ }
+
+ var b strings.Builder
+ appendChatContextLine(&b, "[Finding Context]", "")
+ appendChatContextLine(&b, "ID", f.ID)
+ appendChatContextLine(&b, "Title", f.Title)
+ appendChatContextLine(&b, "Severity", string(f.Severity))
+ appendChatContextLine(&b, "Category", string(f.Category))
+ appendChatContextLine(&b, "Resource", fmt.Sprintf("%s (%s)", f.ResourceName, f.ResourceType))
+ appendChatContextLine(&b, "Description", f.Description)
+ appendChatContextLine(&b, "Recommendation", f.Recommendation)
+ appendChatContextLine(&b, "Evidence", f.Evidence)
+ appendChatContextLine(&b, "Investigation Status", f.InvestigationStatus)
+ appendChatContextLine(&b, "Investigation Outcome", f.InvestigationOutcome)
+ appendChatContextLine(&b, "User Note", f.UserNote)
+ if f.AcknowledgedAt != nil {
+ appendChatContextLine(&b, "Acknowledged At", f.AcknowledgedAt.Format(time.RFC3339))
+ }
+ appendChatContextLine(&b, "Node", f.Node)
+ appendInvestigationRecordChatContext(&b, f.InvestigationRecord)
+ return b.String()
+}
+
+func appendInvestigationRecordChatContext(b *strings.Builder, rec *aicontracts.InvestigationRecord) {
+ if rec == nil {
+ return
+ }
+
+ appendChatContextLine(b, "", "")
+ appendChatContextLine(b, "[Investigation Record]", "")
+ appendChatContextLine(b, "Record ID", rec.ID)
+ appendChatContextLine(b, "Session ID", rec.SessionID)
+ appendChatContextLine(b, "Status", string(rec.Status))
+ appendChatContextLine(b, "Outcome", string(rec.Outcome))
+ appendChatContextLine(b, "Confidence", string(rec.Confidence))
+ appendChatContextLine(b, "Conclusion", rec.Conclusion)
+ appendChatContextLine(b, "Recommended Action", rec.RecommendedAction)
+ appendChatContextLine(b, "Trigger", rec.Trigger.Title)
+ appendChatContextLine(b, "Trigger Description", rec.Trigger.Description)
+ if !rec.Trigger.DetectedAt.IsZero() {
+ appendChatContextLine(b, "Detected At", rec.Trigger.DetectedAt.Format(time.RFC3339))
+ }
+ if !rec.StartedAt.IsZero() {
+ appendChatContextLine(b, "Investigation Started At", rec.StartedAt.Format(time.RFC3339))
+ }
+ if rec.CompletedAt != nil {
+ appendChatContextLine(b, "Investigation Completed At", rec.CompletedAt.Format(time.RFC3339))
+ }
+ appendChatContextLine(b, "Approval ID", rec.ApprovalID)
+ appendChatContextLine(b, "Error", rec.Error)
+
+ appendInvestigationRecordEvidenceContext(b, rec.Evidence)
+ appendStringListChatContext(b, "Verification", rec.Verification)
+ appendStringListChatContext(b, "Tools Used", rec.ToolsUsed)
+
+ if rec.ProposedFix != nil {
+ appendChatContextLine(b, "Proposed Fix", rec.ProposedFix.Description)
+ appendChatContextLine(b, "Proposed Fix Risk", rec.ProposedFix.RiskLevel)
+ appendChatContextLine(b, "Proposed Fix Target Host", rec.ProposedFix.TargetHost)
+ appendChatContextLine(b, "Proposed Fix Rationale", rec.ProposedFix.Rationale)
+ if rec.ProposedFix.Destructive {
+ appendChatContextLine(b, "Proposed Fix Destructive", "true")
+ }
+ switch len(rec.ProposedFix.Commands) {
+ case 0:
+ case 1:
+ appendChatContextLine(b, "Proposed Fix Commands", "1 command recorded for approval context")
+ default:
+ appendChatContextLine(b, "Proposed Fix Commands", fmt.Sprintf("%d commands recorded for approval context", len(rec.ProposedFix.Commands)))
+ }
+ }
+}
+
+func appendInvestigationRecordEvidenceContext(b *strings.Builder, evidence []aicontracts.InvestigationRecordEvidence) {
+ if len(evidence) == 0 {
+ return
+ }
+
+ count := 0
+ for _, item := range evidence {
+ if count >= findingChatContextListLimit {
+ break
+ }
+ parts := make([]string, 0, 3)
+ if strings.TrimSpace(item.Kind) != "" {
+ parts = append(parts, strings.TrimSpace(item.Kind))
+ }
+ if strings.TrimSpace(item.ID) != "" {
+ parts = append(parts, strings.TrimSpace(item.ID))
+ }
+ if strings.TrimSpace(item.Summary) != "" {
+ parts = append(parts, strings.TrimSpace(item.Summary))
+ }
+ if len(parts) == 0 {
+ continue
+ }
+ count++
+ appendChatContextLine(b, fmt.Sprintf("Evidence %d", count), strings.Join(parts, ": "))
+ }
+ if remaining := len(evidence) - count; remaining > 0 {
+ appendChatContextLine(b, "Evidence Additional Count", fmt.Sprintf("%d", remaining))
+ }
+}
+
+func appendStringListChatContext(b *strings.Builder, label string, values []string) {
+ count := 0
+ for _, value := range values {
+ normalized := strings.TrimSpace(value)
+ if normalized == "" {
+ continue
+ }
+ if count >= findingChatContextListLimit {
+ break
+ }
+ count++
+ appendChatContextLine(b, fmt.Sprintf("%s %d", label, count), normalized)
+ }
+ if remaining := len(values) - count; remaining > 0 {
+ appendChatContextLine(b, fmt.Sprintf("%s Additional Count", label), fmt.Sprintf("%d", remaining))
+ }
+}
+
+func appendChatContextLine(b *strings.Builder, label string, value string) {
+ label = strings.TrimSpace(label)
+ value = strings.TrimSpace(value)
+ if label == "" && value == "" {
+ b.WriteByte('\n')
+ return
+ }
+ if label == "" {
+ b.WriteString(value)
+ b.WriteByte('\n')
+ return
+ }
+ if value == "" {
+ b.WriteString(label)
+ b.WriteByte('\n')
+ return
+ }
+ b.WriteString(label)
+ b.WriteString(": ")
+ b.WriteString(value)
+ b.WriteByte('\n')
+}
+
// HandleChat handles POST /api/ai/chat - streaming chat
func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
// CORS
@@ -929,29 +1080,7 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
store := h.GetUnifiedStoreForOrg(GetOrgID(ctx))
if store != nil {
if f := store.Get(req.FindingID); f != nil {
- findingCtx := fmt.Sprintf("[Finding Context]\nID: %s\nTitle: %s\nSeverity: %s\nCategory: %s\nResource: %s (%s)\nDescription: %s",
- f.ID, f.Title, f.Severity, f.Category, f.ResourceName, f.ResourceType, f.Description)
- if f.Recommendation != "" {
- findingCtx += fmt.Sprintf("\nRecommendation: %s", f.Recommendation)
- }
- if f.Evidence != "" {
- findingCtx += fmt.Sprintf("\nEvidence: %s", f.Evidence)
- }
- if f.InvestigationStatus != "" {
- findingCtx += fmt.Sprintf("\nInvestigation Status: %s", f.InvestigationStatus)
- }
- if f.InvestigationOutcome != "" {
- findingCtx += fmt.Sprintf("\nInvestigation Outcome: %s", f.InvestigationOutcome)
- }
- if f.UserNote != "" {
- findingCtx += fmt.Sprintf("\nUser Note: %s", f.UserNote)
- }
- if f.AcknowledgedAt != nil {
- findingCtx += fmt.Sprintf("\nAcknowledged At: %s", f.AcknowledgedAt.Format(time.RFC3339))
- }
- if f.Node != "" {
- findingCtx += fmt.Sprintf("\nNode: %s", f.Node)
- }
+ findingCtx := buildUnifiedFindingChatContext(f)
prompt = findingCtx + "\n\n---\nUser message: " + prompt
}
}
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index 777fc30956..b73077c9d0 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -13,9 +13,11 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
@@ -546,6 +548,102 @@ func TestHandleChat_PassesAutonomousModeOverride(t *testing.T) {
assert.Equal(t, http.StatusOK, w.Code)
}
+func TestHandleChat_IncludesInvestigationRecordContext(t *testing.T) {
+ cfg := &config.Config{}
+ h := newTestAIHandler(cfg, nil, nil)
+ mockSvc := new(MockAIService)
+ h.defaultService = mockSvc
+
+ detectedAt := time.Date(2026, 5, 6, 12, 0, 0, 0, time.UTC)
+ completedAt := detectedAt.Add(3 * time.Minute)
+ store := unified.NewUnifiedStore(unified.DefaultAlertToFindingConfig())
+ store.AddFromAI(&unified.UnifiedFinding{
+ ID: "finding-123",
+ Source: unified.SourceAIPatrol,
+ Severity: unified.SeverityCritical,
+ Category: unified.CategoryPerformance,
+ ResourceID: "vm-100",
+ ResourceName: "web-server",
+ ResourceType: "vm",
+ Node: "pve-1",
+ Title: "High CPU usage",
+ Description: "CPU stayed above 95%.",
+ Recommendation: "Review the backup job.",
+ Evidence: "cpu=96%",
+ DetectedAt: detectedAt,
+ LastSeenAt: detectedAt,
+ InvestigationStatus: "completed",
+ InvestigationOutcome: "fix_queued",
+ InvestigationAttempts: 1,
+ InvestigationRecord: &aicontracts.InvestigationRecord{
+ ID: "investigation-123",
+ FindingID: "finding-123",
+ SessionID: "session-123",
+ Subject: aicontracts.InvestigationRecordSubject{
+ ResourceID: "vm-100",
+ ResourceName: "web-server",
+ ResourceType: "vm",
+ Node: "pve-1",
+ },
+ Trigger: aicontracts.InvestigationRecordTrigger{
+ FindingKey: "cpu-high",
+ Source: "ai-patrol",
+ Severity: "critical",
+ Category: "performance",
+ Title: "High CPU usage",
+ DetectedAt: detectedAt,
+ Description: "CPU stayed above 95%.",
+ },
+ Status: aicontracts.InvestigationStatusCompleted,
+ Outcome: aicontracts.OutcomeFixQueued,
+ Confidence: aicontracts.InvestigationRecordConfidenceHigh,
+ Evidence: []aicontracts.InvestigationRecordEvidence{{Kind: "metrics", Summary: "CPU stayed above 95% for 10 minutes"}},
+ Conclusion: "Backup job saturated CPU.",
+ RecommendedAction: "Approve a controlled service restart after backup completion.",
+ ProposedFix: &aicontracts.InvestigationRecordFix{
+ ID: "fix-123",
+ Description: "Restart the workload service",
+ Commands: []string{"systemctl restart workload.service"},
+ RiskLevel: "medium",
+ TargetHost: "pve-1",
+ Rationale: "The process is wedged after backup IO pressure.",
+ },
+ Verification: []string{"CPU returned below 50%"},
+ ToolsUsed: []string{"metrics.history", "ssh.exec"},
+ StartedAt: detectedAt,
+ CompletedAt: &completedAt,
+ ApprovalID: "approval-123",
+ },
+ })
+ h.SetUnifiedStore(store)
+
+ mockSvc.On("IsRunning").Return(true)
+ mockSvc.
+ On("ExecuteStream", mock.Anything, mock.Anything, mock.Anything).
+ Return(nil).
+ Run(func(args mock.Arguments) {
+ reqArg := args.Get(1).(chat.ExecuteRequest)
+ assert.Equal(t, "finding-123", reqArg.FindingID)
+ assert.Contains(t, reqArg.Prompt, "[Finding Context]")
+ assert.Contains(t, reqArg.Prompt, "[Investigation Record]")
+ assert.Contains(t, reqArg.Prompt, "Conclusion: Backup job saturated CPU.")
+ assert.Contains(t, reqArg.Prompt, "Recommended Action: Approve a controlled service restart after backup completion.")
+ assert.Contains(t, reqArg.Prompt, "Evidence 1: metrics: CPU stayed above 95% for 10 minutes")
+ assert.Contains(t, reqArg.Prompt, "Proposed Fix: Restart the workload service")
+ assert.Contains(t, reqArg.Prompt, "Proposed Fix Commands: 1 command recorded for approval context")
+ assert.Contains(t, reqArg.Prompt, "User message: What happened?")
+ assert.NotContains(t, reqArg.Prompt, "systemctl restart workload.service")
+ })
+
+ body := `{"prompt":"What happened?","finding_id":"finding-123"}`
+ req := httptest.NewRequest("POST", "/api/ai/chat", strings.NewReader(body))
+ w := httptest.NewRecorder()
+
+ h.HandleChat(w, req)
+
+ assert.Equal(t, http.StatusOK, w.Code)
+}
+
func TestHandleChat_DropsLegacyMentionTypes(t *testing.T) {
cfg := &config.Config{}
h := newTestAIHandler(cfg, nil, nil)