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.

Add Patrol run history Assistant handoff

rcourtman40c0b22bc4c2
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index b4c8334ae6..cd74558d9e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -931,6 +931,12 @@ the canonical monitored-system blocked payload.
`error_summary` and `error_detail` whenever an erroring run has structured
provider, model, tool, context-window, quota, auth, rate-limit, or
connectivity failure context
+ and the Patrol run-history Assistant handoff contract, so frontend
+ run-history consumers may pass a bounded `[Patrol Run Context]` block,
+ scoped resource references, run outcome/coverage facts, sanitized analysis,
+ and structured runtime failure summary/detail as model-only chat context
+ while forcing request-local approval-required mode and leaving retries,
+ configuration changes, and remediation authority outside the chat payload
and the main Patrol page composition boundary, so once that governed
secondary area exists inside the summary shell the same payloads must not
also drive a second page-level status strip elsewhere on the route
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index ace4150a1f..310c388654 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -831,7 +831,13 @@ frontend primitive boundary.
that same feature helper to attach bounded model-only assessment,
verification, latest-run, supporting-context evidence, active-finding, and
resource reference context while forcing request-local approval-required
- mode. Active-finding entries in that assessment handoff may add live pending
+ mode. Patrol run-history handoffs must also use that feature helper rather
+ than a row-local Assistant prompt, so the shared drawer receives only a
+ generic visible briefing plus bounded model-only run context, scoped
+ resource references, runtime failure summary/detail, and
+ `autonomousMode:false` while the Patrol feature remains the source of run
+ copy and retry/configuration guidance. Active-finding entries in that
+ assessment handoff may add live pending
approval posture only as safe structured metadata: approval ID, pending
status, risk, target, requested/expiry timestamps, action plan identity,
approval policy, plan expiry, dry-run posture, and command count. Those
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index d2cd124863..42926d067e 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -243,6 +243,16 @@ Patrol-specific presentation helpers.
frame Assistant as explanation, prioritization, and safe next-step review
rather than a generic reactive chat
box.
+ Patrol run-history entries may also open Assistant for a selected run, but
+ that handoff must flow through the same Patrol-owned investigation-context
+ model rather than a row-local prompt. The handoff may pass bounded run
+ history facts such as run ID/type/status, trigger, timing, coverage, scope,
+ findings snapshot availability, outcome counts, tool/triage effort,
+ `error_summary`, `error_detail`, sanitized Patrol analysis, and scoped
+ resource references as model-only context. It must force request-local
+ approval-required mode, present a source-named visible drawer briefing, and
+ frame Assistant as explanation and next-step review rather than execution or
+ automatic retry authority.
## Current State
@@ -306,6 +316,15 @@ references from a generic assessment discussion, including approval-policy and
dry-run posture when available, and its initial prompt must prioritize those
approvals or action references before broader assessment discussion while
command payloads stay out of the drawer.
+Run-history rows now follow that same Assistant handoff model. A selected
+`frontend-modern/src/components/patrol/RunHistoryEntry.tsx` row may open
+Assistant through
+`frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts` with a
+`[Patrol Run Context]` block, scoped resource references, runtime failure
+summary/detail when present, bounded outcome and coverage facts, and a visible
+`Patrol run attached` drawer briefing. The row must not create a second
+prompt-only Assistant shortcut or imply that Assistant can retry Patrol,
+change provider configuration, or execute remediation from run-history context.
That active-runtime label must stay operational rather than verdict-like: the
header chip should communicate that Patrol is enabled or available, not imply
that infrastructure health is currently good merely because the runtime is on.
diff --git a/frontend-modern/src/components/patrol/RunHistoryEntry.tsx b/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
index e4b0702205..66f20914ad 100644
--- a/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
+++ b/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
@@ -3,6 +3,8 @@ import type { Accessor } from 'solid-js';
import type { PatrolRunRecord } from '@/api/patrol';
import { FindingsPanel } from '@/components/AI/FindingsPanel';
import { renderMarkdown } from '@/components/AI/aiChatUtils';
+import { buildPatrolRunAssistantHandoff } from '@/features/patrol/patrolInvestigationContextModel';
+import { aiChatStore } from '@/stores/aiChat';
import { RunToolCallTrace } from './RunToolCallTrace';
import {
formatDurationMs,
@@ -38,6 +40,7 @@ import FilterXIcon from 'lucide-solid/icons/filter-x';
import SparklesIcon from 'lucide-solid/icons/sparkles';
import MailIcon from 'lucide-solid/icons/mail';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
+import MessageSquareIcon from 'lucide-solid/icons/message-square';
interface PatrolStreamState {
phase: Accessor<string>;
@@ -152,10 +155,19 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
const runIsHealthy = isPatrolRunHealthy(run.status, run.error_count);
const coverageSummary = getPatrolRunCoverageSummary(run);
const hasFindingsSnapshot = run.finding_ids !== undefined;
- const runStatus = getPatrolRunStatusPresentation(run.status, run.error_count, hasFindingsSnapshot);
+ const runStatus = getPatrolRunStatusPresentation(
+ run.status,
+ run.error_count,
+ hasFindingsSnapshot,
+ );
const runErrorSummary = String(run.error_summary || '').trim();
const runErrorDetail = String(run.error_detail || '').trim();
const hasRunErrorDetail = run.error_count > 0 && (runErrorSummary || runErrorDetail);
+ const handleDiscussRun = (event: Event) => {
+ event.stopPropagation();
+ const handoff = buildPatrolRunAssistantHandoff(run);
+ aiChatStore.openWithPrompt(handoff.prompt, handoff.context);
+ };
return (
<div
@@ -191,7 +203,9 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
<Show when={run.rejected_findings}>
<span class="text-muted">• {run.rejected_findings} rejected</span>
</Show>
- <Show when={!hasFindingsSnapshot && run.new_findings === 0 && run.existing_findings === 0}>
+ <Show
+ when={!hasFindingsSnapshot && run.new_findings === 0 && run.existing_findings === 0}
+ >
<span class="text-blue-600 dark:text-blue-400">• Findings snapshot unavailable</span>
</Show>
</div>
@@ -201,74 +215,86 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
<Show when={props.selected}>
<div class="px-3 pb-3 border-t border-blue-200 dark:border-blue-800 mt-0">
{/* Section 1: Narrative Summary */}
- <div class="mt-3 flex items-start gap-2 text-sm text-base-content">
- <SparklesIcon class="w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 flex-shrink-0" />
- <p>
- {coverageSummary ? (
- <>
- {coverageSummary}{' '}
- {formatDurationMs(run.duration_ms) ? (
- <>
- in <strong>{formatDurationMs(run.duration_ms)}</strong>
- </>
- ) : (
- ''
- )}{' '}
- {run.tool_call_count > 0 ? (
- <>
- using <strong>{run.tool_call_count}</strong> tool call
- {run.tool_call_count !== 1 ? 's' : ''}
- </>
- ) : (
- ''
- )}
- .{' '}
- </>
- ) : (
- <>
- Patrol completed
- {formatDurationMs(run.duration_ms) ? (
- <>
- {' '}
- in <strong>{formatDurationMs(run.duration_ms)}</strong>
- </>
- ) : (
- ''
- )}
- .{' '}
- </>
- )}
- {run.new_findings > 0 ? (
- <>
- Found <strong>{run.new_findings}</strong> new issue
- {run.new_findings !== 1 ? 's' : ''}
- {run.auto_fix_count > 0 ? (
- <>
- , remediated <strong>{run.auto_fix_count}</strong>
- </>
- ) : (
- ''
- )}
- .
- </>
- ) : run.existing_findings > 0 ? (
- <>
- No new issues, but <strong>{run.existing_findings}</strong> existing issue
- {run.existing_findings !== 1 ? 's' : ''} remain.
- </>
- ) : !hasFindingsSnapshot ? (
- <span class="text-blue-600 dark:text-blue-400">
- This run predates findings snapshots, so run-specific findings cannot be fully
- verified.
- </span>
- ) : runIsHealthy ? (
- <span class="text-green-600 dark:text-green-400">All clear — no new issues.</span>
- ) : (
- <span class="text-amber-600 dark:text-amber-400">
- Patrol completed with issues requiring review.
- </span>
- )}
- </p>
+ <div class="mt-3 flex flex-wrap items-start justify-between gap-3">
+ <div class="flex min-w-0 flex-1 items-start gap-2 text-sm text-base-content">
+ <SparklesIcon class="w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 flex-shrink-0" />
+ <p>
+ {coverageSummary ? (
+ <>
+ {coverageSummary}{' '}
+ {formatDurationMs(run.duration_ms) ? (
+ <>
+ in <strong>{formatDurationMs(run.duration_ms)}</strong>
+ </>
+ ) : (
+ ''
+ )}{' '}
+ {run.tool_call_count > 0 ? (
+ <>
+ using <strong>{run.tool_call_count}</strong> tool call
+ {run.tool_call_count !== 1 ? 's' : ''}
+ </>
+ ) : (
+ ''
+ )}
+ .{' '}
+ </>
+ ) : (
+ <>
+ Patrol completed
+ {formatDurationMs(run.duration_ms) ? (
+ <>
+ {' '}
+ in <strong>{formatDurationMs(run.duration_ms)}</strong>
+ </>
+ ) : (
+ ''
+ )}
+ .{' '}
+ </>
+ )}
+ {run.new_findings > 0 ? (
+ <>
+ Found <strong>{run.new_findings}</strong> new issue
+ {run.new_findings !== 1 ? 's' : ''}
+ {run.auto_fix_count > 0 ? (
+ <>
+ , remediated <strong>{run.auto_fix_count}</strong>
+ </>
+ ) : (
+ ''
+ )}
+ .
+ </>
+ ) : run.existing_findings > 0 ? (
+ <>
+ No new issues, but <strong>{run.existing_findings}</strong> existing issue
+ {run.existing_findings !== 1 ? 's' : ''} remain.
+ </>
+ ) : !hasFindingsSnapshot ? (
+ <span class="text-blue-600 dark:text-blue-400">
+ This run predates findings snapshots, so run-specific findings cannot be fully
+ verified.
+ </span>
+ ) : runIsHealthy ? (
+ <span class="text-green-600 dark:text-green-400">All clear — no new issues.</span>
+ ) : (
+ <span class="text-amber-600 dark:text-amber-400">
+ Patrol completed with issues requiring review.
+ </span>
+ )}
+ </p>
+ </div>
+ <button
+ type="button"
+ data-testid="patrol-run-assistant-button"
+ onClick={handleDiscussRun}
+ class="inline-flex flex-shrink-0 items-center gap-1.5 rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs font-semibold text-base-content shadow-sm transition-colors hover:bg-surface-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
+ title="Discuss this Patrol run with Assistant"
+ >
+ <MessageSquareIcon class="h-3.5 w-3.5" aria-hidden="true" />
+ <span>Discuss</span>
+ </button>
</div>
<Show when={hasRunErrorDetail}>
diff --git a/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx b/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
index 3c5178ae01..b89e084415 100644
--- a/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
@@ -1,12 +1,13 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { PatrolRunRecord } from '@/api/patrol';
import { RunHistoryEntry } from '../RunHistoryEntry';
-const { findingsPanelState } = vi.hoisted(() => ({
+const { findingsPanelState, openWithPromptMock } = vi.hoisted(() => ({
findingsPanelState: {
latestProps: null as Record<string, unknown> | null,
},
+ openWithPromptMock: vi.fn(),
}));
vi.mock('@/components/AI/FindingsPanel', () => ({
@@ -38,6 +39,12 @@ vi.mock('@/components/AI/aiChatUtils', () => ({
renderMarkdown: (content: string) => content,
}));
+vi.mock('@/stores/aiChat', () => ({
+ aiChatStore: {
+ openWithPrompt: openWithPromptMock,
+ },
+}));
+
describe('RunHistoryEntry', () => {
const patrolStream = {
phase: () => '',
@@ -88,6 +95,7 @@ describe('RunHistoryEntry', () => {
beforeEach(() => {
findingsPanelState.latestProps = null;
+ openWithPromptMock.mockReset();
});
afterEach(() => {
@@ -184,13 +192,13 @@ describe('RunHistoryEntry', () => {
expect(screen.queryByText('• 1 resources')).not.toBeInTheDocument();
expect(screen.queryByText('Scoped to 2 resources')).not.toBeInTheDocument();
expect(
- screen.getByText((_, element) =>
- element?.tagName === 'P' &&
- (element.textContent?.includes('Checked 1 of 2 scoped resources') ??
- false) &&
- (element.textContent?.includes('453ms') ?? false) &&
- (element.textContent?.includes('Patrol completed with issues requiring review.') ??
- false),
+ screen.getByText(
+ (_, element) =>
+ element?.tagName === 'P' &&
+ (element.textContent?.includes('Checked 1 of 2 scoped resources') ?? false) &&
+ (element.textContent?.includes('453ms') ?? false) &&
+ (element.textContent?.includes('Patrol completed with issues requiring review.') ??
+ false),
),
).toBeInTheDocument();
});
@@ -219,6 +227,57 @@ describe('RunHistoryEntry', () => {
expect(screen.getByText('error')).toBeInTheDocument();
});
+ it('opens Assistant with structured run history context', () => {
+ render(() => (
+ <RunHistoryEntry
+ run={{
+ ...run,
+ id: 'run-runtime-error',
+ effective_scope_resource_ids: ['vm-100'],
+ scope_resource_types: ['vm'],
+ resources_checked: 1,
+ guests_checked: 1,
+ error_count: 1,
+ status: 'error',
+ tool_call_count: 1,
+ error_summary: 'Selected model does not support Patrol tools',
+ error_detail:
+ "agentic patrol failed: API error (404): No endpoints found that support the provided 'tool_choice' value.",
+ }}
+ isLive={false}
+ patrolStream={patrolStream}
+ selected={true}
+ onSelect={vi.fn()}
+ />
+ ));
+
+ fireEvent.click(screen.getByRole('button', { name: /discuss/i }));
+
+ expect(openWithPromptMock).toHaveBeenCalledTimes(1);
+ const [prompt, context] = openWithPromptMock.mock.calls[0];
+ expect(prompt).toContain('Discuss this Pulse Patrol run');
+ expect(prompt).toContain('Start by explaining the Patrol runtime failure');
+ expect(context).toMatchObject({
+ targetType: 'patrol-run',
+ targetId: 'run-runtime-error',
+ autonomousMode: false,
+ handoffResources: [{ id: 'vm-100', type: 'vm' }],
+ context: {
+ source: 'pulse-patrol-run',
+ runId: 'run-runtime-error',
+ errorCount: 1,
+ handoffResourceCount: 1,
+ },
+ });
+ expect(context.handoffContext).toContain('[Patrol Run Context]');
+ expect(context.handoffContext).toContain('Runtime Failure: Selected model');
+ expect(context.handoffContext).toContain('tool_choice');
+ expect(context.briefing).toMatchObject({
+ title: 'Patrol run attached',
+ actionLabel: 'Review Patrol runtime failure',
+ });
+ });
+
it('keeps zero-coverage scoped runs on the shared coverage narrative', () => {
render(() => (
<RunHistoryEntry
@@ -241,12 +300,13 @@ describe('RunHistoryEntry', () => {
expect(screen.getByText('• Checked 0 of 2 scoped resources')).toBeInTheDocument();
expect(screen.queryByText('Scoped to 2 resources')).not.toBeInTheDocument();
expect(
- screen.getByText((_, element) =>
- element?.tagName === 'P' &&
- (element.textContent?.includes('Checked 0 of 2 scoped resources') ?? false) &&
- (element.textContent?.includes('453ms') ?? false) &&
- (element.textContent?.includes('Patrol completed with issues requiring review.') ??
- false),
+ screen.getByText(
+ (_, element) =>
+ element?.tagName === 'P' &&
+ (element.textContent?.includes('Checked 0 of 2 scoped resources') ?? false) &&
+ (element.textContent?.includes('453ms') ?? false) &&
+ (element.textContent?.includes('Patrol completed with issues requiring review.') ??
+ false),
),
).toBeInTheDocument();
expect(screen.queryByText(/^Patrol completed in 453ms/)).not.toBeInTheDocument();
@@ -270,9 +330,10 @@ describe('RunHistoryEntry', () => {
));
expect(
- screen.getByText((_, element) =>
- element?.tagName === 'P' &&
- (element.textContent?.includes('No new issues, but 2 existing issues remain.') ?? false),
+ screen.getByText(
+ (_, element) =>
+ element?.tagName === 'P' &&
+ (element.textContent?.includes('No new issues, but 2 existing issues remain.') ?? false),
),
).toBeInTheDocument();
expect(screen.queryByText('All clear — no new issues.')).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 1b5cb2777d..75d6d4a3cb 100644
--- a/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { RemediationPlan } from '@/api/ai';
+import type { PatrolRunRecord } from '@/api/patrol';
import {
buildPatrolAssessmentAssistantHandoff,
@@ -9,6 +10,7 @@ import {
buildPatrolAssistantFindingPrompt,
buildPatrolAssistantProposedFixBriefingInput,
buildPatrolInvestigationContextSummary,
+ buildPatrolRunAssistantHandoff,
buildPatrolInvestigationRecordPresentation,
buildPatrolRemediationPlanAssistantBriefing,
buildPatrolRemediationPlanAssistantPrompt,
@@ -364,6 +366,83 @@ describe('patrolInvestigationContextModel', () => {
expect(JSON.stringify(handoff)).not.toContain('systemctl restart workload.service');
});
+ it('builds a model-only Assistant handoff for a Patrol run runtime failure', () => {
+ const run: PatrolRunRecord = {
+ id: 'run-runtime-error',
+ started_at: '2026-05-07T12:00:00Z',
+ completed_at: '2026-05-07T12:00:03Z',
+ duration_ms: 3000,
+ type: 'scoped',
+ trigger_reason: 'alert_fired',
+ scope_resource_ids: ['vm-100'],
+ effective_scope_resource_ids: ['vm-100'],
+ scope_resource_types: ['vm'],
+ resources_checked: 1,
+ nodes_checked: 0,
+ guests_checked: 1,
+ docker_checked: 0,
+ storage_checked: 0,
+ hosts_checked: 0,
+ truenas_checked: 0,
+ pbs_checked: 0,
+ pmg_checked: 0,
+ kubernetes_checked: 0,
+ new_findings: 0,
+ existing_findings: 0,
+ rejected_findings: 0,
+ resolved_findings: 0,
+ auto_fix_count: 0,
+ findings_summary: 'Runtime failure prevented analysis.',
+ finding_ids: [],
+ error_count: 1,
+ error_summary: 'Selected model does not support Patrol tools',
+ error_detail:
+ "agentic patrol failed: API error (404): No endpoints found that support the provided 'tool_choice' value.",
+ status: 'error',
+ triage_flags: 0,
+ triage_skipped_llm: false,
+ tool_call_count: 1,
+ ai_analysis: '<|DSML|trace>provider trace</|DSML|trace>Visible runtime summary.',
+ };
+
+ const handoff = buildPatrolRunAssistantHandoff(run);
+
+ expect(handoff.prompt).toContain('Discuss this Pulse Patrol run');
+ expect(handoff.prompt).toContain('Start by explaining the Patrol runtime failure');
+ expect(handoff.context.autonomousMode).toBe(false);
+ expect(handoff.context).toMatchObject({
+ targetType: 'patrol-run',
+ targetId: 'run-runtime-error',
+ context: {
+ source: 'pulse-patrol-run',
+ runId: 'run-runtime-error',
+ effectiveStatus: 'error',
+ errorCount: 1,
+ resourcesChecked: 1,
+ findingSnapshotCount: 0,
+ handoffResourceCount: 1,
+ },
+ });
+ expect(handoff.context.handoffResources).toEqual([{ id: 'vm-100', type: 'vm' }]);
+ expect(handoff.context.handoffContext).toContain('[Patrol Run Context]');
+ expect(handoff.context.handoffContext).toContain('Source: Pulse Patrol run history');
+ expect(handoff.context.handoffContext).toContain('Run Type: Scoped run');
+ expect(handoff.context.handoffContext).toContain('Runtime Failure: Selected model');
+ expect(handoff.context.handoffContext).toContain('tool_choice');
+ expect(handoff.context.handoffContext).toContain('Patrol Analysis: Visible runtime summary.');
+ expect(handoff.context.briefing).toMatchObject({
+ sourceLabel: 'Pulse Patrol',
+ title: 'Patrol run attached',
+ actionLabel: 'Review Patrol runtime failure',
+ suggestedPrompts: [
+ 'Explain why this Patrol run failed',
+ 'List provider or model checks',
+ 'What should I retry after fixing it?',
+ ],
+ });
+ expect(JSON.stringify(handoff)).not.toContain('provider trace');
+ });
+
it('builds operator-facing Patrol record presentation without exposing raw commands', () => {
const presentation = buildPatrolInvestigationRecordPresentation({
id: 'record-1',
diff --git a/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts b/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
index eeea829690..d6c149c80b 100644
--- a/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
+++ b/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
@@ -4,6 +4,7 @@ import type {
ResourceCorrelation,
} from '@/types/aiIntelligence';
import type { ApprovalRequest, InvestigationRecord, RemediationPlan } from '@/api/ai';
+import type { PatrolRunRecord } from '@/api/patrol';
import type {
AIChatContext,
AIChatContextBriefing,
@@ -21,6 +22,18 @@ import {
formatResourceCorrelationSummary,
sortResourceCorrelations,
} from '@/utils/resourceCorrelationPresentation';
+import {
+ formatDurationMs,
+ formatScope,
+ formatTriggerReason,
+ getCanonicalScopeResourceIds,
+ sanitizeAnalysis,
+} from '@/utils/patrolFormat';
+import {
+ getPatrolRunCoverageSummary,
+ getPatrolRunKindLabel,
+ getPatrolRunStatusPresentation,
+} from '@/utils/patrolRunPresentation';
export interface PatrolInvestigationContextSummaryInput {
recentChangesCount?: number | null;
@@ -235,11 +248,17 @@ export interface PatrolAssistantFindingHandoff {
context: Omit<AIChatContext, 'initialPrompt'>;
}
+export interface PatrolRunAssistantHandoff {
+ prompt: string;
+ context: Omit<AIChatContext, 'initialPrompt'>;
+}
+
const MAX_ASSESSMENT_FINDINGS = 5;
const MAX_ASSESSMENT_RECENT_CHANGES = 3;
const MAX_ASSESSMENT_CORRELATIONS = 3;
const MAX_ASSESSMENT_RESOURCES = 8;
const MAX_ASSESSMENT_HANDOFF_ACTIONS = 4;
+const MAX_PATROL_RUN_HANDOFF_RESOURCES = 8;
const MAX_PATROL_BRIEFING_SUGGESTED_PROMPTS = 3;
export function buildPatrolInvestigationContextSummary(
@@ -545,6 +564,43 @@ export function buildPatrolAssistantFindingHandoff(
};
}
+export function buildPatrolRunAssistantHandoff(run: PatrolRunRecord): PatrolRunAssistantHandoff {
+ const runId = normalizeText(run.id);
+ const kindLabel = getPatrolRunKindLabel(run.type);
+ const findingsSnapshotAvailable = run.finding_ids !== undefined;
+ const statusLabel = getPatrolRunStatusPresentation(
+ run.status || 'unknown',
+ run.error_count || 0,
+ findingsSnapshotAvailable,
+ ).label;
+ const runtimeFailure = formatPatrolRunRuntimeFailure(run);
+ const handoffResources = buildPatrolRunHandoffResources(run);
+
+ return {
+ prompt: buildPatrolRunAssistantPrompt(run, kindLabel, statusLabel, runtimeFailure),
+ context: {
+ targetType: 'patrol-run',
+ targetId: runId || undefined,
+ autonomousMode: false,
+ handoffContext: buildPatrolRunAssistantModelContext(run, kindLabel, statusLabel),
+ handoffResources: handoffResources.length > 0 ? handoffResources : undefined,
+ briefing: buildPatrolRunAssistantBriefing(run, kindLabel, statusLabel, runtimeFailure),
+ context: {
+ source: 'pulse-patrol-run',
+ runId: runId || undefined,
+ runType: normalizeText(run.type) || undefined,
+ triggerReason: normalizeText(run.trigger_reason) || undefined,
+ status: normalizeText(run.status) || undefined,
+ effectiveStatus: statusLabel,
+ errorCount: normalizeNonNegativeCount(run.error_count),
+ resourcesChecked: normalizeNonNegativeCount(run.resources_checked),
+ findingSnapshotCount: Array.isArray(run.finding_ids) ? run.finding_ids.length : undefined,
+ handoffResourceCount: handoffResources.length,
+ },
+ },
+ };
+}
+
export function buildPatrolAssistantFindingHandoffActions(
finding: PatrolAssessmentAssistantFindingInput,
): AIChatHandoffAction[] {
@@ -815,6 +871,270 @@ function buildPatrolAssessmentAssistantModelContext(
.join('\n');
}
+function buildPatrolRunAssistantPrompt(
+ run: PatrolRunRecord,
+ kindLabel: string,
+ statusLabel: string,
+ runtimeFailure: string | undefined,
+): string {
+ const runId = normalizeText(run.id);
+ const trigger = formatTriggerReason(run.trigger_reason);
+ const runLabel = [kindLabel, runId].filter(isNonEmptyString).join(' ') || 'Patrol run';
+ const focus = runtimeFailure
+ ? `Start by explaining the Patrol runtime failure (${truncateContextText(runtimeFailure, 180)}), what likely caused it, and what should be checked before retrying Patrol.`
+ : `Start by explaining the run outcome (${statusLabel}${
+ trigger ? `, ${trigger.toLowerCase()}` : ''
+ }) and the safest next operational step from the attached context.`;
+
+ return [
+ `Discuss this Pulse Patrol run: ${runLabel}.`,
+ focus,
+ 'Use the attached model-only run history context before suggesting next actions.',
+ 'Do not infer, repeat, or execute raw command text from this handoff.',
+ ]
+ .filter(isNonEmptyString)
+ .join('\n\n');
+}
+
+function buildPatrolRunAssistantModelContext(
+ run: PatrolRunRecord,
+ kindLabel: string,
+ statusLabel: string,
+): string {
+ const scope = formatScope(run);
+ const coverage = formatPatrolRunCoverage(run);
+ const runtimeFailure = formatPatrolRunRuntimeFailure(run);
+ const outcomes = formatPatrolRunOutcomes(run);
+ const timing = formatPatrolRunTiming(run);
+ const effort = formatPatrolRunEffort(run);
+ const analysis = truncateContextText(sanitizeAnalysis(run.ai_analysis), 500);
+
+ return [
+ '[Patrol Run Context]',
+ 'Source: Pulse Patrol run history',
+ formatContextLine('Run ID', run.id),
+ formatContextLine('Run Type', kindLabel),
+ formatContextLine('Status', statusLabel),
+ formatContextLine('Trigger', formatTriggerReason(run.trigger_reason)),
+ formatContextLine('Timing', timing),
+ formatContextLine('Coverage', coverage),
+ formatContextLine('Scope', scope),
+ formatContextLine('Findings Snapshot', formatPatrolRunFindingsSnapshot(run)),
+ formatContextLine('Outcomes', outcomes),
+ formatContextLine('Runtime Failure', runtimeFailure),
+ formatContextLine('Effort', effort),
+ formatContextLine('Findings Summary', run.findings_summary),
+ formatContextLine('Patrol Analysis', analysis),
+ 'Operator Boundary: This Patrol run handoff is model-only context for explanation and review. Configuration changes, diagnostics, remediation, and command execution require explicit governed operator action.',
+ ]
+ .filter(isNonEmptyString)
+ .join('\n');
+}
+
+function buildPatrolRunAssistantBriefing(
+ run: PatrolRunRecord,
+ kindLabel: string,
+ statusLabel: string,
+ runtimeFailure: string | undefined,
+): AIChatContextBriefing {
+ const coverage = formatPatrolRunCoverage(run);
+ const outcomes = formatPatrolRunOutcomes(run);
+ const timing = formatPatrolRunTiming(run);
+ const effort = formatPatrolRunEffort(run);
+ const analysis = truncateContextText(sanitizeAnalysis(run.ai_analysis), 220);
+
+ return {
+ sourceLabel: 'Pulse Patrol',
+ title: 'Patrol run attached',
+ subject: [kindLabel, normalizeText(run.id)].filter(isNonEmptyString).join(' ') || kindLabel,
+ statusLabel: [statusLabel, formatTriggerReason(run.trigger_reason), coverage]
+ .filter(isNonEmptyString)
+ .join(' · '),
+ detailLines: [
+ runtimeFailure ? `Runtime failure: ${runtimeFailure}` : undefined,
+ timing,
+ formatScope(run),
+ effort,
+ ]
+ .filter(isNonEmptyString)
+ .slice(0, 4),
+ evidence: [outcomes, run.findings_summary, analysis].filter(isNonEmptyString).slice(0, 4),
+ actionLabel: runtimeFailure ? 'Review Patrol runtime failure' : 'Discuss Patrol run outcome',
+ safetyNote:
+ 'Assistant can explain the Patrol run context; retries, configuration changes, and remediation remain operator-controlled.',
+ suggestedPrompts: buildPatrolRunSuggestedPrompts(Boolean(runtimeFailure)),
+ };
+}
+
+function buildPatrolRunSuggestedPrompts(hasRuntimeFailure: boolean): string[] {
+ if (hasRuntimeFailure) {
+ return formatPatrolSuggestedPrompts([
+ 'Explain why this Patrol run failed',
+ 'List provider or model checks',
+ 'What should I retry after fixing it?',
+ ]);
+ }
+
+ return formatPatrolSuggestedPrompts([
+ 'Summarize this Patrol run',
+ 'What needs attention from this run?',
+ 'What should I verify next?',
+ ]);
+}
+
+function buildPatrolRunHandoffResources(run: PatrolRunRecord): AIChatHandoffResource[] {
+ const type =
+ run.scope_resource_types?.length === 1 ? normalizeText(run.scope_resource_types[0]) : '';
+ const resources = new Map<string, AIChatHandoffResource>();
+
+ for (const id of getCanonicalScopeResourceIds(run) ?? []) {
+ const normalizedID = normalizeText(id);
+ if (!normalizedID || resources.size >= MAX_PATROL_RUN_HANDOFF_RESOURCES) continue;
+ resources.set(normalizedID, {
+ id: normalizedID,
+ type: type || undefined,
+ });
+ }
+
+ return Array.from(resources.values());
+}
+
+function formatPatrolRunRuntimeFailure(run: PatrolRunRecord): string | undefined {
+ const summary = normalizeText(run.error_summary);
+ const detail = normalizeText(run.error_detail);
+ if (summary && detail && summary !== detail) {
+ return `${summary}: ${truncateContextText(detail, 260)}`;
+ }
+ if (summary || detail) {
+ return summary || detail;
+ }
+ const errorCount = normalizeNonNegativeCount(run.error_count);
+ if (errorCount > 0) {
+ return `${errorCount} Patrol runtime error${errorCount === 1 ? '' : 's'} recorded`;
+ }
+ return undefined;
+}
+
+function formatPatrolRunCoverage(run: PatrolRunRecord): string | undefined {
+ const coverage = getPatrolRunCoverageSummary(run);
+ if (coverage) return coverage;
+
+ return formatBriefingStringList(
+ [
+ normalizeNonNegativeCount(run.resources_checked) > 0
+ ? `${normalizeNonNegativeCount(run.resources_checked)} resources checked`
+ : undefined,
+ normalizeNonNegativeCount(run.nodes_checked) > 0
+ ? `${normalizeNonNegativeCount(run.nodes_checked)} nodes`
+ : undefined,
+ normalizeNonNegativeCount(run.guests_checked) > 0
+ ? `${normalizeNonNegativeCount(run.guests_checked)} VMs`
+ : undefined,
+ normalizeNonNegativeCount(run.docker_checked) > 0
+ ? `${normalizeNonNegativeCount(run.docker_checked)} containers`
+ : undefined,
+ normalizeNonNegativeCount(run.storage_checked) > 0
+ ? `${normalizeNonNegativeCount(run.storage_checked)} storage resources`
+ : undefined,
+ normalizeNonNegativeCount(run.hosts_checked) > 0
+ ? `${normalizeNonNegativeCount(run.hosts_checked)} agents`
+ : undefined,
+ normalizeNonNegativeCount(run.truenas_checked) > 0
+ ? `${normalizeNonNegativeCount(run.truenas_checked)} TrueNAS systems`
+ : undefined,
+ normalizeNonNegativeCount(run.kubernetes_checked) > 0
+ ? `${normalizeNonNegativeCount(run.kubernetes_checked)} Kubernetes resources`
+ : undefined,
+ ],
+ 8,
+ 'coverage facts',
+ );
+}
+
+function formatPatrolRunFindingsSnapshot(run: PatrolRunRecord): string {
+ if (run.finding_ids === undefined) {
+ return 'unavailable for this run';
+ }
+ const count = run.finding_ids.length;
+ return `${count} finding ID${count === 1 ? '' : 's'} captured`;
+}
+
+function formatPatrolRunOutcomes(run: PatrolRunRecord): string | undefined {
+ return formatBriefingStringList(
+ [
+ normalizeNonNegativeCount(run.new_findings) > 0
+ ? `${normalizeNonNegativeCount(run.new_findings)} new finding${
+ normalizeNonNegativeCount(run.new_findings) === 1 ? '' : 's'
+ }`
+ : undefined,
+ normalizeNonNegativeCount(run.existing_findings) > 0
+ ? `${normalizeNonNegativeCount(run.existing_findings)} existing finding${
+ normalizeNonNegativeCount(run.existing_findings) === 1 ? '' : 's'
+ }`
+ : undefined,
+ normalizeNonNegativeCount(run.resolved_findings) > 0
+ ? `${normalizeNonNegativeCount(run.resolved_findings)} resolved finding${
+ normalizeNonNegativeCount(run.resolved_findings) === 1 ? '' : 's'
+ }`
+ : undefined,
+ normalizeNonNegativeCount(run.rejected_findings) > 0
+ ? `${normalizeNonNegativeCount(run.rejected_findings)} rejected finding${
+ normalizeNonNegativeCount(run.rejected_findings) === 1 ? '' : 's'
+ }`
+ : undefined,
+ normalizeNonNegativeCount(run.auto_fix_count) > 0
+ ? `${normalizeNonNegativeCount(run.auto_fix_count)} auto-remediation${
+ normalizeNonNegativeCount(run.auto_fix_count) === 1 ? '' : 's'
+ }`
+ : undefined,
+ normalizeNonNegativeCount(run.error_count) > 0
+ ? `${normalizeNonNegativeCount(run.error_count)} error${
+ normalizeNonNegativeCount(run.error_count) === 1 ? '' : 's'
+ }`
+ : undefined,
+ ],
+ 8,
+ 'outcome facts',
+ );
+}
+
+function formatPatrolRunTiming(run: PatrolRunRecord): string | undefined {
+ return formatBriefingStringList(
+ [
+ normalizeText(run.started_at) ? `started ${normalizeText(run.started_at)}` : undefined,
+ normalizeText(run.completed_at) ? `completed ${normalizeText(run.completed_at)}` : undefined,
+ formatDurationMs(run.duration_ms)
+ ? `duration ${formatDurationMs(run.duration_ms)}`
+ : undefined,
+ ],
+ 3,
+ 'timing facts',
+ );
+}
+
+function formatPatrolRunEffort(run: PatrolRunRecord): string | undefined {
+ const tokenCount =
+ normalizeNonNegativeCount(run.input_tokens) + normalizeNonNegativeCount(run.output_tokens);
+ return formatBriefingStringList(
+ [
+ normalizeNonNegativeCount(run.tool_call_count) > 0
+ ? `${normalizeNonNegativeCount(run.tool_call_count)} tool call${
+ normalizeNonNegativeCount(run.tool_call_count) === 1 ? '' : 's'
+ }`
+ : undefined,
+ normalizeNonNegativeCount(run.triage_flags) > 0
+ ? `${normalizeNonNegativeCount(run.triage_flags)} triage flag${
+ normalizeNonNegativeCount(run.triage_flags) === 1 ? '' : 's'
+ }`
+ : undefined,
+ run.triage_skipped_llm ? 'LLM skipped for deterministic triage' : undefined,
+ tokenCount > 0 ? `${tokenCount} tokens` : undefined,
+ ],
+ 4,
+ 'effort facts',
+ );
+}
+
function buildPatrolAssessmentHandoffResources(
input: PatrolAssessmentAssistantHandoffInput,
): AIChatHandoffResource[] {
diff --git a/tests/integration/tests/18-patrol-runtime-state.spec.ts b/tests/integration/tests/18-patrol-runtime-state.spec.ts
index 8e2b62a581..ac400dc09f 100644
--- a/tests/integration/tests/18-patrol-runtime-state.spec.ts
+++ b/tests/integration/tests/18-patrol-runtime-state.spec.ts
@@ -633,9 +633,9 @@ test.describe("Patrol runtime-state browser contract", () => {
await applyButton.click();
await expect(page.getByText(PATROL_AUTONOMY_PRO_REQUIRED)).toBeVisible();
- await expect(page.getByText("Failed to save advanced settings")).toHaveCount(
- 0,
- );
+ await expect(
+ page.getByText("Failed to save advanced settings"),
+ ).toHaveCount(0);
});
test("surfaces scoped trigger context inside the summary and split trigger controls on the Patrol page", async ({
@@ -682,5 +682,16 @@ test.describe("Patrol runtime-state browser contract", () => {
page.getByText("Selected model does not support Patrol tools"),
).toBeVisible();
await expect(page.getByText(/tool_choice/)).toBeVisible();
+
+ await page.getByTestId("patrol-run-assistant-button").click();
+ const assistantContext = page.getByLabel("Assistant context");
+ await expect(assistantContext).toBeVisible();
+ await expect(assistantContext).toContainText("Patrol run attached");
+ await expect(assistantContext).toContainText(
+ "Review Patrol runtime failure",
+ );
+ await expect(assistantContext).toContainText(
+ "Selected model does not support Patrol tools",
+ );
});
});