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.

Bind governed action intent across Patrol and web

rcourtman2e9520da812f
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 7d0c877dbe..3f2aa51bae 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -5927,6 +5927,16 @@ source authority, repeated timestamps, unknown states, and capability loss
fail closed. Existing stopped guests therefore do not become findings merely
because Patrol or Pulse restarted.
+Production admission also reconciles the transition against the canonical,
+organization-scoped action-audit store before emitting. A completed `shutdown`
+or `stop` may suppress the finding only for the same canonical guest when its
+canonical `ActionResultV2` execution succeeded and a recorded approval falls
+between the prior fresh running observation and the newer stopped observation.
+Legacy-only results, failed or nonterminal actions, other capabilities or
+resources, out-of-window decisions, cross-organization stores, and audit-read
+errors do not suppress the warning. Suppression advances the observation
+baseline so the intentional stop cannot surface one cycle later.
+
The watcher runs before the model-provider gate whenever guest analysis is
enabled, so detection is not conditional on an available LLM. Fresh running
evidence reconciles an active finding; stale or incomplete state does not, and
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 081de579e0..15f45dd95e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7362,6 +7362,10 @@ both requests to the exact reviewed plan by sending `planHash`; the REST fields
remain optional for transport compatibility, but any presented hash that differs
from the authoritative persisted plan fails with
`action_plan_identity_mismatch` before a decision write or executor dispatch.
+The canonical browser writer in `frontend-modern/src/api/resourceActions.ts`
+requires a non-empty reviewed hash for both mutations and always serializes it.
+Actions and Patrol browser consumers must pass the hash from the plan currently
+shown to the operator; a missing hash fails locally without issuing a request.
Mobile uses the durable pending inbox so approved-but-not-run and executing
actions survive refresh and remain visible. It must reject through the decision
endpoint; legacy
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 588ab9286d..9f996bd40f 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -4961,3 +4961,6 @@ recovery, delivery, and next-step content actionable at desktop and 390-pixel
phone viewports. Responsive layout must not hide the exact parameter authority,
evidence source, or recovery instruction, and it must not add a duplicate legacy
verification card when `ActionResultV2` is present.
+Its action controls are also plan-identity-bound: a missing reviewed `planHash`
+renders explicit replan guidance and hides approve, reject, and run controls,
+while an actionable record sends the exact displayed hash on every mutation.
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 779e32e779..0b1c69384e 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -1985,6 +1985,11 @@ and offers an Assistant handoff. Collapsed-row attention state must consult the
same investigation action reference, so it cannot claim there is no approval
while the expanded panel has one. Browser proof must exercise pending,
terminal-verified, and legacy-history states rather than judging only source.
+The typed reference must also carry the exact reviewed `planHash` before
+`ApprovalSection` exposes approve, reject, or run controls. Decision and
+execution requests pass that same hash through the canonical browser client;
+missing identity is an explicit replan-required state and never falls back to
+action id alone.
Backend Patrol finding reconciliation now reads `ActionResultV2`: execution
failed or known-not-run maps to fix failure; confirmed verification maps to
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index a70806b91a..1503726390 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -616,6 +616,11 @@ into one outcome. Docker lifecycle controls may create a canonical plan and
open this shared review, but may not auto-approve, auto-execute, or use a
second-click local confirmation. Proof is owned by the colocated action tests,
`DockerNativeTables.test.tsx`, and desktop journeys 81 and 83.
+The shared review may offer decision or execution controls only when the
+current record carries a non-empty `planHash`; every mutation passes that exact
+displayed identity through the canonical resource-action client. Legacy or
+mixed-version records without it remain reviewable but require replanning and
+cannot create a browser mutation.
1. Add new resource types and identity fields in `internal/unifiedresources/types.go`
Agentless availability endpoints enter the model as
diff --git a/frontend-modern/src/api/__tests__/actionAudit.test.ts b/frontend-modern/src/api/__tests__/actionAudit.test.ts
index f2f02ed66e..155b507bc3 100644
--- a/frontend-modern/src/api/__tests__/actionAudit.test.ts
+++ b/frontend-modern/src/api/__tests__/actionAudit.test.ts
@@ -38,11 +38,25 @@ const canonicalEvidenceDigest = (evidence: ActionEvidence): string => {
};
const makeAgentEvidence = (id: string): ActionEvidence => {
- const envelope: ActionEvidence = { version: 1, id, observerId: 'agent:pve-1', observerKind: 'unified_agent', observerTrustDomain: 'agent:pve-1', executorTrustDomain: 'agent:pve-1', method: 'typed_read_after_write', subjectId: 'proxmox:node:pve-1', observedAt: '2026-07-12T10:01:00Z', receivedAt: '2026-07-12T10:05:00Z', digest: '' };
+ const envelope: ActionEvidence = {
+ version: 1,
+ id,
+ observerId: 'agent:pve-1',
+ observerKind: 'unified_agent',
+ observerTrustDomain: 'agent:pve-1',
+ executorTrustDomain: 'agent:pve-1',
+ method: 'typed_read_after_write',
+ subjectId: 'proxmox:node:pve-1',
+ observedAt: '2026-07-12T10:01:00Z',
+ receivedAt: '2026-07-12T10:05:00Z',
+ digest: '',
+ };
return { ...envelope, digest: canonicalEvidenceDigest(envelope) };
};
-const legacyVerificationStatus = (truth: ActionResultV2): 'verified' | 'failed' | 'unverified' | 'unknown' =>
+const legacyVerificationStatus = (
+ truth: ActionResultV2,
+): 'verified' | 'failed' | 'unverified' | 'unknown' =>
truth.verification.status === 'confirmed'
? 'verified'
: truth.verification.status === 'contradicted'
@@ -54,17 +68,40 @@ const legacyVerificationStatus = (truth: ActionResultV2): 'verified' | 'failed'
const isTask10FixtureValid = (truth: ActionResultV2): boolean => {
if (truth.execution.status !== 'succeeded' && !truth.execution.reasonCode?.trim()) return false;
const evidenceCount = truth.verification.evidence?.length ?? 0;
- if (truth.verification.status === 'inconclusive' && !truth.verification.reasonCode?.trim()) return false;
- if (truth.verification.status === 'not_attempted' && (truth.verification.evidenceClass !== 'none' || evidenceCount !== 0)) return false;
- if ((truth.verification.status === 'confirmed' || truth.verification.status === 'contradicted') && (truth.verification.evidenceClass === 'none' || evidenceCount === 0)) return false;
+ if (truth.verification.status === 'inconclusive' && !truth.verification.reasonCode?.trim())
+ return false;
+ if (
+ truth.verification.status === 'not_attempted' &&
+ (truth.verification.evidenceClass !== 'none' || evidenceCount !== 0)
+ )
+ return false;
+ if (
+ (truth.verification.status === 'confirmed' || truth.verification.status === 'contradicted') &&
+ (truth.verification.evidenceClass === 'none' || evidenceCount === 0)
+ )
+ return false;
if (truth.verification.evidenceClass === 'none' && evidenceCount !== 0) return false;
if (truth.verification.evidenceClass !== 'none' && evidenceCount === 0) return false;
- if ((truth.verification.evidence ?? []).some((evidence) => {
- const observedAt = new Date(evidence.observedAt).valueOf();
- const receivedAt = new Date(evidence.receivedAt).valueOf();
- return !Number.isFinite(observedAt) || !Number.isFinite(receivedAt) || receivedAt < observedAt || evidence.digest !== canonicalEvidenceDigest(evidence);
- })) return false;
- if (truth.verification.evidenceClass === 'independent' && (truth.verification.evidence ?? []).some((evidence) => evidence.observerTrustDomain === evidence.executorTrustDomain)) return false;
+ if (
+ (truth.verification.evidence ?? []).some((evidence) => {
+ const observedAt = new Date(evidence.observedAt).valueOf();
+ const receivedAt = new Date(evidence.receivedAt).valueOf();
+ return (
+ !Number.isFinite(observedAt) ||
+ !Number.isFinite(receivedAt) ||
+ receivedAt < observedAt ||
+ evidence.digest !== canonicalEvidenceDigest(evidence)
+ );
+ })
+ )
+ return false;
+ if (
+ truth.verification.evidenceClass === 'independent' &&
+ (truth.verification.evidence ?? []).some(
+ (evidence) => evidence.observerTrustDomain === evidence.executorTrustDomain,
+ )
+ )
+ return false;
return true;
};
@@ -212,13 +249,65 @@ describe('ActionAuditAPI', () => {
it('preserves typed APT ActionResultV2 axes and the durable receipt without normalization', async () => {
const evidence = makeAgentEvidence('apt-update-evidence');
const audit = {
- id: 'apt-update', createdAt: '2026-07-12T10:00:00Z', updatedAt: '2026-07-12T10:05:00Z', state: 'completed' as const,
- request: { requestId: 'apt-request', resourceId: 'proxmox:node:pve-1', capabilityName: 'install_os_updates', params: {}, reason: 'Resolve the current update finding', requestedBy: 'pulse_patrol' },
- plan: { actionId: 'apt-update', requestId: 'apt-request', allowed: true, requiresApproval: true, approvalPolicy: 'admin' as const, rollbackAvailable: false },
- result: { success: false, actionResultV2: { version: 2 as const, execution: { status: 'inconclusive' as const, reasonCode: 'possible_partial_effect', summary: 'APT package updates: phase=install; 6 pending before, 3 pending after; package manager health: unhealthy; recovery required: true; reboot required: false' }, verification: { status: 'contradicted' as const, evidenceClass: 'agent_attested' as const, summary: 'Three updates remain.', evidence: [evidence] }, compensation: { support: 'unavailable' as const, status: 'not_available' as const } } },
+ id: 'apt-update',
+ createdAt: '2026-07-12T10:00:00Z',
+ updatedAt: '2026-07-12T10:05:00Z',
+ state: 'completed' as const,
+ request: {
+ requestId: 'apt-request',
+ resourceId: 'proxmox:node:pve-1',
+ capabilityName: 'install_os_updates',
+ params: {},
+ reason: 'Resolve the current update finding',
+ requestedBy: 'pulse_patrol',
+ },
+ plan: {
+ actionId: 'apt-update',
+ requestId: 'apt-request',
+ allowed: true,
+ requiresApproval: true,
+ approvalPolicy: 'admin' as const,
+ rollbackAvailable: false,
+ },
+ result: {
+ success: false,
+ actionResultV2: {
+ version: 2 as const,
+ execution: {
+ status: 'inconclusive' as const,
+ reasonCode: 'possible_partial_effect',
+ summary:
+ 'APT package updates: phase=install; 6 pending before, 3 pending after; package manager health: unhealthy; recovery required: true; reboot required: false',
+ },
+ verification: {
+ status: 'contradicted' as const,
+ evidenceClass: 'agent_attested' as const,
+ summary: 'Three updates remain.',
+ evidence: [evidence],
+ },
+ compensation: { support: 'unavailable' as const, status: 'not_available' as const },
+ },
+ },
verificationOutcome: { status: 'failed' as const },
};
- const detail = { audit, events: [], attempt: { id: 'attempt-1', actionId: audit.id, state: 'receipt_recorded' as const, createdAt: audit.createdAt, updatedAt: audit.updatedAt, dispatchCount: 1 }, receipt: { attemptId: 'attempt-1', actionId: audit.id, transportRequestId: 'transport-1', receivedAt: audit.updatedAt } };
+ const detail = {
+ audit,
+ events: [],
+ attempt: {
+ id: 'attempt-1',
+ actionId: audit.id,
+ state: 'receipt_recorded' as const,
+ createdAt: audit.createdAt,
+ updatedAt: audit.updatedAt,
+ dispatchCount: 1,
+ },
+ receipt: {
+ attemptId: 'attempt-1',
+ actionId: audit.id,
+ transportRequestId: 'transport-1',
+ receivedAt: audit.updatedAt,
+ },
+ };
apiFetchJSONMock.mockResolvedValueOnce(detail);
await expect(ResourceActionsAPI.getAction(audit.id)).resolves.toEqual(detail);
@@ -228,38 +317,126 @@ describe('ActionAuditAPI', () => {
verification: { status: 'contradicted', evidenceClass: 'agent_attested' },
compensation: { support: 'unavailable', status: 'not_available' },
});
- expect(detail.receipt).toMatchObject({ attemptId: 'attempt-1', transportRequestId: 'transport-1' });
+ expect(detail.receipt).toMatchObject({
+ attemptId: 'attempt-1',
+ transportRequestId: 'transport-1',
+ });
expect(detail.audit.verificationOutcome?.status).toBe('failed');
- expect(detail.audit.result?.actionResultV2?.verification.evidence?.[0].digest).toBe(canonicalEvidenceDigest(evidence));
+ expect(detail.audit.result?.actionResultV2?.verification.evidence?.[0].digest).toBe(
+ canonicalEvidenceDigest(evidence),
+ );
});
it('guards tier-5 APT fixtures against impossible Task10 evidence combinations', () => {
const evidence = makeAgentEvidence('evidence-1');
const compensation = { support: 'unavailable' as const, status: 'not_available' as const };
const valid = [
- { version: 2, execution: { status: 'succeeded' }, verification: { status: 'confirmed', evidenceClass: 'agent_attested', evidence: [evidence] }, compensation },
- { version: 2, execution: { status: 'inconclusive', reasonCode: 'possible_partial_effect' }, verification: { status: 'contradicted', evidenceClass: 'agent_attested', evidence: [evidence] }, compensation },
- { version: 2, execution: { status: 'inconclusive', reasonCode: 'possible_partial_effect' }, verification: { status: 'inconclusive', evidenceClass: 'none', reasonCode: 'package_manager_health_unknown' }, compensation },
+ {
+ version: 2,
+ execution: { status: 'succeeded' },
+ verification: {
+ status: 'confirmed',
+ evidenceClass: 'agent_attested',
+ evidence: [evidence],
+ },
+ compensation,
+ },
+ {
+ version: 2,
+ execution: { status: 'inconclusive', reasonCode: 'possible_partial_effect' },
+ verification: {
+ status: 'contradicted',
+ evidenceClass: 'agent_attested',
+ evidence: [evidence],
+ },
+ compensation,
+ },
+ {
+ version: 2,
+ execution: { status: 'inconclusive', reasonCode: 'possible_partial_effect' },
+ verification: {
+ status: 'inconclusive',
+ evidenceClass: 'none',
+ reasonCode: 'package_manager_health_unknown',
+ },
+ compensation,
+ },
] satisfies ActionResultV2[];
expect(valid.every(isTask10FixtureValid)).toBe(true);
expect(valid.map(legacyVerificationStatus)).toEqual(['verified', 'failed', 'unverified']);
- const notAttempted = { version: 2, execution: { status: 'not_run', reasonCode: 'preflight_refused' }, verification: { status: 'not_attempted', evidenceClass: 'none' }, compensation } satisfies ActionResultV2;
+ const notAttempted = {
+ version: 2,
+ execution: { status: 'not_run', reasonCode: 'preflight_refused' },
+ verification: { status: 'not_attempted', evidenceClass: 'none' },
+ compensation,
+ } satisfies ActionResultV2;
expect(isTask10FixtureValid(notAttempted)).toBe(true);
expect(legacyVerificationStatus(notAttempted)).toBe('unknown');
expect(evidence.digest).toBe(canonicalEvidenceDigest(evidence));
- expect(new Date(evidence.receivedAt).valueOf()).toBeGreaterThanOrEqual(new Date(evidence.observedAt).valueOf());
+ expect(new Date(evidence.receivedAt).valueOf()).toBeGreaterThanOrEqual(
+ new Date(evidence.observedAt).valueOf(),
+ );
const impossible = [
{ ...valid[0], verification: { status: 'confirmed', evidenceClass: 'none', evidence: [] } },
- { ...valid[1], verification: { status: 'contradicted', evidenceClass: 'agent_attested', evidence: [] } },
+ {
+ ...valid[1],
+ verification: { status: 'contradicted', evidenceClass: 'agent_attested', evidence: [] },
+ },
{ ...valid[2], verification: { status: 'inconclusive', evidenceClass: 'none' } },
- { ...valid[2], verification: { status: 'inconclusive', evidenceClass: 'none', reasonCode: 'package_manager_health_unknown', evidence: [evidence] } },
- { ...valid[2], verification: { status: 'not_attempted', evidenceClass: 'agent_attested', evidence: [evidence] } },
+ {
+ ...valid[2],
+ verification: {
+ status: 'inconclusive',
+ evidenceClass: 'none',
+ reasonCode: 'package_manager_health_unknown',
+ evidence: [evidence],
+ },
+ },
+ {
+ ...valid[2],
+ verification: {
+ status: 'not_attempted',
+ evidenceClass: 'agent_attested',
+ evidence: [evidence],
+ },
+ },
{ ...valid[2], execution: { status: 'inconclusive' } },
- { ...valid[0], verification: { ...valid[0].verification, evidence: [{ ...evidence, digest: `sha256:${'a'.repeat(64)}` }] } },
- { ...valid[0], verification: { ...valid[0].verification, evidence: [{ ...evidence, receivedAt: '2026-07-12T09:59:00Z', digest: canonicalEvidenceDigest({ ...evidence, receivedAt: '2026-07-12T09:59:00Z', digest: '' }) }] } },
+ {
+ ...valid[0],
+ verification: {
+ ...valid[0].verification,
+ evidence: [{ ...evidence, digest: `sha256:${'a'.repeat(64)}` }],
+ },
+ },
+ {
+ ...valid[0],
+ verification: {
+ ...valid[0].verification,
+ evidence: [
+ {
+ ...evidence,
+ receivedAt: '2026-07-12T09:59:00Z',
+ digest: canonicalEvidenceDigest({
+ ...evidence,
+ receivedAt: '2026-07-12T09:59:00Z',
+ digest: '',
+ }),
+ },
+ ],
+ },
+ },
] as ActionResultV2[];
- expect(impossible.map(isTask10FixtureValid)).toEqual([false, false, false, false, false, false, false, false]);
+ expect(impossible.map(isTask10FixtureValid)).toEqual([
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ ]);
});
it('builds the canonical resource-scoped action audit query', async () => {
@@ -555,12 +732,13 @@ describe('ActionAuditAPI', () => {
ResourceActionsAPI.decideAction(
'action/docker/restart',
'approved',
+ 'sha256:reviewed-plan',
'operator confirmed restart',
),
).resolves.toEqual(decision);
- await expect(ResourceActionsAPI.executeAction('action/docker/restart')).resolves.toEqual(
- execution,
- );
+ await expect(
+ ResourceActionsAPI.executeAction('action/docker/restart', 'sha256:reviewed-plan'),
+ ).resolves.toEqual(execution);
expect(apiFetchJSONMock).toHaveBeenNthCalledWith(
1,
@@ -569,6 +747,7 @@ describe('ActionAuditAPI', () => {
method: 'POST',
body: JSON.stringify({
outcome: 'approved',
+ planHash: 'sha256:reviewed-plan',
reason: 'operator confirmed restart',
}),
},
@@ -578,8 +757,18 @@ describe('ActionAuditAPI', () => {
'/api/actions/action%2Fdocker%2Frestart/execute',
{
method: 'POST',
- body: JSON.stringify({}),
+ body: JSON.stringify({ planHash: 'sha256:reviewed-plan' }),
},
);
});
+
+ it('refuses action mutations without a reviewed plan identity', async () => {
+ await expect(ResourceActionsAPI.decideAction('action-1', 'approved', ' ')).rejects.toThrow(
+ 'reviewed action plan identity',
+ );
+ await expect(ResourceActionsAPI.executeAction('action-1', '')).rejects.toThrow(
+ 'reviewed action plan identity',
+ );
+ expect(apiFetchJSONMock).not.toHaveBeenCalled();
+ });
});
diff --git a/frontend-modern/src/api/resourceActions.ts b/frontend-modern/src/api/resourceActions.ts
index 05677e7e9b..45c5ab41b1 100644
--- a/frontend-modern/src/api/resourceActions.ts
+++ b/frontend-modern/src/api/resourceActions.ts
@@ -12,6 +12,16 @@ import type {
export type ActionDecisionOutcome = 'approved' | 'rejected';
+function reviewedPlanHash(planHash: string): string {
+ const normalized = planHash.trim();
+ if (!normalized) {
+ throw new Error(
+ 'A reviewed action plan identity is required. Create a new plan before continuing.',
+ );
+ }
+ return normalized;
+}
+
export class ResourceActionsAPI {
static async listActions(view: ActionInboxView, limit = 100): Promise<ActionInboxResponse> {
const params = new URLSearchParams({ view, limit: String(limit) });
@@ -36,6 +46,7 @@ export class ResourceActionsAPI {
static async decideAction(
actionId: string,
outcome: ActionDecisionOutcome,
+ planHash: string,
reason?: string,
): Promise<ActionDecisionResponse> {
return apiFetchJSON<ActionDecisionResponse>(
@@ -44,18 +55,26 @@ export class ResourceActionsAPI {
method: 'POST',
body: JSON.stringify({
outcome,
+ planHash: reviewedPlanHash(planHash),
...(reason ? { reason } : {}),
}),
},
);
}
- static async executeAction(actionId: string, reason?: string): Promise<ActionExecutionResponse> {
+ static async executeAction(
+ actionId: string,
+ planHash: string,
+ reason?: string,
+ ): Promise<ActionExecutionResponse> {
return apiFetchJSON<ActionExecutionResponse>(
`/api/actions/${encodeURIComponent(actionId)}/execute`,
{
method: 'POST',
- body: JSON.stringify(reason ? { reason } : {}),
+ body: JSON.stringify({
+ planHash: reviewedPlanHash(planHash),
+ ...(reason ? { reason } : {}),
+ }),
},
);
}
diff --git a/frontend-modern/src/components/patrol/ApprovalSection.tsx b/frontend-modern/src/components/patrol/ApprovalSection.tsx
index 96a3a34256..6a791871d1 100644
--- a/frontend-modern/src/components/patrol/ApprovalSection.tsx
+++ b/frontend-modern/src/components/patrol/ApprovalSection.tsx
@@ -135,9 +135,10 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
await aiIntelligenceStore.loadFindings();
};
- const execute = async (actionId: string) => {
+ const execute = async (actionId: string, planHash: string) => {
const result = await ResourceActionsAPI.executeAction(
actionId,
+ planHash,
'Operator requested execution from the Patrol action review',
);
setLatestAudit(result.audit);
@@ -154,16 +155,18 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
const handleApproveAndRun = async (event: Event) => {
event.stopPropagation();
const current = action();
- if (!current) return;
+ const planHash = current?.plan.planHash?.trim();
+ if (!current || !planHash) return;
setBusyAction('approve');
try {
const decision = await ResourceActionsAPI.decideAction(
current.action_id,
'approved',
+ planHash,
'Approved from the Patrol action review',
);
setLatestAudit(decision.audit);
- await execute(current.action_id);
+ await execute(current.action_id, planHash);
await refreshPatrol();
} catch (error) {
notificationStore.error((error as Error).message || 'Failed to approve and run action');
@@ -175,10 +178,11 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
const handleRun = async (event: Event) => {
event.stopPropagation();
const current = action();
- if (!current) return;
+ const planHash = current?.plan.planHash?.trim();
+ if (!current || !planHash) return;
setBusyAction('execute');
try {
- await execute(current.action_id);
+ await execute(current.action_id, planHash);
await refreshPatrol();
} catch (error) {
notificationStore.error((error as Error).message || 'Failed to run action');
@@ -190,12 +194,14 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
const handleReject = async (event: Event) => {
event.stopPropagation();
const current = action();
- if (!current) return;
+ const planHash = current?.plan.planHash?.trim();
+ if (!current || !planHash) return;
setBusyAction('reject');
try {
const decision = await ResourceActionsAPI.decideAction(
current.action_id,
'rejected',
+ planHash,
'Rejected from the Patrol action review',
);
setLatestAudit(decision.audit);
@@ -287,6 +293,9 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
{(currentAction) => {
const presentation = createMemo(() => statePresentation(currentAction().state));
const preflight = createMemo(() => currentAction().plan.preflight);
+ const reviewedPlanHash = createMemo(
+ () => currentAction().plan.planHash?.trim() || '',
+ );
return (
<div class="space-y-3">
<div class="flex flex-wrap items-center gap-2">
@@ -350,8 +359,24 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
</div>
</Show>
+ <Show when={!reviewedPlanHash()}>
+ <div
+ role="alert"
+ class="rounded border border-amber-300 bg-amber-50 p-2 text-sm text-amber-900 dark:bg-amber-950/40 dark:text-amber-200"
+ >
+ This action has no reviewed plan identity. Create a new plan before approving
+ or running it.
+ </div>
+ </Show>
+
<div class="flex flex-wrap items-center gap-2 border-t border-border-subtle pt-3">
- <Show when={canManageAction() && currentAction().state === 'pending_approval'}>
+ <Show
+ when={
+ reviewedPlanHash() &&
+ canManageAction() &&
+ currentAction().state === 'pending_approval'
+ }
+ >
<Button
type="button"
variant="success"
@@ -381,6 +406,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
<Show
when={
canManageAction() &&
+ reviewedPlanHash() &&
(currentAction().state === 'planned' ||
currentAction().state === 'approved')
}
diff --git a/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx b/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
index 02fc2377a6..a762d526b2 100644
--- a/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
@@ -53,6 +53,7 @@ function actionReference(stateValue: PatrolActionReference['state']): PatrolActi
requiresApproval: stateValue === 'pending_approval',
approvalPolicy: stateValue === 'pending_approval' ? 'admin' : 'none',
rollbackAvailable: true,
+ planHash: 'sha256:reviewed-plan',
message: 'Restart the unhealthy workload',
preflight: {
target: 'vm:42',
@@ -159,10 +160,12 @@ describe('ApprovalSection typed action lifecycle', () => {
expect(decideActionMock).toHaveBeenCalledWith(
'act-1',
'approved',
+ 'sha256:reviewed-plan',
'Approved from the Patrol action review',
);
expect(executeActionMock).toHaveBeenCalledWith(
'act-1',
+ 'sha256:reviewed-plan',
'Operator requested execution from the Patrol action review',
);
});
@@ -190,6 +193,7 @@ describe('ApprovalSection typed action lifecycle', () => {
expect(decideActionMock).toHaveBeenCalledWith(
'act-1',
'rejected',
+ 'sha256:reviewed-plan',
'Rejected from the Patrol action review',
),
);
@@ -215,6 +219,19 @@ describe('ApprovalSection typed action lifecycle', () => {
);
});
+ it('fails closed when the typed action has no reviewed plan identity', async () => {
+ const action = actionReference('pending_approval');
+ delete action.plan.planHash;
+ getInvestigationMock.mockResolvedValue(investigation(action));
+
+ render(() => <ApprovalSection findingId="finding-1" investigationOutcome="fix_queued" />);
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('no reviewed plan identity');
+ expect(screen.queryByRole('button', { name: /approve and run/i })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /^reject$/i })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /run action/i })).not.toBeInTheDocument();
+ });
+
it('fails closed when only a legacy investigation artifact remains', async () => {
getInvestigationMock.mockResolvedValue({
...investigation(),
diff --git a/frontend-modern/src/features/actions/ActionReviewDialog.tsx b/frontend-modern/src/features/actions/ActionReviewDialog.tsx
index f285e2a40c..9afd143c3a 100644
--- a/frontend-modern/src/features/actions/ActionReviewDialog.tsx
+++ b/frontend-modern/src/features/actions/ActionReviewDialog.tsx
@@ -27,6 +27,7 @@ export const ActionReviewDialog: Component<{
const hasCurrentPolicyProvenance = createMemo(
() => audit()?.plan.policyDecision?.status === 'resolved',
);
+ const reviewedPlanHash = createMemo(() => audit()?.plan.planHash?.trim() || '');
const aptParametersValid = createMemo(() => {
const action = audit();
return action ? getAPTActionPresentation(action)?.parametersValid !== false : false;
@@ -37,17 +38,28 @@ export const ActionReviewDialog: Component<{
const timestamp = new Date(expiresAt).valueOf();
return Number.isNaN(timestamp) || timestamp <= clock();
});
- const canDecide = () => hasCurrentPolicyProvenance() && aptParametersValid() && !isExpired() && audit()?.state === 'pending_approval';
+ const canDecide = () =>
+ reviewedPlanHash() &&
+ hasCurrentPolicyProvenance() &&
+ aptParametersValid() &&
+ !isExpired() &&
+ audit()?.state === 'pending_approval';
const canExecute = () =>
+ reviewedPlanHash() &&
hasCurrentPolicyProvenance() &&
aptParametersValid() &&
!isExpired() &&
(audit()?.state === 'approved' ||
(audit()?.state === 'planned' && !audit()?.plan.requiresApproval));
const invalidActionMessage = createMemo(() => {
- if (!hasCurrentPolicyProvenance()) return 'This action has no current server policy provenance. Close it and create a new plan before approving or running anything.';
- if (!aptParametersValid()) return 'This host-maintenance action contains unexpected operator-selected parameters. Close it and create a new plan; do not approve or run this record.';
- if (isExpired()) return 'This action review expired. Close it and create a new plan so current resource and policy state can be checked again.';
+ if (!reviewedPlanHash())
+ return 'This action has no reviewed plan identity. Close it and create a new plan before approving or running anything.';
+ if (!hasCurrentPolicyProvenance())
+ return 'This action has no current server policy provenance. Close it and create a new plan before approving or running anything.';
+ if (!aptParametersValid())
+ return 'This host-maintenance action contains unexpected operator-selected parameters. Close it and create a new plan; do not approve or run this record.';
+ if (isExpired())
+ return 'This action review expired. Close it and create a new plan so current resource and policy state can be checked again.';
return '';
});
@@ -61,47 +73,127 @@ export const ActionReviewDialog: Component<{
const decide = async (outcome: 'approved' | 'rejected') => {
const action = audit();
if (!action || busy()) return;
- setBusy(true); setError('');
+ setBusy(true);
+ setError('');
try {
- await ResourceActionsAPI.decideAction(action.id, outcome, `Operator ${outcome} from Actions review.`);
+ await ResourceActionsAPI.decideAction(
+ action.id,
+ outcome,
+ reviewedPlanHash(),
+ `Operator ${outcome} from Actions review.`,
+ );
await refresh();
- notificationStore.success(outcome === 'approved' ? 'Action approved. Review once more before running it.' : 'Action rejected.');
+ notificationStore.success(
+ outcome === 'approved'
+ ? 'Action approved. Review once more before running it.'
+ : 'Action rejected.',
+ );
if (outcome === 'rejected') props.onClose();
} catch (cause) {
- const message = cause instanceof Error ? cause.message : 'The decision could not be recorded.';
+ const message =
+ cause instanceof Error ? cause.message : 'The decision could not be recorded.';
setError(message);
- } finally { setBusy(false); }
+ } finally {
+ setBusy(false);
+ }
};
const execute = async () => {
const action = audit();
if (!action || busy()) return;
- setBusy(true); setError('');
+ setBusy(true);
+ setError('');
try {
- await ResourceActionsAPI.executeAction(action.id, 'Operator confirmed execution from Actions review.');
+ await ResourceActionsAPI.executeAction(
+ action.id,
+ reviewedPlanHash(),
+ 'Operator confirmed execution from Actions review.',
+ );
await refresh();
- notificationStore.success('Action dispatch response recorded. Review execution, verification, and recovery separately.');
+ notificationStore.success(
+ 'Action dispatch response recorded. Review execution, verification, and recovery separately.',
+ );
} catch (cause) {
const message = cause instanceof Error ? cause.message : 'The action could not be run.';
setError(message);
- try { await refresh(); } catch { /* keep the actionable execution error */ }
- } finally { setBusy(false); }
+ try {
+ await refresh();
+ } catch {
+ /* keep the actionable execution error */
+ }
+ } finally {
+ setBusy(false);
+ }
};
return (
- <Dialog isOpen={Boolean(props.detail)} onClose={props.onClose} ariaLabelledBy="action-review-title" panelClass="max-w-3xl">
+ <Dialog
+ isOpen={Boolean(props.detail)}
+ onClose={props.onClose}
+ ariaLabelledBy="action-review-title"
+ panelClass="max-w-3xl"
+ >
<Show when={audit()}>
{(record) => (
<div class="flex max-h-[min(90vh,900px)] flex-col">
<header class="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
- <div><p class="text-xs font-semibold uppercase tracking-wide text-muted">Governed action review</p><h2 id="action-review-title" class="mt-1 text-xl font-semibold">{formatActionName(record().request.capabilityName)}</h2><p class="mt-1 break-all text-sm text-muted">{record().request.resourceId}</p></div>
- <Button variant="ghost" size="icon" aria-label="Close action review" onClick={props.onClose}><XIcon class="h-5 w-5" /></Button>
+ <div>
+ <p class="text-xs font-semibold uppercase tracking-wide text-muted">
+ Governed action review
+ </p>
+ <h2 id="action-review-title" class="mt-1 text-xl font-semibold">
+ {formatActionName(record().request.capabilityName)}
+ </h2>
+ <p class="mt-1 break-all text-sm text-muted">{record().request.resourceId}</p>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label="Close action review"
+ onClick={props.onClose}
+ >
+ <XIcon class="h-5 w-5" />
+ </Button>
</header>
- <div class="overflow-y-auto px-5 py-4"><ActionDecisionPacket audit={record()} detail={props.detail ?? undefined} /><Show when={invalidActionMessage()}><div role="alert" data-testid="action-review-invalid" class="mt-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900 dark:bg-amber-950/40 dark:text-amber-200">{invalidActionMessage()}</div></Show><Show when={error()}><div role="alert" class="mt-4 rounded border border-red-300 bg-red-50 p-3 text-sm text-red-800 dark:bg-red-950/40 dark:text-red-200">{error()}</div></Show></div>
+ <div class="overflow-y-auto px-5 py-4">
+ <ActionDecisionPacket audit={record()} detail={props.detail ?? undefined} />
+ <Show when={invalidActionMessage()}>
+ <div
+ role="alert"
+ data-testid="action-review-invalid"
+ class="mt-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900 dark:bg-amber-950/40 dark:text-amber-200"
+ >
+ {invalidActionMessage()}
+ </div>
+ </Show>
+ <Show when={error()}>
+ <div
+ role="alert"
+ class="mt-4 rounded border border-red-300 bg-red-50 p-3 text-sm text-red-800 dark:bg-red-950/40 dark:text-red-200"
+ >
+ {error()}
+ </div>
+ </Show>
+ </div>
<footer class="flex flex-col-reverse gap-2 border-t border-border px-5 py-4 sm:flex-row sm:justify-end">
<Button onClick={props.onClose}>Close</Button>
- <Show when={canDecide()}><Button variant="danger" disabled={busy()} onClick={() => void decide('rejected')}>Reject</Button><Button variant="primary" isLoading={busy()} onClick={() => void decide('approved')}>Approve</Button></Show>
- <Show when={canExecute()}><Button variant="primary" isLoading={busy()} onClick={() => void execute()}>Run action</Button></Show>
+ <Show when={canDecide()}>
+ <Button variant="danger" disabled={busy()} onClick={() => void decide('rejected')}>
+ Reject
+ </Button>
+ <Button
+ variant="primary"
+ isLoading={busy()}
+ onClick={() => void decide('approved')}
+ >
+ Approve
+ </Button>
+ </Show>
+ <Show when={canExecute()}>
+ <Button variant="primary" isLoading={busy()} onClick={() => void execute()}>
+ Run action
+ </Button>
+ </Show>
</footer>
</div>
)}
diff --git a/frontend-modern/src/features/actions/__tests__/ActionReviewDialog.test.tsx b/frontend-modern/src/features/actions/__tests__/ActionReviewDialog.test.tsx
index 8e89f46101..d7bd565166 100644
--- a/frontend-modern/src/features/actions/__tests__/ActionReviewDialog.test.tsx
+++ b/frontend-modern/src/features/actions/__tests__/ActionReviewDialog.test.tsx
@@ -1,21 +1,96 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ResourceActionsAPI } from '@/api/resourceActions';
import type { ActionAuditRecord, ActionDetailResponse } from '@/types/actionAudit';
import { ActionReviewDialog } from '../ActionReviewDialog';
-vi.mock('@/api/resourceActions', () => ({ ResourceActionsAPI: { getAction: vi.fn(), decideAction: vi.fn(), executeAction: vi.fn() } }));
-vi.mock('@/stores/notifications', () => ({ notificationStore: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));
+vi.mock('@/api/resourceActions', () => ({
+ ResourceActionsAPI: { getAction: vi.fn(), decideAction: vi.fn(), executeAction: vi.fn() },
+}));
+vi.mock('@/stores/notifications', () => ({
+ notificationStore: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },
+}));
-afterEach(() => { cleanup(); vi.useRealTimers(); });
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
-const makeAudit = (status: 'resolved' | 'legacy_unknown', expiresAt: string): ActionAuditRecord => ({
- id: 'action-1', createdAt: '2026-07-12T00:00:00Z', updatedAt: '2026-07-12T00:00:00Z', state: 'pending_approval', decisionRevision: 0,
- request: { requestId: 'request-1', resourceId: 'docker:container:edge', capabilityName: 'restart', reason: 'Recover edge', requestedBy: 'operator' },
+const makeAudit = (
+ status: 'resolved' | 'legacy_unknown',
+ expiresAt: string,
+): ActionAuditRecord => ({
+ id: 'action-1',
+ createdAt: '2026-07-12T00:00:00Z',
+ updatedAt: '2026-07-12T00:00:00Z',
+ state: 'pending_approval',
+ decisionRevision: 0,
+ request: {
+ requestId: 'request-1',
+ resourceId: 'docker:container:edge',
+ capabilityName: 'restart',
+ reason: 'Recover edge',
+ requestedBy: 'operator',
+ },
plan: {
- actionId: 'action-1', requestId: 'request-1', allowed: true, requiresApproval: true, approvalPolicy: 'admin', approvalRequirement: { version: 1, floor: 'admin', quorum: 1, disallowRequester: false }, rollbackAvailable: false, expiresAt,
- policyDecision: status === 'resolved'
- ? { version: 1, status, decisionId: 'decision-1', actionId: 'action-1', scope: { orgId: 'org-1', resourceId: 'docker:container:edge', capabilityName: 'restart' }, authorities: [{ kind: 'capability_registry', sourceId: 'capability-registry:restart', status: 'consulted', scope: { orgId: 'org-1', resourceId: 'docker:container:edge', capabilityName: 'restart' }, approvalFloor: 'admin', reasonCodes: ['capability_approval_admin'] }], approvalRequirement: { version: 1, floor: 'admin', quorum: 1, disallowRequester: false }, planningAllowed: true, requiresApproval: true }
- : { version: 0, status, scope: { orgId: '', resourceId: '', capabilityName: '' }, authorities: [], approvalRequirement: { version: 0, floor: 'admin', quorum: 1, disallowRequester: false }, planningAllowed: false, requiresApproval: true },
+ actionId: 'action-1',
+ requestId: 'request-1',
+ allowed: true,
+ requiresApproval: true,
+ approvalPolicy: 'admin',
+ approvalRequirement: { version: 1, floor: 'admin', quorum: 1, disallowRequester: false },
+ rollbackAvailable: false,
+ expiresAt,
+ planHash: 'sha256:reviewed-plan',
+ policyDecision:
+ status === 'resolved'
+ ? {
+ version: 1,
+ status,
+ decisionId: 'decision-1',
+ actionId: 'action-1',
+ scope: {
+ orgId: 'org-1',
+ resourceId: 'docker:container:edge',
+ capabilityName: 'restart',
+ },
+ authorities: [
+ {
+ kind: 'capability_registry',
+ sourceId: 'capability-registry:restart',
+ status: 'consulted',
+ scope: {
+ orgId: 'org-1',
+ resourceId: 'docker:container:edge',
+ capabilityName: 'restart',
+ },
+ approvalFloor: 'admin',
+ reasonCodes: ['capability_approval_admin'],
+ },
+ ],
+ approvalRequirement: {
+ version: 1,
+ floor: 'admin',
+ quorum: 1,
+ disallowRequester: false,
+ },
+ planningAllowed: true,
+ requiresApproval: true,
+ }
+ : {
+ version: 0,
+ status,
+ scope: { orgId: '', resourceId: '', capabilityName: '' },
+ authorities: [],
+ approvalRequirement: {
+ version: 0,
+ floor: 'admin',
+ quorum: 1,
+ disallowRequester: false,
+ },
+ planningAllowed: false,
+ requiresApproval: true,
+ },
},
verificationOutcome: { status: 'unknown' },
});
@@ -23,8 +98,15 @@ const detail = (audit: ActionAuditRecord): ActionDetailResponse => ({ audit, eve
describe('ActionReviewDialog trust gates', () => {
it('offers no approve or run control for legacy provenance', () => {
- render(() => <ActionReviewDialog detail={detail(makeAudit('legacy_unknown', '2099-01-01T00:00:00Z'))} onClose={vi.fn()} />);
- expect(screen.getByTestId('action-review-invalid')).toHaveTextContent('no current server policy provenance');
+ render(() => (
+ <ActionReviewDialog
+ detail={detail(makeAudit('legacy_unknown', '2099-01-01T00:00:00Z'))}
+ onClose={vi.fn()}
+ />
+ ));
+ expect(screen.getByTestId('action-review-invalid')).toHaveTextContent(
+ 'no current server policy provenance',
+ );
expect(screen.queryByRole('button', { name: 'Approve' })).toBeNull();
expect(screen.queryByRole('button', { name: 'Run action' })).toBeNull();
});
@@ -32,7 +114,12 @@ describe('ActionReviewDialog trust gates', () => {
it('removes decision controls when expiry passes while the dialog remains open', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-07-12T00:00:00Z'));
- render(() => <ActionReviewDialog detail={detail(makeAudit('resolved', '2026-07-12T00:00:00.500Z'))} onClose={vi.fn()} />);
+ render(() => (
+ <ActionReviewDialog
+ detail={detail(makeAudit('resolved', '2026-07-12T00:00:00.500Z'))}
+ onClose={vi.fn()}
+ />
+ ));
expect(screen.getByRole('button', { name: 'Approve' })).toBeInTheDocument();
await vi.advanceTimersByTimeAsync(1000);
expect(screen.queryByRole('button', { name: 'Approve' })).toBeNull();
@@ -41,10 +128,55 @@ describe('ActionReviewDialog trust gates', () => {
it('offers no decision or run control when a typed APT action carries parameters', () => {
const audit = makeAudit('resolved', '2099-01-01T00:00:00Z');
- audit.request = { ...audit.request, capabilityName: 'install_os_updates', params: { package: 'curl' } };
+ audit.request = {
+ ...audit.request,
+ capabilityName: 'install_os_updates',
+ params: { package: 'curl' },
+ };
audit.plan.policyDecision!.scope.capabilityName = 'install_os_updates';
render(() => <ActionReviewDialog detail={detail(audit)} onClose={vi.fn()} />);
- expect(screen.getByTestId('action-review-invalid')).toHaveTextContent('unexpected operator-selected parameters');
+ expect(screen.getByTestId('action-review-invalid')).toHaveTextContent(
+ 'unexpected operator-selected parameters',
+ );
+ expect(screen.queryByRole('button', { name: 'Approve' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Run action' })).toBeNull();
+ });
+
+ it('binds an approval to the plan shown in the dialog', async () => {
+ const audit = makeAudit('resolved', '2099-01-01T00:00:00Z');
+ vi.mocked(ResourceActionsAPI.decideAction).mockResolvedValue({
+ actionId: audit.id,
+ state: 'approved',
+ approval: {
+ actor: 'operator',
+ method: 'api',
+ timestamp: audit.updatedAt,
+ outcome: 'approved',
+ },
+ audit: { ...audit, state: 'approved' },
+ });
+ vi.mocked(ResourceActionsAPI.getAction).mockResolvedValue(
+ detail({ ...audit, state: 'approved' }),
+ );
+ render(() => <ActionReviewDialog detail={detail(audit)} onClose={vi.fn()} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Approve' }));
+ await waitFor(() =>
+ expect(ResourceActionsAPI.decideAction).toHaveBeenCalledWith(
+ 'action-1',
+ 'approved',
+ 'sha256:reviewed-plan',
+ 'Operator approved from Actions review.',
+ ),
+ );
+ });
+
+ it('offers no action controls when the reviewed plan identity is missing', () => {
+ const audit = makeAudit('resolved', '2099-01-01T00:00:00Z');
+ delete audit.plan.planHash;
+ render(() => <ActionReviewDialog detail={detail(audit)} onClose={vi.fn()} />);
+ expect(screen.getByTestId('action-review-invalid')).toHaveTextContent(
+ 'no reviewed plan identity',
+ );
expect(screen.queryByRole('button', { name: 'Approve' })).toBeNull();
expect(screen.queryByRole('button', { name: 'Run action' })).toBeNull();
});
diff --git a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
index 52a9eccc1c..8770e3de6d 100644
--- a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
+++ b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
@@ -71,16 +71,26 @@ describe('apiClient org context', () => {
});
it('preserves authenticated organization context across durable action operations', async () => {
- mockFetch.mockImplementation(async () =>
- new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }),
+ mockFetch.mockImplementation(
+ async () =>
+ new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }),
);
setOrgID('tenant-actions');
await ResourceActionsAPI.listActions('pending', 20);
await ResourceActionsAPI.listActions('settled', 20);
await ResourceActionsAPI.getAction('action/one');
- await ResourceActionsAPI.decideAction('action/one', 'approved', 'Reviewed by operator');
- await ResourceActionsAPI.executeAction('action/one', 'Execute the reviewed plan');
+ await ResourceActionsAPI.decideAction(
+ 'action/one',
+ 'approved',
+ 'sha256:reviewed-plan',
+ 'Reviewed by operator',
+ );
+ await ResourceActionsAPI.executeAction(
+ 'action/one',
+ 'sha256:reviewed-plan',
+ 'Execute the reviewed plan',
+ );
expect(mockFetch.mock.calls.map(([url]) => String(url))).toEqual([
'/api/actions?view=pending&limit=20',
@@ -93,12 +103,16 @@ describe('apiClient org context', () => {
const headers = options.headers as Record<string, string>;
expect(headers['X-Pulse-Org-ID']).toBe('tenant-actions');
}
- const mutationBodies = mockFetch.mock.calls.slice(3).map(([, options]) =>
- JSON.parse(String((options as RequestInit).body)),
- );
+ const mutationBodies = mockFetch.mock.calls
+ .slice(3)
+ .map(([, options]) => JSON.parse(String((options as RequestInit).body)));
expect(mutationBodies).toEqual([
- { outcome: 'approved', reason: 'Reviewed by operator' },
- { reason: 'Execute the reviewed plan' },
+ {
+ outcome: 'approved',
+ planHash: 'sha256:reviewed-plan',
+ reason: 'Reviewed by operator',
+ },
+ { planHash: 'sha256:reviewed-plan', reason: 'Execute the reviewed plan' },
]);
expect(mutationBodies.every((body) => !('orgId' in body))).toBe(true);
});
diff --git a/internal/ai/findings_proxmox_lifecycle.go b/internal/ai/findings_proxmox_lifecycle.go
index 392dd354f2..62d5c323a0 100644
--- a/internal/ai/findings_proxmox_lifecycle.go
+++ b/internal/ai/findings_proxmox_lifecycle.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
)
const (
@@ -18,8 +19,11 @@ const (
proxmoxGuestLifecycleResolveRemoved = "proxmox_guest_lifecycle:resource_removed"
proxmoxVMLifecycleCapabilityHandler = "proxmox.vm.lifecycle"
proxmoxLXCLifecycleCapabilityHandler = "proxmox.ct.lifecycle"
+ proxmoxGuestActionAuditLimit = 100
)
+type proxmoxGuestActionAuditLookup func(resourceID string, since time.Time, limit int) ([]unifiedresources.ActionAuditRecord, error)
+
type proxmoxGuestLifecycleSnapshot struct {
id string
name string
@@ -37,12 +41,17 @@ type proxmoxGuestLifecycleSnapshot struct {
}
type proxmoxGuestLifecycleWatcher struct {
- mu sync.Mutex
- prior map[string]proxmoxGuestLifecycleSnapshot
+ mu sync.Mutex
+ prior map[string]proxmoxGuestLifecycleSnapshot
+ lookupActionAudits proxmoxGuestActionAuditLookup
}
-func newProxmoxGuestLifecycleWatcher() *proxmoxGuestLifecycleWatcher {
- return &proxmoxGuestLifecycleWatcher{prior: make(map[string]proxmoxGuestLifecycleSnapshot)}
+func newProxmoxGuestLifecycleWatcher(lookupActionAudits ...proxmoxGuestActionAuditLookup) *proxmoxGuestLifecycleWatcher {
+ watcher := &proxmoxGuestLifecycleWatcher{prior: make(map[string]proxmoxGuestLifecycleSnapshot)}
+ if len(lookupActionAudits) > 0 {
+ watcher.lookupActionAudits = lookupActionAudits[0]
+ }
+ return watcher
}
// DetectProxmoxGuestLifecycleFindings is the pure detector used by Patrol and
@@ -86,8 +95,13 @@ func (w *proxmoxGuestLifecycleWatcher) Observe(state patrolRuntimeState, active
activeByResource[strings.TrimSpace(finding.ResourceID)] = finding
}
+ type stoppedTransition struct {
+ before proxmoxGuestLifecycleSnapshot
+ after proxmoxGuestLifecycleSnapshot
+ }
+ transitions := make([]stoppedTransition, 0)
+
w.mu.Lock()
- defer w.mu.Unlock()
if w.prior == nil {
w.prior = make(map[string]proxmoxGuestLifecycleSnapshot)
}
@@ -105,7 +119,7 @@ func (w *proxmoxGuestLifecycleWatcher) Observe(state patrolRuntimeState, active
emit = append(emit, buildProxmoxGuestStoppedFinding(snapshot, now.UTC()))
case activeFinding == nil:
if previous, ok := w.prior[id]; ok && proxmoxGuestStoppedTransition(previous, snapshot) {
- emit = append(emit, buildProxmoxGuestStoppedFinding(snapshot, now.UTC()))
+ transitions = append(transitions, stoppedTransition{before: previous, after: snapshot})
}
}
w.prior[id] = snapshot
@@ -126,9 +140,75 @@ func (w *proxmoxGuestLifecycleWatcher) Observe(state patrolRuntimeState, active
}
resolve = append(resolve, resolveSentinel{DedupKey: finding.ID, Reason: proxmoxGuestLifecycleResolveRemoved})
}
+ w.mu.Unlock()
+
+ for _, transition := range transitions {
+ if w.governedStopCompleted(transition.before, transition.after, now.UTC()) {
+ continue
+ }
+ emit = append(emit, buildProxmoxGuestStoppedFinding(transition.after, now.UTC()))
+ }
return emit, resolve
}
+func (w *proxmoxGuestLifecycleWatcher) governedStopCompleted(before, after proxmoxGuestLifecycleSnapshot, now time.Time) bool {
+ if w == nil || w.lookupActionAudits == nil {
+ return false
+ }
+ audits, err := w.lookupActionAudits(after.id, time.Time{}, proxmoxGuestActionAuditLimit)
+ if err != nil {
+ log.Warn().Err(err).Str("resource_id", after.id).Msg("failed to inspect Proxmox guest action audits for Patrol suppression")
+ return false
+ }
+ for _, audit := range audits {
+ if proxmoxGuestAuditExplainsStoppedTransition(audit, before, after, now) {
+ return true
+ }
+ }
+ return false
+}
+
+func proxmoxGuestAuditExplainsStoppedTransition(audit unifiedresources.ActionAuditRecord, before, after proxmoxGuestLifecycleSnapshot, now time.Time) bool {
+ if audit.State != unifiedresources.ActionStateCompleted ||
+ unifiedresources.CanonicalResourceID(audit.Request.ResourceID) != unifiedresources.CanonicalResourceID(after.id) ||
+ audit.Result == nil || !audit.Result.Success || audit.Result.ActionResultV2 == nil ||
+ audit.UpdatedAt.IsZero() || audit.UpdatedAt.Before(before.observedAt) || audit.UpdatedAt.After(now) {
+ return false
+ }
+ capability := strings.ToLower(strings.TrimSpace(audit.Request.CapabilityName))
+ if capability != "shutdown" && capability != "stop" {
+ return false
+ }
+ if unifiedresources.CanonicalActionResultV2(audit).Execution.Status != unifiedresources.ActionExecutionSucceeded {
+ return false
+ }
+ for _, approval := range audit.Approvals {
+ if approval.Outcome != unifiedresources.OutcomeApproved || approval.PolicyLease != nil || approval.Timestamp.IsZero() {
+ continue
+ }
+ approvedAt := approval.Timestamp.UTC()
+ if !approvedAt.Before(before.observedAt) && !approvedAt.After(after.observedAt) && !audit.UpdatedAt.Before(approvedAt) {
+ return true
+ }
+ }
+ return false
+}
+
+func (p *PatrolService) loadProxmoxGuestActionAudits(resourceID string, since time.Time, limit int) ([]unifiedresources.ActionAuditRecord, error) {
+ if p == nil || p.aiService == nil {
+ return nil, nil
+ }
+ p.aiService.mu.RLock()
+ store := p.aiService.resourceExportStore
+ orgID := strings.TrimSpace(p.aiService.orgID)
+ storeOrgID := strings.TrimSpace(p.aiService.resourceExportStoreOrgID)
+ p.aiService.mu.RUnlock()
+ if store == nil || (storeOrgID != "" && storeOrgID != orgID) {
+ return nil, nil
+ }
+ return store.GetActionAudits(resourceID, since, limit)
+}
+
func proxmoxGuestLifecycleSnapshots(readState unifiedresources.ReadState) map[string]proxmoxGuestLifecycleSnapshot {
snapshots := make(map[string]proxmoxGuestLifecycleSnapshot)
if readState == nil {
diff --git a/internal/ai/findings_proxmox_lifecycle_test.go b/internal/ai/findings_proxmox_lifecycle_test.go
index 8c6e0c13f8..47e50e3005 100644
--- a/internal/ai/findings_proxmox_lifecycle_test.go
+++ b/internal/ai/findings_proxmox_lifecycle_test.go
@@ -2,6 +2,7 @@ package ai
import (
"context"
+ "errors"
"strings"
"testing"
"time"
@@ -72,6 +73,102 @@ func TestProxmoxGuestLifecycleWatcherSeedsWithoutFlaggingExistingStoppedGuests(t
}
}
+func TestProxmoxGuestLifecycleWatcherSuppressesGovernedStopWithinObservationWindow(t *testing.T) {
+ now := time.Now().UTC()
+ running := proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOnline, now)
+ stopped := proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second))
+ audit := proxmoxLifecycleGovernedStopAudit("vm:160", "shutdown", now.Add(3*time.Second), now.Add(8*time.Second))
+ lookupCalls := 0
+ watcher := newProxmoxGuestLifecycleWatcher(func(resourceID string, since time.Time, limit int) ([]unifiedresources.ActionAuditRecord, error) {
+ lookupCalls++
+ if resourceID != "vm:160" || !since.IsZero() || limit != proxmoxGuestActionAuditLimit {
+ t.Fatalf("lookup resource=%q since=%s limit=%d", resourceID, since, limit)
+ }
+ return []unifiedresources.ActionAuditRecord{audit}, nil
+ })
+ watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(running)}, nil, now)
+ emit, resolve := watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(stopped)}, nil, now.Add(11*time.Second))
+ if lookupCalls != 1 || len(emit) != 0 || len(resolve) != 0 {
+ t.Fatalf("governed stop must suppress exactly once: calls=%d emit=%#v resolve=%#v", lookupCalls, emit, resolve)
+ }
+
+ emit, _ = watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(stopped)}, nil, now.Add(12*time.Second))
+ if lookupCalls != 1 || len(emit) != 0 {
+ t.Fatalf("suppressed transition must still advance baseline: calls=%d emit=%#v", lookupCalls, emit)
+ }
+}
+
+func TestProxmoxGuestLifecycleWatcherEmitsWhenGovernedStopAuditIsNotCausal(t *testing.T) {
+ now := time.Now().UTC()
+ before := proxmoxGuestLifecycleSnapshot{id: "vm:160", observedAt: now}
+ after := proxmoxGuestLifecycleSnapshot{id: "vm:160", observedAt: now.Add(10 * time.Second)}
+ valid := proxmoxLifecycleGovernedStopAudit("vm:160", "stop", now.Add(3*time.Second), now.Add(8*time.Second))
+
+ tests := []struct {
+ name string
+ mutate func(*unifiedresources.ActionAuditRecord)
+ }{
+ {name: "different resource", mutate: func(a *unifiedresources.ActionAuditRecord) { a.Request.ResourceID = "vm:999" }},
+ {name: "restart capability", mutate: func(a *unifiedresources.ActionAuditRecord) { a.Request.CapabilityName = "restart" }},
+ {name: "failed audit state", mutate: func(a *unifiedresources.ActionAuditRecord) { a.State = unifiedresources.ActionStateFailed }},
+ {name: "legacy result only", mutate: func(a *unifiedresources.ActionAuditRecord) { a.Result.ActionResultV2 = nil }},
+ {name: "failed execution", mutate: func(a *unifiedresources.ActionAuditRecord) { a.Result.Success = false }},
+ {name: "stale approval", mutate: func(a *unifiedresources.ActionAuditRecord) { a.Approvals[0].Timestamp = now.Add(-time.Second) }},
+ {name: "approval after stop", mutate: func(a *unifiedresources.ActionAuditRecord) { a.Approvals[0].Timestamp = now.Add(11 * time.Second) }},
+ {name: "policy authorization", mutate: func(a *unifiedresources.ActionAuditRecord) {
+ a.Approvals[0].PolicyLease = &unifiedresources.ActionPolicyAuthorizationLease{}
+ }},
+ {name: "completion before approval", mutate: func(a *unifiedresources.ActionAuditRecord) { a.UpdatedAt = now.Add(2 * time.Second) }},
+ {name: "future completion", mutate: func(a *unifiedresources.ActionAuditRecord) { a.UpdatedAt = now.Add(12 * time.Second) }},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ audit := valid
+ audit.Approvals = append([]unifiedresources.ActionApprovalRecord(nil), valid.Approvals...)
+ result := *valid.Result
+ audit.Result = &result
+ test.mutate(&audit)
+ if proxmoxGuestAuditExplainsStoppedTransition(audit, before, after, now.Add(11*time.Second)) {
+ t.Fatalf("non-causal audit explained transition: %#v", audit)
+ }
+ })
+ }
+}
+
+func TestProxmoxGuestLifecycleWatcherFailsOpenWhenActionAuditLookupFails(t *testing.T) {
+ now := time.Now().UTC()
+ watcher := newProxmoxGuestLifecycleWatcher(func(string, time.Time, int) ([]unifiedresources.ActionAuditRecord, error) {
+ return nil, errors.New("audit store unavailable")
+ })
+ watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(
+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOnline, now),
+ )}, nil, now)
+ emit, _ := watcher.Observe(patrolRuntimeState{readState: proxmoxLifecycleReadState(
+ proxmoxLifecycleTestResource("vm:160", unifiedresources.ResourceTypeVM, unifiedresources.StatusOffline, now.Add(10*time.Second)),
+ )}, nil, now.Add(11*time.Second))
+ if len(emit) != 1 {
+ t.Fatalf("audit lookup failure must preserve warning: %#v", emit)
+ }
+}
+
+func TestNewPatrolServiceWiresProxmoxLifecycleToOrgScopedActionStore(t *testing.T) {
+ store := unifiedresources.NewMemoryStore()
+ service := &Service{orgID: "org-1", resourceExportStore: store, resourceExportStoreOrgID: "org-1"}
+ patrol := NewPatrolService(service, nil)
+ if patrol.proxmoxGuestLifecycleWatcher == nil || patrol.proxmoxGuestLifecycleWatcher.lookupActionAudits == nil {
+ t.Fatal("production Proxmox lifecycle watcher has no action-audit lookup")
+ }
+ audits, err := patrol.proxmoxGuestLifecycleWatcher.lookupActionAudits("vm:160", time.Time{}, 10)
+ if err != nil || len(audits) != 0 {
+ t.Fatalf("org-scoped action lookup audits=%#v err=%v", audits, err)
+ }
+ service.resourceExportStoreOrgID = "org-2"
+ audits, err = patrol.proxmoxGuestLifecycleWatcher.lookupActionAudits("vm:160", time.Time{}, 10)
+ if err != nil || audits != nil {
+ t.Fatalf("cross-org action store must fail closed: audits=%#v err=%v", audits, err)
+ }
+}
+
func TestProxmoxGuestLifecycleWatcherFailsClosedOnFreshnessCapabilityAndGuestGuards(t *testing.T) {
now := time.Now().UTC()
resourceIDs := []string{"vm:stale", "vm:same-clock", "vm:no-capability", "vm:template", "vm:locked"}
@@ -167,3 +264,18 @@ func proxmoxLifecycleTestResource(id string, resourceType unifiedresources.Resou
}},
}
}
+
+func proxmoxLifecycleGovernedStopAudit(resourceID, capability string, approvedAt, completedAt time.Time) unifiedresources.ActionAuditRecord {
+ resultV2 := unifiedresources.ActionResultV2{
+ Version: unifiedresources.ActionResultV2Version,
+ Execution: unifiedresources.ActionExecutionTruth{Status: unifiedresources.ActionExecutionSucceeded},
+ Verification: unifiedresources.ActionVerificationTruth{Status: unifiedresources.ActionVerificationNotAttempted, EvidenceClass: unifiedresources.ActionEvidenceNone},
+ Compensation: unifiedresources.ActionCompensationTruth{Support: unifiedresources.ActionCompensationUnavailable, Status: unifiedresources.ActionCompensationNotAvailable},
+ }
+ return unifiedresources.ActionAuditRecord{
+ ID: "action-stop-1", CreatedAt: approvedAt.Add(-time.Minute), UpdatedAt: completedAt, State: unifiedresources.ActionStateCompleted,
+ Request: unifiedresources.ActionRequest{ResourceID: resourceID, CapabilityName: capability},
+ Approvals: []unifiedresources.ActionApprovalRecord{{Timestamp: approvedAt, Outcome: unifiedresources.OutcomeApproved}},
+ Result: &unifiedresources.ExecutionResult{Success: true, ActionResultV2: &resultV2},
+ }
+}
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index e0f0107d5b..5118885aac 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -704,7 +704,7 @@ func NewPatrolService(aiService *Service, stateProvider StateProvider) *PatrolSe
p.findings.SetStormThrottler(p.stormThrottler)
p.updateSafetyWatcher = newUpdateSafetyWatcher()
p.aptWorkflowWatcher = newAPTWorkflowWatcher()
- p.proxmoxGuestLifecycleWatcher = newProxmoxGuestLifecycleWatcher()
+ p.proxmoxGuestLifecycleWatcher = newProxmoxGuestLifecycleWatcher(p.loadProxmoxGuestActionAudits)
p.pdmAlertBridge = newPDMAlertBridge(newPDMAlertSourceFromEnv())
return p
}