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 policy-scoped Patrol autonomy

rcourtman69b2028513c3
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 0b357f7a39..f9f8747fbd 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -5590,7 +5590,7 @@
"status": "partial",
"completion": {
"state": "bounded-residual",
- "summary": "Action governance has a first-class governed floor AND the typed action lifecycle is now the only autonomous route for Patrol: investigations run under a core-owned, non-interactive, read-only execution profile and can only emit a side-effect-free typed action proposal (patrol_propose_action), which the shared action lifecycle plans, approves, and executes with plan hashing, remediation locks, plan-drift revalidation, and read-after-write verification. Action continuity is audit-authoritative: callbacks trigger org-scoped re-reads, investigation reads recover missed transitions by trusted origin, desktop and mobile decisions use the canonical /api/actions routes, terminal verification maps honestly onto Patrol findings and push outcomes, and legacy command-shaped history remains inert. The enterprise orchestrator consumes the exact capability catalog and preserves independent runtime/proposal failures; a code-level detect-plan-approve-execute-verify-reconcile journey proves one execution and durable verified completion. Remaining post-RC hardening: policy-scoped autonomy presets (per tenant/resource/action/window), host-update and storage-pressure workflows as the second and third complete verticals, richer dry-run providers, multi-actor approvals, and a real-lab detect-plan-execute-verify-rollback journey proof.",
+ "summary": "Action governance has a first-class governed floor AND the typed action lifecycle is now the only autonomous route for Patrol: investigations run under a core-owned, non-interactive, read-only execution profile and can only emit a side-effect-free typed action proposal (patrol_propose_action), which the shared action lifecycle plans, approves, and executes with plan hashing, remediation locks, plan-drift revalidation, and read-after-write verification. The first policy-authorized vertical is live: Docker/Podman restart is capability-owned low-risk eligible, requires an explicit per-resource capability allowlist, supports an optional recurring timezone window, remains bounded by the tenant Patrol mode and full-mode unlock, rechecks policy before decision and dispatch, and records its server-owned policy approval plus terminal verification in the same audit trail. Never-auto-remediate, missing/unknown policy, unsupported capabilities, dry-run/MFA floors, closed windows, and mode downgrades all fail closed. Action continuity is audit-authoritative: idempotent proposal replay cannot rewind or double-execute a terminal action, callbacks trigger org-scoped re-reads, investigation reads recover missed transitions by trusted origin, desktop and mobile decisions use the canonical /api/actions routes, terminal verification maps honestly onto Patrol findings and push outcomes, and legacy command-shaped history remains inert. Remaining post-RC hardening: broader tenant defaults/inheritance and automation rate budgets, host-update and storage-pressure workflows as the second and third complete verticals, richer dry-run providers, multi-actor approvals, and a real-lab detect-plan-execute-verify-rollback journey proof.",
"tracking": [
{
"kind": "lane-followup",
@@ -5674,6 +5674,11 @@
"path": "frontend-modern/src/components/Infrastructure/ResourceActionHistory.tsx",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "frontend-modern/src/components/Infrastructure/useResourceDetailDrawerHistoryState.ts",
@@ -5739,6 +5744,11 @@
"path": "internal/api/contract_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/patrol_action_broker.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/api/patrol_action_broker_test.go",
@@ -5759,6 +5769,11 @@
"path": "internal/unifiedresources/actions_test.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/resource_operator_state_policy_test.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/unifiedresources/store.go",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 91625049ec..8e48784b37 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -363,6 +363,11 @@ same API-owned lifecycle; agent lifecycle surfaces must not consume
Patrol-origin action audits as an agent command grant or lifecycle
execution shortcut, and must not subscribe lifecycle side effects to the
API-owned org-scoped action-transition hook. The investigation
+broker may authorize eligible actions under core-owned tenant/resource policy,
+but that policy decision does not grant agent lifecycle code a parallel
+authorization primitive: all execution still enters through the shared action
+lifecycle and its agent executor.
+The investigation
continuity reconciler in `internal/api/patrol_action_reconciliation.go` is
also API-owned: callbacks only wake an authoritative action-audit re-read,
and missed callbacks recover during investigation reads. Agent lifecycle
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 3325bb91dd..1f3ebec089 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -4561,12 +4561,16 @@ successor to that command-shaped approval flow and the ONLY sanctioned route
from an enterprise Patrol investigation to a Pulse infrastructure mutation:
`OrchestratorActionBroker` exposes exactly `Capabilities` (read-only catalog
of a resource's advertised capabilities and parameter schemas, including
-sensitivity) and `Submit` (plan-only typed proposal). The contract
+sensitivity and core-owned auto-authorization eligibility) and `Submit`
+(typed proposal). The contract
deliberately omits org ID, requestedBy, autonomy, risk, approval-policy,
destructive, command, and target-host fields, and has no decide or execute
methods, so enterprise code can neither claim authorization nor dispatch;
-authorization always derives from the capability's declared policy on the
-core lifecycle. `OrchestratorDeps.ActionBroker` carries the seam and is
+authorization always derives inside core from the tenant Patrol mode,
+capability eligibility, persisted per-resource allowlist/window, remediation
+lock, and the canonical lifecycle. Enterprise receives the resulting pending
+or terminal disposition, including honest verification status, but never an
+authorization primitive. `OrchestratorDeps.ActionBroker` carries the seam and is
now REQUIRED: the enterprise factory disables the orchestrator when it is
absent rather than falling back. The command-execution side doors are
gone. `OrchestratorChatService` exposes only investigation-specific
@@ -5662,3 +5666,9 @@ so a missed callback cannot strand Patrol on stale approval state. Finding
lifecycle publication is idempotent and emits unified lifecycle updates plus
honest terminal push outcomes without turning unverified execution into an
all-clear.
+Policy-authorized submission is still audit-authoritative. Missing policy
+state, provider errors, closed/out-of-window resource policy, unsupported
+eligibility, or a Patrol mode below the capability's class leave the action
+pending rather than converting a valid proposal into an investigation failure.
+An idempotent resubmission returns the existing action disposition and must not
+execute a terminal action twice.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5dfaeabff2..c80f52ae16 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1814,7 +1814,7 @@ a new API state machine, queue contract, or verification-accounting field.
returns `503` `audit_store_unavailable`, and unrelated query failures remain
`query_failed`. List pagination must stay bounded so audit history reads
cannot become unbounded table scans through API parameters.
- Plan-only unified action planning is part of that same API-first action
+ Unified action planning is part of that same API-first action
contract: `POST /api/actions/plan` must route through
`internal/api/actions.go`, `internal/actionlifecycle/service.go`,
`internal/actionplanner/planner.go`, and
@@ -1823,9 +1823,10 @@ a new API state machine, queue contract, or verification-accounting field.
versions, plan hash, and preflight checks without approving or executing the
capability. A successful plan must also be durably recorded in the unified
action-audit store with initial lifecycle evidence before the API returns:
- approval-required plans land as `pending_approval`, retries with the same
- deterministic action identity may upsert the audit record, and retries must
- not duplicate the initial lifecycle events. MCP, CLI, and UI consumers may
+ approval-required plans land as `pending_approval`, and retries with the same
+ deterministic action identity must return the existing audit without
+ rewinding an approved, executing, or terminal record or duplicating its
+ lifecycle events. MCP, CLI, and UI consumers may
adapt this payload, but they must not become the source of truth for action
planning semantics.
The plan/decision/execution lifecycle itself is transport-independent and
@@ -1839,13 +1840,22 @@ a new API state machine, queue contract, or verification-accounting field.
lifecycle or dispatch a resource mutation around this service.
The Patrol proposal seam rides that same service:
`internal/api/patrol_action_broker.go` implements the public
- `aicontracts.OrchestratorActionBroker` contract as a tenant-bound,
- plan-only adapter. It stamps the fixed `pulse_patrol` requestedBy actor
+ `aicontracts.OrchestratorActionBroker` contract as a tenant-bound proposal
+ adapter. It stamps the fixed `pulse_patrol` requestedBy actor
and a broker-owned `ActionOrigin` (surface/finding/investigation/proposal
IDs) through the service's internal `PlanWithOptions`; the public plan
endpoint keeps calling plain `Plan`, so an HTTP request body can never
- claim a first-party origin. Submit never decides or executes (even an
- `ApprovalNone` capability returns a planned disposition), and proposals
+ claim a first-party origin. Enterprise still has no decision or execution
+ method. After planning, core may auto-authorize only when the capability's
+ declared eligibility, the persisted resource capability allowlist and
+ optional recurring window, `NeverAutoRemediate`, and the tenant's effective
+ Patrol mode all allow it. Assisted mode admits only `low_risk`; unlocked full
+ mode may also admit `elevated`; monitor, approval, dry-run-only, MFA, missing,
+ and unknown policy fail closed to the pending disposition. Core re-reads the
+ policy immediately before execution and records the decision as actor
+ `pulse_patrol_policy` with approval method `policy`; the canonical lifecycle
+ still owns locks, drift validation, execution, verification, publication,
+ and replay safety. Proposals
that populate a capability parameter declared `IsSensitive` are refused
with `ErrSensitiveParamsRequireOperator` before any audit persistence,
so secret material never enters model output, investigation stores, or
@@ -1861,7 +1871,7 @@ a new API state machine, queue contract, or verification-accounting field.
Patrol proposal must carry both its finding and investigation IDs
before anything persists; identity-less proposals are refused so a
governed action can never lose deterministic correlation.
- Plan-only proof: `TestContract_PatrolActionBrokerIsPlanOnly` in
+ Authority proof: `TestContract_PatrolActionBrokerKeepsPolicyExecutionCoreOwned` in
`internal/api/contract_test.go`.
The proposal enters that broker from the investigation-only
`patrol_propose_action` capture (canonical name and descriptor in
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 679321feee..be1ce41f35 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -326,7 +326,7 @@ attention`, `approval needed`, `outcome verified`, `no active work`) instead
Intelligence settings and external-agent surfaces own MCP setup/readiness,
while API security owns only the scoped-token creation surface they link to.
Patrol mode labels and details must match the backend execution policy:
- assisted mode may say it can run low or medium-risk fixes allowed by policy,
+ assisted mode may say it can run low-risk fixes explicitly allowed by policy,
but it must not imply that warning severity alone makes a command safe;
high-risk, critical, destructive, or unknown-risk fixes remain approval-bound
unless the operator has selected a broader autonomy level. Compact Patrol
@@ -963,6 +963,13 @@ not inside the secondary Schedule & model drawer: the first configurable decisio
what Patrol may handle automatically (`Watch only`, `Ask first`,
`Safe auto-fix`, `Autopilot`), and there must be only one visible chooser for
that decision.
+Per-resource automatic-action scope is configured in the canonical resource
+drawer, not duplicated on the Patrol page. The drawer may expose only
+capabilities whose backend contract declares auto-authorization eligibility,
+requires an explicit capability allowlist, and may collect an optional daily
+time/timezone window. Patrol mode remains the tenant-wide upper bound: a
+resource opt-in cannot widen Watch only or Ask first, admit elevated work in
+Safe auto-fix, bypass the full-mode unlock, or override Never auto-remediate.
Commercial, runtime, and documentation copy that describes this same decision
must also use those visible labels and the umbrella name `Patrol mode`, not
the retired `Only watch`, `Fix safe issues`, `Full control`, or generic
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 56a441f4a2..c353302e83 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -357,6 +357,11 @@ regression protection.
on the AI settings handler once at startup, and each broker or catalog is
constructed lazily per investigation run rather than eagerly per request, so
the wiring adds no fan-out to the protected hot path.
+ Core-owned Patrol policy resolution follows that same boundary: the broker
+ may resolve the already-scoped AI service and read its in-memory effective
+ autonomy/full-unlock posture only during proposal submission. Router setup
+ and unrelated protected requests must not enumerate tenants, load provider
+ catalogs, scan resource policy, or execute action planning eagerly.
Proxmox VM/LXC lifecycle execution follows that same routed-executor budget:
router setup may register the Proxmox executor alongside Docker / Podman,
but it must not resolve guests, probe node agents, call `qm` / `pct`, poll
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index aa1a2101b1..3a54292ccc 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -6022,6 +6022,7 @@
"frontend-modern/src/components/Infrastructure/ResourceDetailDrawerSupportDisclosure.tsx",
"frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts",
"frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx",
+ "frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx",
"frontend-modern/src/components/Infrastructure/ResourcePolicySummary.tsx",
"frontend-modern/src/components/Infrastructure/UnifiedResourceHostTableCard.tsx",
"frontend-modern/src/components/Infrastructure/UnifiedResourcePBSTableSection.tsx",
@@ -6196,6 +6197,7 @@
"frontend-modern/src/components/Infrastructure/ResourceDetailDrawerSupportDisclosure.tsx",
"frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts",
"frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx",
+ "frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx",
"frontend-modern/src/components/Infrastructure/ResourcePolicySummary.tsx",
"frontend-modern/src/components/Infrastructure/UnifiedResourceHostTableCard.tsx",
"frontend-modern/src/components/Infrastructure/UnifiedResourcePBSTableSection.tsx",
@@ -6287,6 +6289,7 @@
"frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerIdentityModel.test.ts",
"frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerOperationalModel.test.ts",
"frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.test.ts",
+ "frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts",
"frontend-modern/src/components/Infrastructure/__tests__/ResourcePolicySummary.test.tsx",
"frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx",
"frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.workloads-link.test.tsx",
@@ -6501,6 +6504,7 @@
"internal/unifiedresources/registry_test.go",
"internal/unifiedresources/resolve_test.go",
"internal/unifiedresources/resolved_host_set_test.go",
+ "internal/unifiedresources/resource_operator_state_policy_test.go",
"internal/unifiedresources/snapshot_source_filter_test.go",
"internal/unifiedresources/store_test.go"
]
@@ -6524,6 +6528,7 @@
"internal/unifiedresources/registry_test.go",
"internal/unifiedresources/resolve_test.go",
"internal/unifiedresources/resolved_host_set_test.go",
+ "internal/unifiedresources/resource_operator_state_policy_test.go",
"internal/unifiedresources/snapshot_source_filter_test.go",
"internal/unifiedresources/store_test.go"
]
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 2e29a08ad5..c3d2c10de3 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1269,3 +1269,10 @@ decision or execution request only through the existing scoped route checks;
they cannot supply requester identity, origin, approval policy, capability
catalog entries, or verification outcome. Legacy command-shaped investigation
history is never exposed as an executable payload in desktop or mobile review.
+Core-owned Patrol policy authorization is additive to that boundary, not a new
+caller grant. It requires an eligible capability, an explicit persisted
+per-resource capability allowlist (and any configured recurring window), an
+effective tenant Patrol mode that admits the eligibility class, and an absent
+Never-auto-remediate lock. Missing or unknown state denies automatic execution.
+The policy actor/method are server-stamped and cannot be supplied by the model,
+enterprise orchestrator, browser, relay, or action-proposal payload.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 4bb9a107a8..137240da4a 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -3743,6 +3743,12 @@ billing state grants relay, the shared runtime helper must persist the
canonical hosted relay config and keep subsequent reads on that same
machine-owned state instead of letting adjacent surfaces invent their own
fallback bootstrap or disable heuristics.
+Storage and recovery consumers of the shared action lifecycle must also treat
+core-owned Patrol auto-authorization as action-audit state, not as a reusable
+storage mutation grant. Per-resource capability allowlists and recurring
+windows may admit only capabilities whose canonical resource contract declares
+eligibility; storage-pressure remediation remains approval-bound until a
+complete capability and verification workflow explicitly declares otherwise.
That same shared `internal/api/` boundary also owns hosted browser-session
precedence for adjacent protected reads. Storage- and recovery-adjacent hosted
surfaces may run without local auth configured, but a valid tenant
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index ff1d83213e..c56e754d1e 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -87,7 +87,8 @@ temperature, capacity, health, and identity enrichment.
47. `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`
48. `frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx`
49. `frontend-modern/src/components/Infrastructure/ResourceCorrelationSummary.tsx`
-50. `frontend-modern/src/components/Infrastructure/ResourcePolicySummary.tsx`
+50. `frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx`
+50a. `frontend-modern/src/components/Infrastructure/ResourcePolicySummary.tsx`
51. `frontend-modern/src/components/Infrastructure/UnifiedResourceHostTableCard.tsx`
52. `frontend-modern/src/components/Infrastructure/UnifiedResourcePBSTableSection.tsx`
53. `frontend-modern/src/components/Infrastructure/UnifiedResourcePMGTableSection.tsx`
@@ -1433,18 +1434,27 @@ canonical resource. This freshness gate belongs in
rendering or frontend fallback code.
`resource_operator_state.go` owns the operator-set per-resource intent
-schema. `ResourceOperatorState` carries four narrow operator-intent
+schema. `ResourceOperatorState` carries five narrow operator-intent
fields (`IntentionallyOffline`, `NeverAutoRemediate`, maintenance
window via `MaintenanceStartAt` / `MaintenanceEndAt` / `MaintenanceReason`,
-and a canonical `Criticality` hint of `high|medium|low|""`) plus
+canonical `Criticality` hint of `high|medium|low|""`, and an explicit
+`AutoRemediationPolicy`) plus
operator-attribution metadata (`Note`, `SetAt`, `SetBy`). The shape is
intentionally fixed-field rather than a freeform metadata bag so
downstream finding-suppression and severity-weighting logic has a stable
contract to honor. `ValidateResourceOperatorState` rejects malformed
records with a stable `ErrResourceOperatorStateInvalid` sentinel
(empty canonical id, partial maintenance window, end ≤ start, unknown
-criticality), and `NormalizeResourceOperatorState` trims whitespace
-and lower-cases the criticality value before persistence. The
+criticality, enabled automatic-action policy without a capability allowlist,
+unknown timezone, or invalid recurring-window minute). The automatic-action
+policy is opt-in and names exact capability IDs; its optional daily IANA-timezone
+window may cross midnight. `NeverAutoRemediate` always wins. Capability-owned
+`ResourceCapability.AutoAuthorization` independently declares whether a
+capability is never eligible, low-risk eligible, or elevated eligible; it does
+not lower `MinimumApprovalLevel`. The first eligible vertical is Docker/Podman
+container `restart` at `low_risk`; unspecified capabilities normalize to never.
+`NormalizeResourceOperatorState` trims whitespace, de-duplicates capability
+names, and lower-cases the criticality value before persistence. The
`ResourceStore` interface now exposes
`GetResourceOperatorState`, `SetResourceOperatorState`, and
`ClearResourceOperatorState`; both the SQLite (table
@@ -1463,12 +1473,13 @@ The operator-facing surface for this contract is
`ResourceOperatorStateSection.tsx` on the resource detail drawer
overview tab, which routes through the canonical TS client at
`frontend-modern/src/api/resourceOperatorState.ts` to
-`/api/resources/{id}/operator-state`. The drawer integration is
-read-only on maintenance windows (the section badges an active
-window when `now` falls within it but does not let the operator
-schedule one — that lives in a follow-up slice). The two boolean
-toggles (intentionally offline, never auto-remediate) are the
-operator-facing primitives this slice surfaces.
+`/api/resources/{id}/operator-state`. Alongside the existing operator-state
+controls, the drawer offers automatic actions only for backend-advertised
+eligible capabilities. Enabling it requires selecting exact capabilities and
+may add a recurring daily time/timezone window; copy must state that this is a
+resource allowlist and that the tenant Patrol mode remains the upper bound.
+The UI must never infer eligibility from capability names, severity, or the
+human approval floor.
The `/api/resources/{id}/operator-state` API surface (GET / PUT /
DELETE) in `internal/api/resources_operator_state.go` is the
diff --git a/frontend-modern/src/api/__tests__/resourceOperatorState.test.ts b/frontend-modern/src/api/__tests__/resourceOperatorState.test.ts
index 6fc672dbc0..1a6d97b5e9 100644
--- a/frontend-modern/src/api/__tests__/resourceOperatorState.test.ts
+++ b/frontend-modern/src/api/__tests__/resourceOperatorState.test.ts
@@ -66,6 +66,11 @@ describe('resourceOperatorState api', () => {
const input: ResourceOperatorStateInput = {
intentionallyOffline: true,
neverAutoRemediate: false,
+ autoRemediationPolicy: {
+ enabled: true,
+ capabilityNames: ['restart'],
+ window: { timezone: 'Europe/London', startMinute: 60, endMinute: 180 },
+ },
};
const result = await setResourceOperatorState('vm:101', input);
@@ -80,6 +85,13 @@ describe('resourceOperatorState api', () => {
// (setAt, setBy) — never echo the input verbatim.
expect(result.setAt).toBe('2026-05-09T11:00:00Z');
expect(result.setBy).toBe('operator:richard');
+ expect(JSON.parse(apiFetchJSONMock.mock.calls[0][1]?.body as string)).toMatchObject({
+ autoRemediationPolicy: {
+ enabled: true,
+ capabilityNames: ['restart'],
+ window: { timezone: 'Europe/London', startMinute: 60, endMinute: 180 },
+ },
+ });
});
it('DELETEs without expecting a body response', async () => {
diff --git a/frontend-modern/src/api/resourceOperatorState.ts b/frontend-modern/src/api/resourceOperatorState.ts
index 460eac440c..39411bf0e4 100644
--- a/frontend-modern/src/api/resourceOperatorState.ts
+++ b/frontend-modern/src/api/resourceOperatorState.ts
@@ -9,6 +9,18 @@ import { apiFetchJSON } from '@/utils/apiClient';
*/
export type ResourceCriticality = 'high' | 'medium' | 'low' | '';
+export interface AutoRemediationWindow {
+ timezone: string;
+ startMinute: number;
+ endMinute: number;
+}
+
+export interface AutoRemediationPolicy {
+ enabled: boolean;
+ capabilityNames: string[];
+ window?: AutoRemediationWindow;
+}
+
export interface ResourceOperatorState {
canonicalId: string;
/**
@@ -26,6 +38,8 @@ export interface ResourceOperatorState {
* record with `resource_remediation_locked:` prefix on the error.
*/
neverAutoRemediate: boolean;
+ /** Explicit capability allowlist; tenant mode and backend eligibility remain upper bounds. */
+ autoRemediationPolicy?: AutoRemediationPolicy;
/**
* Maintenance window — when present and `now` falls within it, all
* new findings on this resource get auto-acknowledged with
diff --git a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx
index fcb9d0ca30..f52187c24b 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx
@@ -326,6 +326,12 @@ export const ResourceDetailDrawerOverviewTab: Component<ResourceDetailDrawerOver
drawer.resourceTimelineCount() > 0 ||
Boolean(drawer.facetBundleError());
const shouldRenderOperationalGovernanceSections = () => !compactTableRow();
+ const shouldRenderOperatorStateSection = () =>
+ !compactTableRow() ||
+ resource.capabilities?.some(
+ (capability) =>
+ capability.autoAuthorization && capability.autoAuthorization !== 'never',
+ );
const shouldRenderActionHistorySection = () =>
drawer.actionAuditAvailable() &&
(!compactTableRow() ||
@@ -661,8 +667,11 @@ export const ResourceDetailDrawerOverviewTab: Component<ResourceDetailDrawerOver
the "what overrides has the operator set" and "what actions
has Pulse taken" stories read together. The section is
self-fetching keyed on the canonical resource id. */}
- <Show when={shouldRenderOperationalGovernanceSections() && resource.id}>
- <ResourceOperatorStateSection resourceId={resource.id} />
+ <Show when={shouldRenderOperatorStateSection() && resource.id}>
+ <ResourceOperatorStateSection
+ resourceId={resource.id}
+ capabilities={resource.capabilities}
+ />
</Show>
{/* Maintenance Verification Reports sit directly under the
diff --git a/frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx b/frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx
index 355c26219e..0bf8452ab6 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceOperatorStateSection.tsx
@@ -1,4 +1,4 @@
-import { Component, Show, createEffect, createMemo, createSignal } from 'solid-js';
+import { Component, For, Show, createEffect, createMemo, createSignal } from 'solid-js';
import { Toggle } from '@/components/shared/Toggle';
import { notificationStore } from '@/stores/notifications';
import {
@@ -11,6 +11,7 @@ import {
} from '@/api/resourceOperatorState';
import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
import { formatRelativeTime } from '@/utils/format';
+import type { ResourceCapability } from '@/types/resource';
/**
* ResourceOperatorStateSection surfaces the operator-set per-resource
@@ -30,6 +31,7 @@ import { formatRelativeTime } from '@/utils/format';
*/
interface ResourceOperatorStateSectionProps {
resourceId: string;
+ capabilities?: ResourceCapability[];
}
export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectionProps> = (
@@ -65,6 +67,35 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
const [note, setNote] = createSignal('');
const [saving, setSaving] = createSignal(false);
const [confirmingLock, setConfirmingLock] = createSignal(false);
+ const [autoRemediationEnabled, setAutoRemediationEnabled] = createSignal(false);
+ const [autoCapabilities, setAutoCapabilities] = createSignal<string[]>([]);
+ const [autoWindowEnabled, setAutoWindowEnabled] = createSignal(false);
+ const [autoWindowStart, setAutoWindowStart] = createSignal('00:00');
+ const [autoWindowEnd, setAutoWindowEnd] = createSignal('23:59');
+ const [autoWindowTimezone, setAutoWindowTimezone] = createSignal('UTC');
+
+ const eligibleAutoCapabilities = createMemo(() =>
+ (props.capabilities ?? []).filter(
+ (capability) => capability.autoAuthorization && capability.autoAuthorization !== 'never',
+ ),
+ );
+
+ const minuteToTime = (minute: number): string => {
+ const normalized = Math.max(0, Math.min(1439, minute));
+ return `${String(Math.floor(normalized / 60)).padStart(2, '0')}:${String(normalized % 60).padStart(2, '0')}`;
+ };
+
+ const timeToMinute = (value: string): number => {
+ const [hours, minutes] = value.split(':').map(Number);
+ return hours * 60 + minutes;
+ };
+
+ const capabilityDisplayName = (name: string): string =>
+ name
+ .split('_')
+ .filter(Boolean)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(' ');
// Maintenance-window scheduler state. The form is closed by default;
// `Schedule maintenance window` opens it pre-filled with sensible
@@ -85,6 +116,15 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
setNeverAutoRemediate(current?.neverAutoRemediate ?? false);
setCriticality(current?.criticality ?? '');
setNote(current?.note ?? '');
+ const autoPolicy = current?.autoRemediationPolicy;
+ setAutoRemediationEnabled(autoPolicy?.enabled ?? false);
+ setAutoCapabilities(autoPolicy?.capabilityNames ?? []);
+ setAutoWindowEnabled(Boolean(autoPolicy?.window));
+ setAutoWindowStart(minuteToTime(autoPolicy?.window?.startMinute ?? 0));
+ setAutoWindowEnd(minuteToTime(autoPolicy?.window?.endMinute ?? 1439));
+ setAutoWindowTimezone(
+ autoPolicy?.window?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC',
+ );
setConfirmingLock(false);
});
@@ -94,11 +134,26 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
const persistedLocked = current?.neverAutoRemediate ?? false;
const persistedCriticality = current?.criticality ?? '';
const persistedNote = current?.note ?? '';
+ const persistedAuto = current?.autoRemediationPolicy ?? {
+ enabled: false,
+ capabilityNames: [],
+ };
+ const selected = [...autoCapabilities()].sort();
+ const persistedSelected = [...persistedAuto.capabilityNames].sort();
+ const windowChanged = autoWindowEnabled()
+ ? !persistedAuto.window ||
+ persistedAuto.window.timezone !== autoWindowTimezone() ||
+ persistedAuto.window.startMinute !== timeToMinute(autoWindowStart()) ||
+ persistedAuto.window.endMinute !== timeToMinute(autoWindowEnd())
+ : Boolean(persistedAuto.window);
return (
intentionallyOffline() !== persistedOffline ||
neverAutoRemediate() !== persistedLocked ||
criticality() !== persistedCriticality ||
- note().trim() !== persistedNote
+ note().trim() !== persistedNote ||
+ autoRemediationEnabled() !== persistedAuto.enabled ||
+ JSON.stringify(selected) !== JSON.stringify(persistedSelected) ||
+ windowChanged
);
});
@@ -131,6 +186,19 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
const input: ResourceOperatorStateInput = {
intentionallyOffline: intentionallyOffline(),
neverAutoRemediate: neverAutoRemediate(),
+ autoRemediationPolicy: {
+ enabled: autoRemediationEnabled(),
+ capabilityNames: autoCapabilities(),
+ ...(autoWindowEnabled()
+ ? {
+ window: {
+ timezone: autoWindowTimezone(),
+ startMinute: timeToMinute(autoWindowStart()),
+ endMinute: timeToMinute(autoWindowEnd()),
+ },
+ }
+ : {}),
+ },
// Preserve any maintenance-window data the API currently holds
// — window scheduling is a separate action and clobbering it
// on save would surprise the operator.
@@ -160,6 +228,15 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
setNeverAutoRemediate(current?.neverAutoRemediate ?? false);
setCriticality(current?.criticality ?? '');
setNote(current?.note ?? '');
+ const autoPolicy = current?.autoRemediationPolicy;
+ setAutoRemediationEnabled(autoPolicy?.enabled ?? false);
+ setAutoCapabilities(autoPolicy?.capabilityNames ?? []);
+ setAutoWindowEnabled(Boolean(autoPolicy?.window));
+ setAutoWindowStart(minuteToTime(autoPolicy?.window?.startMinute ?? 0));
+ setAutoWindowEnd(minuteToTime(autoPolicy?.window?.endMinute ?? 1439));
+ setAutoWindowTimezone(
+ autoPolicy?.window?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC',
+ );
setConfirmingLock(false);
};
@@ -175,6 +252,9 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
setNeverAutoRemediate(false);
setCriticality('');
setNote('');
+ setAutoRemediationEnabled(false);
+ setAutoCapabilities([]);
+ setAutoWindowEnabled(false);
notificationStore.success('Operator overrides cleared');
} catch (err) {
notificationStore.error(
@@ -185,6 +265,21 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
}
};
+ const toggleAutoCapability = (name: string, checked: boolean) => {
+ setAutoCapabilities((current) =>
+ checked ? [...new Set([...current, name])] : current.filter((value) => value !== name),
+ );
+ };
+
+ const autoPolicyValidationError = createMemo(() => {
+ if (!autoRemediationEnabled()) return '';
+ if (autoCapabilities().length === 0) return 'Select at least one eligible capability.';
+ if (autoWindowEnabled() && autoWindowStart() === autoWindowEnd()) {
+ return 'The automatic-action window must have different start and end times.';
+ }
+ return '';
+ });
+
// Compute whether a maintenance window covers `now` so the section
// can badge it. Distinct from `scheduledMaintenanceWindow` — both
// active and future windows are surfaced, with different copy.
@@ -283,6 +378,19 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
// editing one facet must not lose work on the other.
intentionallyOffline: intentionallyOffline(),
neverAutoRemediate: neverAutoRemediate(),
+ autoRemediationPolicy: {
+ enabled: autoRemediationEnabled(),
+ capabilityNames: autoCapabilities(),
+ ...(autoWindowEnabled()
+ ? {
+ window: {
+ timezone: autoWindowTimezone(),
+ startMinute: timeToMinute(autoWindowStart()),
+ endMinute: timeToMinute(autoWindowEnd()),
+ },
+ }
+ : {}),
+ },
maintenanceStartAt: start.toISOString(),
maintenanceEndAt: end.toISOString(),
maintenanceReason: scheduleReason().trim() || undefined,
@@ -308,6 +416,19 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
const input: ResourceOperatorStateInput = {
intentionallyOffline: intentionallyOffline(),
neverAutoRemediate: neverAutoRemediate(),
+ autoRemediationPolicy: {
+ enabled: autoRemediationEnabled(),
+ capabilityNames: autoCapabilities(),
+ ...(autoWindowEnabled()
+ ? {
+ window: {
+ timezone: autoWindowTimezone(),
+ startMinute: timeToMinute(autoWindowStart()),
+ endMinute: timeToMinute(autoWindowEnd()),
+ },
+ }
+ : {}),
+ },
maintenanceStartAt: undefined,
maintenanceEndAt: undefined,
maintenanceReason: undefined,
@@ -380,12 +501,12 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
<div class="grid grid-cols-1 gap-3 pt-2 border-t border-border-subtle sm:grid-cols-[minmax(0,12rem)_minmax(0,1fr)]">
<label class="block">
- <span class="text-sm font-medium text-base-content">Patrol priority</span>
+ <span class="block text-sm font-medium text-base-content">Patrol priority</span>
<select
value={criticality()}
onChange={(e) => setCriticality(e.currentTarget.value as ResourceCriticality)}
disabled={saving()}
- class="mt-1 w-full text-xs rounded border border-border bg-surface px-2 py-1.5 text-base-content focus:outline-none focus:ring-1 focus:ring-blue-400 disabled:opacity-50"
+ class="mt-1 block w-full text-xs rounded border border-border bg-surface px-2 py-1.5 text-base-content focus:outline-none focus:ring-1 focus:ring-blue-400 disabled:opacity-50"
>
<option value="">Default</option>
<option value="high">High</option>
@@ -398,12 +519,12 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
</label>
<label class="block">
- <span class="text-sm font-medium text-base-content">Operator note</span>
+ <span class="block text-sm font-medium text-base-content">Operator note</span>
<textarea
value={note()}
onInput={(e) => setNote(e.currentTarget.value)}
placeholder="e.g. Production database; page before rebooting"
- class="mt-1 min-h-16 w-full resize-y text-xs rounded border border-border bg-surface px-2 py-1.5 text-base-content focus:outline-none focus:ring-1 focus:ring-blue-400 disabled:opacity-50"
+ class="mt-1 block min-h-16 w-full resize-y text-xs rounded border border-border bg-surface px-2 py-1.5 text-base-content focus:outline-none focus:ring-1 focus:ring-blue-400 disabled:opacity-50"
disabled={saving()}
maxLength={500}
/>
@@ -549,6 +670,115 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
</div>
</Show>
+ <Show when={eligibleAutoCapabilities().length > 0}>
+ <div class="space-y-3 border-t border-border-subtle pt-3" aria-label="Automatic actions">
+ <div class="flex items-start justify-between gap-3">
+ <div class="flex-1">
+ <label class="text-sm font-medium text-base-content">Automatic actions</label>
+ <p class="mt-0.5 text-[11px] leading-tight text-muted">
+ Choose exactly which actions Patrol may run on this resource. Your Patrol mode,
+ live safety checks, remediation locks, and verification still apply.
+ </p>
+ </div>
+ <Toggle
+ checked={autoRemediationEnabled()}
+ onChange={(event) => setAutoRemediationEnabled(event.currentTarget.checked)}
+ disabled={saving() || neverAutoRemediate()}
+ />
+ </div>
+
+ <Show when={autoRemediationEnabled()}>
+ <fieldset class="space-y-2 rounded border border-border bg-surface-alt/40 px-3 py-2.5">
+ <legend class="px-1 text-xs font-semibold text-base-content">Allowed actions</legend>
+ <For each={eligibleAutoCapabilities()}>
+ {(capability) => (
+ <label class="flex items-start gap-2 text-xs text-base-content">
+ <input
+ type="checkbox"
+ checked={autoCapabilities().includes(capability.name)}
+ onChange={(event) =>
+ toggleAutoCapability(capability.name, event.currentTarget.checked)
+ }
+ disabled={saving()}
+ class="mt-0.5"
+ />
+ <span class="min-w-0">
+ <span class="block font-medium">
+ {capabilityDisplayName(capability.name)}
+ </span>
+ <span class="block text-muted">
+ {capability.description || 'Backend-governed resource action'}
+ </span>
+ <span class="mt-0.5 block text-muted">
+ {capability.autoAuthorization === 'low_risk'
+ ? 'Available in Safe auto-fix and Autopilot'
+ : 'Available only in unlocked Autopilot'}
+ </span>
+ </span>
+ </label>
+ )}
+ </For>
+
+ <label class="flex items-center justify-between gap-3 border-t border-border-subtle pt-2">
+ <span>
+ <span class="block text-xs font-medium text-base-content">
+ Restrict to daily hours
+ </span>
+ <span class="block text-[11px] text-muted">
+ Leave off to allow the selected actions at any time.
+ </span>
+ </span>
+ <Toggle
+ checked={autoWindowEnabled()}
+ onChange={(event) => setAutoWindowEnabled(event.currentTarget.checked)}
+ disabled={saving()}
+ />
+ </label>
+
+ <Show when={autoWindowEnabled()}>
+ <div class="grid grid-cols-1 gap-2 sm:grid-cols-3">
+ <label class="block text-[11px] text-muted">
+ <span class="block">Start</span>
+ <input
+ type="time"
+ value={autoWindowStart()}
+ onInput={(event) => setAutoWindowStart(event.currentTarget.value)}
+ disabled={saving()}
+ class="mt-0.5 w-full rounded border border-border bg-surface px-2 py-1 text-xs text-base-content"
+ />
+ </label>
+ <label class="block text-[11px] text-muted">
+ <span class="block">End</span>
+ <input
+ type="time"
+ value={autoWindowEnd()}
+ onInput={(event) => setAutoWindowEnd(event.currentTarget.value)}
+ disabled={saving()}
+ class="mt-0.5 w-full rounded border border-border bg-surface px-2 py-1 text-xs text-base-content"
+ />
+ </label>
+ <label class="block text-[11px] text-muted">
+ <span class="block">Timezone</span>
+ <input
+ type="text"
+ value={autoWindowTimezone()}
+ onInput={(event) => setAutoWindowTimezone(event.currentTarget.value)}
+ disabled={saving()}
+ class="mt-0.5 w-full rounded border border-border bg-surface px-2 py-1 text-xs text-base-content"
+ />
+ </label>
+ </div>
+ </Show>
+ <Show when={autoPolicyValidationError()}>
+ <p class="text-[11px] text-red-700 dark:text-red-400">
+ {autoPolicyValidationError()}
+ </p>
+ </Show>
+ </fieldset>
+ </Show>
+ </div>
+ </Show>
+
<div class="flex items-start justify-between gap-3">
<div class="flex-1">
<label class="text-sm font-medium text-base-content">Intentionally offline</label>
@@ -631,7 +861,7 @@ export const ResourceOperatorStateSection: Component<ResourceOperatorStateSectio
<button
type="button"
onClick={handleSave}
- disabled={saving()}
+ disabled={saving() || Boolean(autoPolicyValidationError())}
class="px-2.5 py-1 text-xs font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 rounded transition-colors"
>
{saving() ? 'Saving…' : 'Save overrides'}
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts
index f234e3a10f..932095f31c 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceOperatorStateSection.test.ts
@@ -31,6 +31,15 @@ describe('ResourceOperatorStateSection', () => {
expect(sectionSource).toContain('setNote');
});
+ it('requires explicit capability scope and preserves the backend eligibility ceiling', () => {
+ expect(sectionSource).toContain('Automatic actions');
+ expect(sectionSource).toContain("capability.autoAuthorization !== 'never'");
+ expect(sectionSource).toContain('Select at least one eligible capability.');
+ expect(sectionSource).toContain('Restrict to daily hours');
+ expect(sectionSource).toContain('autoRemediationPolicy');
+ expect(sectionSource).toContain('disabled={saving() || Boolean(autoPolicyValidationError())}');
+ });
+
it('keeps the section out of the parent Suspense fallback by using createNonSuspendingQuery', () => {
// The drawer wraps its children in a page-level Suspense fallback;
// a vanilla createResource here would flicker the fallback every
@@ -178,9 +187,7 @@ describe('ResourceDetailDrawerOverviewTab integration', () => {
// what Pulse actually did. They belong on the same drawer surface
// so the operator can read both stories together.
expect(overviewTabSource).toContain("from './ResourceOperatorStateSection'");
- expect(overviewTabSource).toContain(
- '<ResourceOperatorStateSection resourceId={resource.id} />',
- );
+ expect(overviewTabSource).toContain('capabilities={resource.capabilities}');
// Section must precede the action-history block so the override
// explains the actions that follow, not vice versa.
const operatorIndex = overviewTabSource.indexOf('<ResourceOperatorStateSection');
@@ -189,4 +196,13 @@ describe('ResourceDetailDrawerOverviewTab integration', () => {
expect(historyIndex).toBeGreaterThan(0);
expect(operatorIndex).toBeLessThan(historyIndex);
});
+
+ it('keeps eligible automatic actions reachable from compact platform rows', () => {
+ expect(overviewTabSource).toContain('shouldRenderOperatorStateSection');
+ expect(overviewTabSource).toContain('capability.autoAuthorization');
+ expect(overviewTabSource).toContain("capability.autoAuthorization !== 'never'");
+ expect(overviewTabSource).toContain(
+ '<Show when={shouldRenderOperatorStateSection() && resource.id}>',
+ );
+ });
});
diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.ts
index 2a26320101..84c6afd71f 100644
--- a/frontend-modern/src/types/resource.ts
+++ b/frontend-modern/src/types/resource.ts
@@ -308,6 +308,7 @@ export interface ResourceCapability {
type: string;
description?: string;
minimumApprovalLevel?: string;
+ autoAuthorization?: 'never' | 'low_risk' | 'elevated';
platform?: string;
params?: ResourceCapabilityParam[];
}
diff --git a/internal/actionlifecycle/service.go b/internal/actionlifecycle/service.go
index 6d6166fb71..50f03ba9bb 100644
--- a/internal/actionlifecycle/service.go
+++ b/internal/actionlifecycle/service.go
@@ -264,6 +264,14 @@ func (s *Service) PlanWithOptions(ctx context.Context, orgID string, req unified
if err != nil {
return unified.ActionPlan{}, err
}
+ if existing, found, queryErr := store.GetActionAudit(plan.ActionID); queryErr != nil {
+ return unified.ActionPlan{}, &QueryError{Op: "idempotent action audit", Err: queryErr}
+ } else if found {
+ // Replayed proposals must never rewind an approved, executing, or
+ // terminal action back to its initial plan state. The deterministic
+ // action id already binds request, resource, and capability policy.
+ return existing.Plan, nil
+ }
record, err := persistPlanAudit(store, req, plan, opts.Origin)
if err != nil {
return unified.ActionPlan{}, &PersistError{Op: "action plan audit", Err: err}
@@ -272,6 +280,33 @@ func (s *Service) PlanWithOptions(ctx context.Context, orgID string, req unified
return plan, nil
}
+// Get returns the authoritative audit record for an action.
+func (s *Service) Get(orgID, actionID string) (unified.ActionAuditRecord, bool, error) {
+ store, err := s.store(orgID)
+ if err != nil {
+ return unified.ActionAuditRecord{}, false, err
+ }
+ record, found, err := store.GetActionAudit(strings.TrimSpace(actionID))
+ if err != nil {
+ return unified.ActionAuditRecord{}, false, &QueryError{Op: "action audit", Err: err}
+ }
+ return record, found, nil
+}
+
+// ResourceOperatorState returns the authoritative per-resource policy used by
+// execution and Patrol policy authorization.
+func (s *Service) ResourceOperatorState(orgID, resourceID string) (unified.ResourceOperatorState, bool, error) {
+ store, err := s.store(orgID)
+ if err != nil {
+ return unified.ResourceOperatorState{}, false, err
+ }
+ state, found, err := store.GetResourceOperatorState(unified.CanonicalResourceID(resourceID))
+ if err != nil {
+ return unified.ResourceOperatorState{}, false, &QueryError{Op: "resource operator state", Err: err}
+ }
+ return state, found, nil
+}
+
// Capabilities returns the resource's advertised capability declarations
// through the same registry resolution and typed errors as planning, so a
// proposing surface can inspect capability names and parameter schemas
diff --git a/internal/actionplanner/planner.go b/internal/actionplanner/planner.go
index 761d51fb58..de6b8e8fbf 100644
--- a/internal/actionplanner/planner.go
+++ b/internal/actionplanner/planner.go
@@ -143,20 +143,22 @@ func ResourceVersion(resource unified.Resource) string {
func PolicyVersion(capability unified.ResourceCapability) string {
payload := struct {
- Name string `json:"name"`
- Type unified.CapabilityType `json:"type"`
- Description string `json:"description"`
- MinimumApprovalLevel unified.ActionApprovalLevel `json:"minimumApprovalLevel"`
- Platform string `json:"platform,omitempty"`
- InternalHandler string `json:"internalHandler,omitempty"`
- Params []unified.CapabilityParam `json:"params,omitempty"`
- NormalizedPolicy unified.ActionApprovalLevel `json:"normalizedPolicy"`
- ParamNames []string `json:"paramNames,omitempty"`
+ Name string `json:"name"`
+ Type unified.CapabilityType `json:"type"`
+ Description string `json:"description"`
+ MinimumApprovalLevel unified.ActionApprovalLevel `json:"minimumApprovalLevel"`
+ AutoAuthorization unified.ActionAutoAuthorizationClass `json:"autoAuthorization,omitempty"`
+ Platform string `json:"platform,omitempty"`
+ InternalHandler string `json:"internalHandler,omitempty"`
+ Params []unified.CapabilityParam `json:"params,omitempty"`
+ NormalizedPolicy unified.ActionApprovalLevel `json:"normalizedPolicy"`
+ ParamNames []string `json:"paramNames,omitempty"`
}{
Name: strings.TrimSpace(capability.Name),
Type: capability.Type,
Description: strings.TrimSpace(capability.Description),
MinimumApprovalLevel: capability.MinimumApprovalLevel,
+ AutoAuthorization: capability.AutoAuthorization,
Platform: strings.TrimSpace(capability.Platform),
InternalHandler: strings.TrimSpace(capability.InternalHandler),
Params: normalizeCapabilityParams(capability.Params),
@@ -570,12 +572,13 @@ func displayResourceName(resource unified.Resource) string {
}
type normalizedCapabilityForResourceHash struct {
- Name string `json:"name"`
- Type unified.CapabilityType `json:"type"`
- Description string `json:"description"`
- MinimumApprovalLevel unified.ActionApprovalLevel `json:"minimumApprovalLevel"`
- Platform string `json:"platform,omitempty"`
- Params []unified.CapabilityParam `json:"params,omitempty"`
+ Name string `json:"name"`
+ Type unified.CapabilityType `json:"type"`
+ Description string `json:"description"`
+ MinimumApprovalLevel unified.ActionApprovalLevel `json:"minimumApprovalLevel"`
+ AutoAuthorization unified.ActionAutoAuthorizationClass `json:"autoAuthorization,omitempty"`
+ Platform string `json:"platform,omitempty"`
+ Params []unified.CapabilityParam `json:"params,omitempty"`
}
type normalizedRelationship struct {
@@ -640,6 +643,7 @@ func normalizeCapabilitiesForResourceHash(capabilities []unified.ResourceCapabil
Type: capability.Type,
Description: strings.TrimSpace(capability.Description),
MinimumApprovalLevel: capability.MinimumApprovalLevel,
+ AutoAuthorization: capability.AutoAuthorization,
Platform: strings.TrimSpace(capability.Platform),
Params: normalizeCapabilityParams(capability.Params),
})
diff --git a/internal/actionplanner/planner_test.go b/internal/actionplanner/planner_test.go
index 3d595f1d2f..6c3e6c8428 100644
--- a/internal/actionplanner/planner_test.go
+++ b/internal/actionplanner/planner_test.go
@@ -227,6 +227,38 @@ func TestPlannerReturnsCapabilityNotFound(t *testing.T) {
}
}
+func TestPlannerIdentityChangesWhenAutoAuthorizationEligibilityChanges(t *testing.T) {
+ resource := unified.Resource{
+ ID: "app-container:demo",
+ Type: unified.ResourceTypeAppContainer,
+ Name: "demo",
+ Status: unified.StatusOnline,
+ Capabilities: []unified.ResourceCapability{{
+ Name: "restart",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ }},
+ }
+ req := unified.ActionRequest{
+ RequestID: "proposal-1",
+ ResourceID: resource.ID,
+ CapabilityName: "restart",
+ Reason: "recover service",
+ RequestedBy: "pulse_patrol",
+ }
+ withoutEligibility, err := (Planner{}).Plan(req, resource)
+ if err != nil {
+ t.Fatalf("plan without eligibility: %v", err)
+ }
+ resource.Capabilities[0].AutoAuthorization = unified.AutoAuthorizeLowRisk
+ withEligibility, err := (Planner{}).Plan(req, resource)
+ if err != nil {
+ t.Fatalf("plan with eligibility: %v", err)
+ }
+ if withoutEligibility.PolicyVersion == withEligibility.PolicyVersion || withoutEligibility.ActionID == withEligibility.ActionID || withoutEligibility.PlanHash == withEligibility.PlanHash {
+ t.Fatalf("auto-authorization eligibility must participate in plan identity: without=%#v with=%#v", withoutEligibility, withEligibility)
+ }
+}
+
func TestExportedValidationMatchesPlanningExactly(t *testing.T) {
capabilities := []unified.ResourceCapability{{
Name: "restart",
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index cc457f0e61..3dea06991b 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -20485,7 +20485,7 @@ func TestProUpdateBrokerWiringContract(t *testing.T) {
}
}
-func TestContract_PatrolActionBrokerIsPlanOnly(t *testing.T) {
+func TestContract_PatrolActionBrokerKeepsPolicyExecutionCoreOwned(t *testing.T) {
source, err := os.ReadFile("patrol_action_broker.go")
if err != nil {
t.Fatalf("read patrol_action_broker.go: %v", err)
@@ -20504,14 +20504,25 @@ func TestContract_PatrolActionBrokerIsPlanOnly(t *testing.T) {
"action proposal requires an investigation id",
} {
if !strings.Contains(src, snippet) {
- t.Fatalf("patrol_action_broker.go must pin plan-only broker snippet %q", snippet)
+ t.Fatalf("patrol_action_broker.go must pin typed broker snippet %q", snippet)
}
}
- // The broker must stay a proposer: no decision or execution calls on
- // the lifecycle service, ever.
- for _, forbidden := range []string{".Decide(", ".Execute(", "ExecuteAction(", "ExecuteCommand("} {
+ for _, required := range []string{
+ "autoAuthorizationDecision",
+ "AutoAuthorizeLowRisk",
+ "AllowsAutoRemediationAt",
+ "MethodPolicy",
+ "pulse_patrol_policy",
+ } {
+ if !strings.Contains(src, required) {
+ t.Fatalf("patrol_action_broker.go must keep core policy authorization guard %q", required)
+ }
+ }
+ // Enterprise/model code still cannot dispatch directly. Core may call
+ // only the canonical lifecycle decision/execute methods after policy.
+ for _, forbidden := range []string{"ExecuteAction(", "ExecuteCommand("} {
if strings.Contains(src, forbidden) {
- t.Fatalf("patrol_action_broker.go must not dispatch via %q", forbidden)
+ t.Fatalf("patrol_action_broker.go must not bypass the lifecycle via %q", forbidden)
}
}
}
diff --git a/internal/api/patrol_action_broker.go b/internal/api/patrol_action_broker.go
index 6cd9884c06..19c6111865 100644
--- a/internal/api/patrol_action_broker.go
+++ b/internal/api/patrol_action_broker.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"strings"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
@@ -18,27 +19,44 @@ const patrolActionBrokerActor = "pulse_patrol"
// decisions and terminal outcomes can be reconciled onto the finding.
const patrolActionOriginSurface = "patrol"
+const patrolActionPolicyActor = "pulse_patrol_policy"
+
+// PatrolActionPolicySnapshot is core-owned authorization posture. Enterprise
+// code and model output cannot populate it.
+type PatrolActionPolicySnapshot struct {
+ EffectiveAutonomyLevel string
+ FullModeUnlocked bool
+}
+
+type PatrolActionPolicyProvider func(ctx context.Context, orgID string) (PatrolActionPolicySnapshot, error)
+
// patrolActionBroker is the org-bound core adapter behind
// aicontracts.OrchestratorActionBroker. It routes every Patrol proposal
// through the shared action lifecycle service: identical registry lookup,
// capability validation, availability checks, plan hashing, and audit
-// persistence as the REST plan endpoint. Submit is plan-only; approval and
-// execution remain on the canonical decision/execute lifecycle, so the
-// enterprise investigation side stays a proposer, never a dispatcher.
+// persistence as the REST plan endpoint. Core may authorize and execute an
+// eligible proposal under stored tenant/resource policy; the enterprise
+// investigation side stays a proposer, never a dispatcher.
type patrolActionBroker struct {
orgID string
// lifecycle resolves the shared service per call so late-bound
// executor and publisher wiring on ResourceHandlers stays current.
lifecycle func() *actionlifecycle.Service
+ policy PatrolActionPolicyProvider
+ now func() time.Time
}
// NewPatrolActionBroker builds the tenant-bound Patrol proposal broker over
// the shared action lifecycle service.
-func NewPatrolActionBroker(orgID string, resources *ResourceHandlers) aicontracts.OrchestratorActionBroker {
- return &patrolActionBroker{
+func NewPatrolActionBroker(orgID string, resources *ResourceHandlers, policy ...PatrolActionPolicyProvider) aicontracts.OrchestratorActionBroker {
+ broker := &patrolActionBroker{
orgID: strings.TrimSpace(orgID),
lifecycle: resources.ActionLifecycle,
}
+ if len(policy) > 0 {
+ broker.policy = policy[0]
+ }
+ return broker
}
func (b *patrolActionBroker) Capabilities(ctx context.Context, resourceID string) (aicontracts.ActionCapabilityCatalog, error) {
@@ -56,6 +74,7 @@ func (b *patrolActionBroker) Capabilities(ctx context.Context, resourceID string
Name: capability.Name,
Description: capability.Description,
MinimumApprovalLevel: string(capability.MinimumApprovalLevel),
+ AutoAuthorization: string(unified.NormalizeActionAutoAuthorizationClass(capability.AutoAuthorization)),
Platform: capability.Platform,
Params: make([]aicontracts.ActionCapabilityParamInfo, 0, len(capability.Params)),
}
@@ -125,13 +144,111 @@ func (b *patrolActionBroker) Submit(ctx context.Context, proposal aicontracts.Ac
return aicontracts.ActionDisposition{}, err
}
- // Plan-only by contract: even an ApprovalNone capability is returned
- // as a planned disposition and never auto-executed on submission.
+ record, found, err := b.lifecycle().Get(b.orgID, plan.ActionID)
+ if err != nil {
+ return aicontracts.ActionDisposition{}, err
+ }
+ if !found {
+ return aicontracts.ActionDisposition{}, fmt.Errorf("planned action %q was not persisted", plan.ActionID)
+ }
+ if record.State == unified.ActionStateCompleted || record.State == unified.ActionStateFailed || record.State == unified.ActionStateRejected {
+ return dispositionFromRecord(record), nil
+ }
+
+ if allowed, reason, policyErr := b.autoAuthorizationDecision(ctx, proposal); policyErr == nil && allowed {
+ // Re-evaluate immediately before the decision+dispatch sequence so a
+ // resource lock, scope removal, or tenant-mode downgrade cannot leave
+ // behind a reusable policy approval. A failed recheck leaves the plan in
+ // its ordinary pending/planned state.
+ stillAllowed, _, policyErr := b.autoAuthorizationDecision(ctx, proposal)
+ if policyErr != nil || !stillAllowed {
+ return dispositionFromRecord(record), nil
+ }
+ if record.State == unified.ActionStatePending {
+ record, err = b.lifecycle().Decide(ctx, b.orgID, plan.ActionID, unified.ActionApprovalRecord{
+ Actor: patrolActionPolicyActor,
+ Method: unified.MethodPolicy,
+ Outcome: unified.OutcomeApproved,
+ Reason: reason,
+ })
+ if err != nil {
+ return aicontracts.ActionDisposition{}, err
+ }
+ }
+ record, err = b.lifecycle().Execute(ctx, b.orgID, plan.ActionID, patrolActionPolicyActor, reason)
+ if err != nil {
+ if record.State == unified.ActionStateFailed {
+ return dispositionFromRecord(record), nil
+ }
+ return dispositionFromRecord(record), err
+ }
+ }
+
+ return dispositionFromRecord(record), nil
+}
+
+func dispositionFromRecord(record unified.ActionAuditRecord) aicontracts.ActionDisposition {
return aicontracts.ActionDisposition{
- ActionID: plan.ActionID,
- State: string(actionlifecycle.PlannedActionState(plan)),
- Plan: *approvalPlanRequestToInfo(&plan),
- }, nil
+ ActionID: record.ID,
+ State: string(record.State),
+ VerificationStatus: string(record.VerificationOutcome.Status),
+ Plan: *approvalPlanRequestToInfo(&record.Plan),
+ }
+}
+
+func (b *patrolActionBroker) autoAuthorizationDecision(ctx context.Context, proposal aicontracts.ActionProposal) (bool, string, error) {
+ if b.policy == nil {
+ return false, "", nil
+ }
+ snapshot, err := b.policy(ctx, b.orgID)
+ if err != nil {
+ return false, "", err
+ }
+ capabilities, err := b.lifecycle().Capabilities(ctx, b.orgID, proposal.ResourceID)
+ if err != nil {
+ return false, "", err
+ }
+ var capability *unified.ResourceCapability
+ for i := range capabilities {
+ if strings.TrimSpace(capabilities[i].Name) == proposal.CapabilityName {
+ capability = &capabilities[i]
+ break
+ }
+ }
+ if capability == nil {
+ return false, "", nil
+ }
+ class := unified.NormalizeActionAutoAuthorizationClass(capability.AutoAuthorization)
+ if class == unified.AutoAuthorizeNever || capability.MinimumApprovalLevel == unified.ApprovalDryRun || capability.MinimumApprovalLevel == unified.ApprovalMultiFactor {
+ return false, "", nil
+ }
+ switch strings.TrimSpace(snapshot.EffectiveAutonomyLevel) {
+ case "assisted":
+ if class != unified.AutoAuthorizeLowRisk {
+ return false, "", nil
+ }
+ case "full":
+ if !snapshot.FullModeUnlocked {
+ return false, "", nil
+ }
+ default:
+ return false, "", nil
+ }
+ state, found, err := b.lifecycle().ResourceOperatorState(b.orgID, proposal.ResourceID)
+ if err != nil {
+ return false, "", err
+ }
+ if !found || !state.AllowsAutoRemediationAt(proposal.CapabilityName, b.currentTime()) {
+ return false, "", nil
+ }
+ return true, fmt.Sprintf("Patrol %s policy authorized %s capability %s for resource %s", snapshot.EffectiveAutonomyLevel, class, proposal.CapabilityName, proposal.ResourceID), nil
+}
+
+func (b *patrolActionBroker) currentTime() time.Time {
+ if b.now != nil {
+ return b.now().UTC()
+ }
+ return time.Now().UTC()
}
// rejectSensitiveParams fails a proposal that populates any parameter the
diff --git a/internal/api/patrol_action_broker_test.go b/internal/api/patrol_action_broker_test.go
index f77f4b8d71..e39cb0460d 100644
--- a/internal/api/patrol_action_broker_test.go
+++ b/internal/api/patrol_action_broker_test.go
@@ -18,6 +18,10 @@ import (
)
func newPatrolBrokerTestHandlers(t *testing.T, minimumApproval unified.ActionApprovalLevel) (*ResourceHandlers, *stubActionExecutor) {
+ return newPatrolBrokerTestHandlersWithEligibility(t, minimumApproval, unified.AutoAuthorizeLowRisk)
+}
+
+func newPatrolBrokerTestHandlersWithEligibility(t *testing.T, minimumApproval unified.ActionApprovalLevel, eligibility unified.ActionAutoAuthorizationClass) (*ResourceHandlers, *stubActionExecutor) {
t.Helper()
now := time.Now().UTC()
h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
@@ -38,6 +42,7 @@ func newPatrolBrokerTestHandlers(t *testing.T, minimumApproval unified.ActionApp
Type: unified.CapabilityTypeCommon,
Description: "Restart the VM",
MinimumApprovalLevel: minimumApproval,
+ AutoAuthorization: eligibility,
InternalHandler: "proxmox.vm.restart",
Params: []unified.CapabilityParam{
{Name: "mode", Type: "string", Required: true, Enum: []string{"graceful", "force"}},
@@ -92,7 +97,7 @@ func TestPatrolActionBrokerSubmitPlansThroughCanonicalLifecycle(t *testing.T) {
t.Fatalf("plan projection = %#v", disposition.Plan)
}
if executor.calls != 0 {
- t.Fatalf("submit must never execute, executor calls = %d", executor.calls)
+ t.Fatalf("submit without core policy must not execute, executor calls = %d", executor.calls)
}
store, err := h.getStore("default")
@@ -115,7 +120,7 @@ func TestPatrolActionBrokerSubmitPlansThroughCanonicalLifecycle(t *testing.T) {
}
}
-func TestPatrolActionBrokerSubmitIsPlanOnlyForApprovalNone(t *testing.T) {
+func TestPatrolActionBrokerApprovalNoneDoesNotExecuteWithoutCorePolicy(t *testing.T) {
h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalNone)
broker := NewPatrolActionBroker("default", h)
@@ -130,7 +135,7 @@ func TestPatrolActionBrokerSubmitIsPlanOnlyForApprovalNone(t *testing.T) {
t.Fatal("ApprovalNone capability should not require approval")
}
if executor.calls != 0 {
- t.Fatalf("submit must never auto-execute, executor calls = %d", executor.calls)
+ t.Fatalf("submit without core policy must not execute, executor calls = %d", executor.calls)
}
}
@@ -178,7 +183,7 @@ func TestPatrolActionBrokerCapabilitiesCatalog(t *testing.T) {
byName[capability.Name] = capability
}
restart := byName["restart"]
- if restart.MinimumApprovalLevel != string(unified.ApprovalAdmin) || len(restart.Params) != 1 || restart.Params[0].Sensitive {
+ if restart.MinimumApprovalLevel != string(unified.ApprovalAdmin) || restart.AutoAuthorization != string(unified.AutoAuthorizeLowRisk) || len(restart.Params) != 1 || restart.Params[0].Sensitive {
t.Fatalf("restart capability = %#v", restart)
}
join := byName["join_cluster"]
@@ -191,6 +196,179 @@ func TestPatrolActionBrokerCapabilitiesCatalog(t *testing.T) {
}
}
+func TestPatrolActionBrokerAutoAuthorizesOnlyExplicitScopedEligibleCapability(t *testing.T) {
+ h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("getStore: %v", err)
+ }
+ if err := store.SetResourceOperatorState(unified.ResourceOperatorState{
+ CanonicalID: "vm:42",
+ AutoRemediationPolicy: unified.AutoRemediationPolicy{
+ Enabled: true,
+ CapabilityNames: []string{"restart"},
+ },
+ SetAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+ broker := NewPatrolActionBroker("default", h, func(context.Context, string) (PatrolActionPolicySnapshot, error) {
+ return PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "assisted"}, nil
+ })
+
+ disposition, err := broker.Submit(context.Background(), patrolTestProposal())
+ if err != nil {
+ t.Fatalf("Submit: %v", err)
+ }
+ if disposition.State != string(unified.ActionStateCompleted) {
+ t.Fatalf("state = %q, want completed", disposition.State)
+ }
+ if executor.calls != 1 {
+ t.Fatalf("executor calls = %d, want 1", executor.calls)
+ }
+ audit, found, err := store.GetActionAudit(disposition.ActionID)
+ if err != nil || !found {
+ t.Fatalf("GetActionAudit: found=%v err=%v", found, err)
+ }
+ if len(audit.Approvals) != 1 || audit.Approvals[0].Actor != patrolActionPolicyActor || audit.Approvals[0].Method != unified.MethodPolicy {
+ t.Fatalf("policy approval = %#v", audit.Approvals)
+ }
+
+ // An idempotent proposal replay returns the terminal audit and cannot
+ // rewind or execute the action a second time.
+ replayed, err := broker.Submit(context.Background(), patrolTestProposal())
+ if err != nil || replayed.State != string(unified.ActionStateCompleted) {
+ t.Fatalf("replay disposition=%#v err=%v", replayed, err)
+ }
+ if executor.calls != 1 {
+ t.Fatalf("replay executor calls = %d, want 1", executor.calls)
+ }
+}
+
+func TestPatrolActionBrokerPolicyScopeAndWindowFailClosed(t *testing.T) {
+ h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("getStore: %v", err)
+ }
+ if err := store.SetResourceOperatorState(unified.ResourceOperatorState{
+ CanonicalID: "vm:42",
+ AutoRemediationPolicy: unified.AutoRemediationPolicy{
+ Enabled: true,
+ CapabilityNames: []string{"restart"},
+ Window: &unified.AutoRemediationWindow{
+ Timezone: "UTC", StartMinute: 60, EndMinute: 120,
+ },
+ },
+ SetAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+ broker := NewPatrolActionBroker("default", h, func(context.Context, string) (PatrolActionPolicySnapshot, error) {
+ return PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "assisted"}, nil
+ }).(*patrolActionBroker)
+ broker.now = func() time.Time { return time.Date(2026, 7, 10, 3, 0, 0, 0, time.UTC) }
+
+ disposition, err := broker.Submit(context.Background(), patrolTestProposal())
+ if err != nil {
+ t.Fatalf("Submit: %v", err)
+ }
+ if disposition.State != string(unified.ActionStatePending) || executor.calls != 0 {
+ t.Fatalf("outside-window disposition=%#v calls=%d", disposition, executor.calls)
+ }
+}
+
+func TestPatrolActionBrokerAutonomyModeIsAnUpperBound(t *testing.T) {
+ tests := []struct {
+ name string
+ eligibility unified.ActionAutoAuthorizationClass
+ snapshot PatrolActionPolicySnapshot
+ wantCalls int
+ }{
+ {name: "monitor denies low risk", eligibility: unified.AutoAuthorizeLowRisk, snapshot: PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "monitor"}},
+ {name: "approval denies low risk", eligibility: unified.AutoAuthorizeLowRisk, snapshot: PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "approval"}},
+ {name: "assisted denies elevated", eligibility: unified.AutoAuthorizeElevated, snapshot: PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "assisted"}},
+ {name: "locked full denies elevated", eligibility: unified.AutoAuthorizeElevated, snapshot: PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "full"}},
+ {name: "unlocked full admits elevated", eligibility: unified.AutoAuthorizeElevated, snapshot: PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "full", FullModeUnlocked: true}, wantCalls: 1},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ h, executor := newPatrolBrokerTestHandlersWithEligibility(t, unified.ApprovalAdmin, tc.eligibility)
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("getStore: %v", err)
+ }
+ if err := store.SetResourceOperatorState(unified.ResourceOperatorState{
+ CanonicalID: "vm:42",
+ AutoRemediationPolicy: unified.AutoRemediationPolicy{
+ Enabled: true,
+ CapabilityNames: []string{"restart"},
+ },
+ SetAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+ broker := NewPatrolActionBroker("default", h, func(context.Context, string) (PatrolActionPolicySnapshot, error) {
+ return tc.snapshot, nil
+ })
+ disposition, err := broker.Submit(context.Background(), patrolTestProposal())
+ if err != nil {
+ t.Fatalf("Submit: %v", err)
+ }
+ if executor.calls != tc.wantCalls {
+ t.Fatalf("executor calls = %d, want %d (disposition=%#v)", executor.calls, tc.wantCalls, disposition)
+ }
+ if tc.wantCalls == 0 && disposition.State != string(unified.ActionStatePending) {
+ t.Fatalf("denied state = %q, want pending_approval", disposition.State)
+ }
+ if tc.wantCalls == 1 && disposition.State != string(unified.ActionStateCompleted) {
+ t.Fatalf("authorized state = %q, want completed", disposition.State)
+ }
+ })
+ }
+}
+
+func TestPatrolActionBrokerRevokedPolicyCannotLeaveReusableApproval(t *testing.T) {
+ h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("getStore: %v", err)
+ }
+ if err := store.SetResourceOperatorState(unified.ResourceOperatorState{
+ CanonicalID: "vm:42",
+ AutoRemediationPolicy: unified.AutoRemediationPolicy{
+ Enabled: true,
+ CapabilityNames: []string{"restart"},
+ },
+ SetAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+ policyReads := 0
+ broker := NewPatrolActionBroker("default", h, func(context.Context, string) (PatrolActionPolicySnapshot, error) {
+ policyReads++
+ if policyReads == 1 {
+ return PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "assisted"}, nil
+ }
+ return PatrolActionPolicySnapshot{EffectiveAutonomyLevel: "approval"}, nil
+ })
+
+ disposition, err := broker.Submit(context.Background(), patrolTestProposal())
+ if err != nil {
+ t.Fatalf("Submit: %v", err)
+ }
+ if disposition.State != string(unified.ActionStatePending) || executor.calls != 0 {
+ t.Fatalf("revoked disposition=%#v calls=%d", disposition, executor.calls)
+ }
+ record, found, err := store.GetActionAudit(disposition.ActionID)
+ if err != nil || !found {
+ t.Fatalf("GetActionAudit: found=%v err=%v", found, err)
+ }
+ if len(record.Approvals) != 0 || record.Result != nil {
+ t.Fatalf("revoked policy left reusable authority: approvals=%#v result=%#v", record.Approvals, record.Result)
+ }
+}
+
func TestPatrolActionBrokerRequiresCorrelationIdentity(t *testing.T) {
h, _ := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
broker := NewPatrolActionBroker("default", h)
diff --git a/internal/api/resources_operator_state.go b/internal/api/resources_operator_state.go
index e49699c7d5..67439e794a 100644
--- a/internal/api/resources_operator_state.go
+++ b/internal/api/resources_operator_state.go
@@ -18,30 +18,32 @@ import (
// adapts to and from `unified.ResourceOperatorState` so the storage
// type's evolution stays decoupled from the wire format.
type resourceOperatorStateAPI struct {
- CanonicalID string `json:"canonicalId"`
- IntentionallyOffline bool `json:"intentionallyOffline"`
- NeverAutoRemediate bool `json:"neverAutoRemediate"`
- MaintenanceStartAt *time.Time `json:"maintenanceStartAt,omitempty"`
- MaintenanceEndAt *time.Time `json:"maintenanceEndAt,omitempty"`
- MaintenanceReason string `json:"maintenanceReason,omitempty"`
- Criticality string `json:"criticality,omitempty"`
- Note string `json:"note,omitempty"`
- SetAt time.Time `json:"setAt"`
- SetBy string `json:"setBy,omitempty"`
+ CanonicalID string `json:"canonicalId"`
+ IntentionallyOffline bool `json:"intentionallyOffline"`
+ NeverAutoRemediate bool `json:"neverAutoRemediate"`
+ AutoRemediationPolicy unified.AutoRemediationPolicy `json:"autoRemediationPolicy"`
+ MaintenanceStartAt *time.Time `json:"maintenanceStartAt,omitempty"`
+ MaintenanceEndAt *time.Time `json:"maintenanceEndAt,omitempty"`
+ MaintenanceReason string `json:"maintenanceReason,omitempty"`
+ Criticality string `json:"criticality,omitempty"`
+ Note string `json:"note,omitempty"`
+ SetAt time.Time `json:"setAt"`
+ SetBy string `json:"setBy,omitempty"`
}
func toResourceOperatorStateAPI(state unified.ResourceOperatorState) resourceOperatorStateAPI {
return resourceOperatorStateAPI{
- CanonicalID: state.CanonicalID,
- IntentionallyOffline: state.IntentionallyOffline,
- NeverAutoRemediate: state.NeverAutoRemediate,
- MaintenanceStartAt: state.MaintenanceStartAt,
- MaintenanceEndAt: state.MaintenanceEndAt,
- MaintenanceReason: state.MaintenanceReason,
- Criticality: string(state.Criticality),
- Note: state.Note,
- SetAt: state.SetAt,
- SetBy: state.SetBy,
+ CanonicalID: state.CanonicalID,
+ IntentionallyOffline: state.IntentionallyOffline,
+ NeverAutoRemediate: state.NeverAutoRemediate,
+ AutoRemediationPolicy: state.AutoRemediationPolicy,
+ MaintenanceStartAt: state.MaintenanceStartAt,
+ MaintenanceEndAt: state.MaintenanceEndAt,
+ MaintenanceReason: state.MaintenanceReason,
+ Criticality: string(state.Criticality),
+ Note: state.Note,
+ SetAt: state.SetAt,
+ SetBy: state.SetBy,
}
}
@@ -100,14 +102,15 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
// canonical_id from URL wins over body to prevent scope confusion
// (operator wrote vm:101 in the URL but vm:102 in the body).
state := unified.ResourceOperatorState{
- CanonicalID: resourceID,
- IntentionallyOffline: payload.IntentionallyOffline,
- NeverAutoRemediate: payload.NeverAutoRemediate,
- MaintenanceStartAt: payload.MaintenanceStartAt,
- MaintenanceEndAt: payload.MaintenanceEndAt,
- MaintenanceReason: payload.MaintenanceReason,
- Criticality: unified.ResourceCriticality(payload.Criticality),
- Note: payload.Note,
+ CanonicalID: resourceID,
+ IntentionallyOffline: payload.IntentionallyOffline,
+ NeverAutoRemediate: payload.NeverAutoRemediate,
+ AutoRemediationPolicy: payload.AutoRemediationPolicy,
+ MaintenanceStartAt: payload.MaintenanceStartAt,
+ MaintenanceEndAt: payload.MaintenanceEndAt,
+ MaintenanceReason: payload.MaintenanceReason,
+ Criticality: unified.ResourceCriticality(payload.Criticality),
+ Note: payload.Note,
// Server-populated attribution: ignore any client values so
// the audit trail can't be spoofed.
SetAt: time.Now().UTC(),
diff --git a/internal/api/router.go b/internal/api/router.go
index 9bdec86e19..3ca9d4da9c 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -661,7 +661,21 @@ func (r *Router) setupRoutes() {
r.resourceHandlers.SetActionTransitionPublisher(r.aiSettingsHandler.ReconcilePatrolActionTransition)
resourceHandlers := r.resourceHandlers
r.aiSettingsHandler.SetActionBrokerFactory(func(orgID string) aicontracts.OrchestratorActionBroker {
- return NewPatrolActionBroker(orgID, resourceHandlers)
+ return NewPatrolActionBroker(orgID, resourceHandlers, func(ctx context.Context, scopedOrgID string) (PatrolActionPolicySnapshot, error) {
+ orgCtx := context.WithValue(ctx, OrgIDContextKey, approval.NormalizeOrgID(scopedOrgID))
+ svc := r.aiSettingsHandler.GetAIService(orgCtx)
+ if svc == nil {
+ return PatrolActionPolicySnapshot{}, nil
+ }
+ cfg := svc.GetConfig()
+ if cfg == nil {
+ return PatrolActionPolicySnapshot{}, nil
+ }
+ return PatrolActionPolicySnapshot{
+ EffectiveAutonomyLevel: svc.GetEffectivePatrolAutonomyLevel(),
+ FullModeUnlocked: cfg.PatrolFullModeUnlocked,
+ }, nil
+ })
})
r.aiSettingsHandler.SetProposalCatalogFactory(func(orgID string) tools.ProposalCatalog {
return func(ctx context.Context, resourceID string) ([]unifiedresources.ResourceCapability, error) {
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index 163f2d6a61..204b39a8e8 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -45,6 +45,7 @@ const (
MethodUI ApprovalMethod = "ui"
MethodAPI ApprovalMethod = "api"
MethodMFAChallenge ApprovalMethod = "mfa_challenge"
+ MethodPolicy ApprovalMethod = "policy"
)
// ActionApprovalRecord captures a specific approval or rejection event.
diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.go
index aefec4fd6a..221069d8b5 100644
--- a/internal/unifiedresources/adapters.go
+++ b/internal/unifiedresources/adapters.go
@@ -2219,11 +2219,16 @@ func dockerContainerLifecycleCapabilitySet(runtime string, names ...string) []Re
if name == "" {
continue
}
+ autoAuthorization := AutoAuthorizeNever
+ if name == "restart" {
+ autoAuthorization = AutoAuthorizeLowRisk
+ }
capabilities = append(capabilities, ResourceCapability{
Name: name,
Type: CapabilityTypeCommon,
Description: fmt.Sprintf("%s this %s container through its reporting Pulse agent.", titleAction(name), displayRuntime),
MinimumApprovalLevel: ApprovalAdmin,
+ AutoAuthorization: autoAuthorization,
Platform: runtime,
InternalHandler: "docker.container.lifecycle",
})
diff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.go
index 3e1659cb24..056a0b412e 100644
--- a/internal/unifiedresources/adapters_test.go
+++ b/internal/unifiedresources/adapters_test.go
@@ -95,6 +95,13 @@ func TestResourceFromDockerContainerAdvertisesLifecycleCapabilities(t *testing.T
if capability.Platform != "docker" || capability.InternalHandler != "docker.container.lifecycle" {
t.Fatalf("capability %q platform/handler = %q/%q", capability.Name, capability.Platform, capability.InternalHandler)
}
+ wantAuto := AutoAuthorizeNever
+ if capability.Name == "restart" {
+ wantAuto = AutoAuthorizeLowRisk
+ }
+ if capability.AutoAuthorization != wantAuto {
+ t.Fatalf("capability %q auto authorization = %q, want %q", capability.Name, capability.AutoAuthorization, wantAuto)
+ }
}
exited, _ := resourceFromDockerContainer(models.DockerContainer{
diff --git a/internal/unifiedresources/capabilities.go b/internal/unifiedresources/capabilities.go
index e6c9e4a3dc..3716b31096 100644
--- a/internal/unifiedresources/capabilities.go
+++ b/internal/unifiedresources/capabilities.go
@@ -10,6 +10,36 @@ const (
ApprovalMultiFactor ActionApprovalLevel = "mfa" // Requires strict explicit 2FA
)
+// ActionAutoAuthorizationClass declares whether a capability may ever be
+// authorized by core-owned Patrol policy instead of a human decision. This is
+// independent from MinimumApprovalLevel: the approval floor remains the human
+// fallback and audit classification, while this class is an explicit
+// capability-owner opt-in to policy authorization. Empty and unknown values
+// always mean never.
+type ActionAutoAuthorizationClass string
+
+const (
+ AutoAuthorizeNever ActionAutoAuthorizationClass = "never"
+ AutoAuthorizeLowRisk ActionAutoAuthorizationClass = "low_risk"
+ AutoAuthorizeElevated ActionAutoAuthorizationClass = "elevated"
+)
+
+func IsValidActionAutoAuthorizationClass(value ActionAutoAuthorizationClass) bool {
+ switch value {
+ case "", AutoAuthorizeNever, AutoAuthorizeLowRisk, AutoAuthorizeElevated:
+ return true
+ default:
+ return false
+ }
+}
+
+func NormalizeActionAutoAuthorizationClass(value ActionAutoAuthorizationClass) ActionAutoAuthorizationClass {
+ if value == "" || !IsValidActionAutoAuthorizationClass(value) {
+ return AutoAuthorizeNever
+ }
+ return value
+}
+
// CapabilityType represents a standard unified intent or a vendor-specific escape hatch.
type CapabilityType string
@@ -32,13 +62,14 @@ type CapabilityParam struct {
// ResourceCapability defines a bounded safe action that can be performed against a resource.
type ResourceCapability struct {
- Name string `json:"name"`
- Type CapabilityType `json:"type"`
- Description string `json:"description"`
- MinimumApprovalLevel ActionApprovalLevel `json:"minimumApprovalLevel"` // Policy may escalate this
- Platform string `json:"platform,omitempty"`
- InternalHandler string `json:"-"` // DO NOT expose execution plumbing to public surfaces
- Params []CapabilityParam `json:"params,omitempty"`
+ Name string `json:"name"`
+ Type CapabilityType `json:"type"`
+ Description string `json:"description"`
+ MinimumApprovalLevel ActionApprovalLevel `json:"minimumApprovalLevel"` // Policy may escalate this
+ AutoAuthorization ActionAutoAuthorizationClass `json:"autoAuthorization,omitempty"` // Missing/never stays human-authorized
+ Platform string `json:"platform,omitempty"`
+ InternalHandler string `json:"-"` // DO NOT expose execution plumbing to public surfaces
+ Params []CapabilityParam `json:"params,omitempty"`
}
// ResourceActionReadiness carries backend-owned current executability state
diff --git a/internal/unifiedresources/resource_operator_state.go b/internal/unifiedresources/resource_operator_state.go
index 06685238fa..ea890a901d 100644
--- a/internal/unifiedresources/resource_operator_state.go
+++ b/internal/unifiedresources/resource_operator_state.go
@@ -3,6 +3,7 @@ package unifiedresources
import (
"errors"
"fmt"
+ "sort"
"strings"
"time"
)
@@ -19,6 +20,25 @@ const (
CriticalityLow ResourceCriticality = "low"
)
+// AutoRemediationWindow is an optional recurring daily window in an IANA
+// timezone. StartMinute is inclusive and EndMinute is exclusive. Windows may
+// cross midnight; a nil window means any time. The explicit timezone keeps
+// policy evaluation stable across server moves and daylight-saving changes.
+type AutoRemediationWindow struct {
+ Timezone string `json:"timezone"`
+ StartMinute int `json:"startMinute"`
+ EndMinute int `json:"endMinute"`
+}
+
+// AutoRemediationPolicy is the operator's explicit per-resource allowlist.
+// Tenant Patrol mode and capability eligibility are independent upper bounds:
+// this record can only narrow them. Disabled or empty policy fails closed.
+type AutoRemediationPolicy struct {
+ Enabled bool `json:"enabled"`
+ CapabilityNames []string `json:"capabilityNames"`
+ Window *AutoRemediationWindow `json:"window,omitempty"`
+}
+
// IsValidCriticality reports whether the value is empty or one of the three
// canonical levels. Empty is valid (operator has not set a hint). Anything
// else is rejected at the API boundary so freeform strings cannot accumulate
@@ -64,6 +84,12 @@ type ResourceOperatorState struct {
// operator must clear the flag to allow remediation.
NeverAutoRemediate bool `json:"neverAutoRemediate"`
+ // AutoRemediationPolicy explicitly opts this resource and named
+ // capabilities into policy authorization. It never overrides
+ // NeverAutoRemediate, capability eligibility, tenant mode, MFA, dry-run,
+ // or any execution-time safety gate.
+ AutoRemediationPolicy AutoRemediationPolicy `json:"autoRemediationPolicy"`
+
// MaintenanceStartAt and MaintenanceEndAt define a time-bounded
// suppression window. When now is within [start, end), all findings
// raised against this resource get auto-acknowledged with
@@ -106,6 +132,9 @@ type ResourceOperatorState struct {
func (s ResourceOperatorState) IsEmpty() bool {
return !s.IntentionallyOffline &&
!s.NeverAutoRemediate &&
+ !s.AutoRemediationPolicy.Enabled &&
+ len(s.AutoRemediationPolicy.CapabilityNames) == 0 &&
+ s.AutoRemediationPolicy.Window == nil &&
s.MaintenanceStartAt == nil &&
s.MaintenanceEndAt == nil &&
strings.TrimSpace(s.MaintenanceReason) == "" &&
@@ -150,6 +179,9 @@ func ValidateResourceOperatorState(state ResourceOperatorState) error {
if !IsValidCriticality(string(state.Criticality)) {
return fmt.Errorf("%w: criticality %q is not one of (high, medium, low, empty)", ErrResourceOperatorStateInvalid, state.Criticality)
}
+ if err := ValidateAutoRemediationPolicy(state.AutoRemediationPolicy); err != nil {
+ return fmt.Errorf("%w: %v", ErrResourceOperatorStateInvalid, err)
+ }
startSet := state.MaintenanceStartAt != nil
endSet := state.MaintenanceEndAt != nil
if startSet != endSet {
@@ -173,9 +205,95 @@ func NormalizeResourceOperatorState(state ResourceOperatorState) ResourceOperato
state.Note = strings.TrimSpace(state.Note)
state.SetBy = strings.TrimSpace(state.SetBy)
state.Criticality = ResourceCriticality(strings.ToLower(strings.TrimSpace(string(state.Criticality))))
+ state.AutoRemediationPolicy = NormalizeAutoRemediationPolicy(state.AutoRemediationPolicy)
return state
}
+// NormalizeAutoRemediationPolicy returns a deterministic copy for storage,
+// hashing, and exact capability matching.
+func NormalizeAutoRemediationPolicy(policy AutoRemediationPolicy) AutoRemediationPolicy {
+ seen := map[string]struct{}{}
+ names := make([]string, 0, len(policy.CapabilityNames))
+ for _, name := range policy.CapabilityNames {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ continue
+ }
+ if _, ok := seen[name]; ok {
+ continue
+ }
+ seen[name] = struct{}{}
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ policy.CapabilityNames = names
+ if policy.Window != nil {
+ window := *policy.Window
+ window.Timezone = strings.TrimSpace(window.Timezone)
+ policy.Window = &window
+ }
+ return policy
+}
+
+func ValidateAutoRemediationPolicy(policy AutoRemediationPolicy) error {
+ policy = NormalizeAutoRemediationPolicy(policy)
+ if policy.Enabled && len(policy.CapabilityNames) == 0 {
+ return errors.New("enabled auto remediation requires at least one capability")
+ }
+ if policy.Window == nil {
+ return nil
+ }
+ if policy.Window.Timezone == "" {
+ return errors.New("auto remediation window requires an IANA timezone")
+ }
+ if _, err := time.LoadLocation(policy.Window.Timezone); err != nil {
+ return fmt.Errorf("auto remediation timezone %q is invalid", policy.Window.Timezone)
+ }
+ if policy.Window.StartMinute < 0 || policy.Window.StartMinute > 1439 || policy.Window.EndMinute < 0 || policy.Window.EndMinute > 1439 {
+ return errors.New("auto remediation window minutes must be between 0 and 1439")
+ }
+ if policy.Window.StartMinute == policy.Window.EndMinute {
+ return errors.New("auto remediation window start and end must differ")
+ }
+ return nil
+}
+
+// AllowsAutoRemediationAt evaluates only the explicit per-resource scope.
+// Tenant mode, capability class, and lifecycle gates remain separate checks.
+func (s ResourceOperatorState) AllowsAutoRemediationAt(capabilityName string, now time.Time) bool {
+ if s.NeverAutoRemediate {
+ return false
+ }
+ policy := NormalizeAutoRemediationPolicy(s.AutoRemediationPolicy)
+ if !policy.Enabled {
+ return false
+ }
+ capabilityName = strings.TrimSpace(capabilityName)
+ allowed := false
+ for _, name := range policy.CapabilityNames {
+ if name == capabilityName {
+ allowed = true
+ break
+ }
+ }
+ if !allowed {
+ return false
+ }
+ if policy.Window == nil {
+ return true
+ }
+ location, err := time.LoadLocation(policy.Window.Timezone)
+ if err != nil {
+ return false
+ }
+ local := now.In(location)
+ minute := local.Hour()*60 + local.Minute()
+ if policy.Window.StartMinute < policy.Window.EndMinute {
+ return minute >= policy.Window.StartMinute && minute < policy.Window.EndMinute
+ }
+ return minute >= policy.Window.StartMinute || minute < policy.Window.EndMinute
+}
+
type resourceOperatorStateLifecycleStore interface {
SetResourceOperatorStateWithMaintenanceLifecycle(state ResourceOperatorState) (ResourceOperatorState, error)
ClearResourceOperatorStateWithMaintenanceLifecycle(canonicalID string, observedAt time.Time, actor string) error
diff --git a/internal/unifiedresources/resource_operator_state_policy_test.go b/internal/unifiedresources/resource_operator_state_policy_test.go
new file mode 100644
index 0000000000..6b09197405
--- /dev/null
+++ b/internal/unifiedresources/resource_operator_state_policy_test.go
@@ -0,0 +1,86 @@
+package unifiedresources
+
+import (
+ "testing"
+ "time"
+)
+
+func TestAutoRemediationPolicyRequiresExplicitCapabilityAndValidWindow(t *testing.T) {
+ state := ResourceOperatorState{
+ CanonicalID: "vm:42",
+ AutoRemediationPolicy: AutoRemediationPolicy{Enabled: true},
+ }
+ if err := ValidateResourceOperatorState(state); err == nil {
+ t.Fatal("enabled policy without capabilities must fail")
+ }
+ state.AutoRemediationPolicy = AutoRemediationPolicy{
+ Enabled: true,
+ CapabilityNames: []string{" restart ", "restart"},
+ Window: &AutoRemediationWindow{
+ Timezone: "Europe/London", StartMinute: 60, EndMinute: 180,
+ },
+ }
+ normalized := NormalizeResourceOperatorState(state)
+ if err := ValidateResourceOperatorState(normalized); err != nil {
+ t.Fatalf("valid policy: %v", err)
+ }
+ if len(normalized.AutoRemediationPolicy.CapabilityNames) != 1 || normalized.AutoRemediationPolicy.CapabilityNames[0] != "restart" {
+ t.Fatalf("normalized capabilities = %#v", normalized.AutoRemediationPolicy.CapabilityNames)
+ }
+}
+
+func TestResourceOperatorStateAllowsAutoRemediationInsideDailyWindow(t *testing.T) {
+ state := ResourceOperatorState{
+ AutoRemediationPolicy: AutoRemediationPolicy{
+ Enabled: true,
+ CapabilityNames: []string{"restart"},
+ Window: &AutoRemediationWindow{
+ Timezone: "UTC", StartMinute: 23 * 60, EndMinute: 2 * 60,
+ },
+ },
+ }
+ if !state.AllowsAutoRemediationAt("restart", time.Date(2026, 7, 10, 23, 30, 0, 0, time.UTC)) {
+ t.Fatal("cross-midnight window should allow late segment")
+ }
+ if !state.AllowsAutoRemediationAt("restart", time.Date(2026, 7, 11, 1, 30, 0, 0, time.UTC)) {
+ t.Fatal("cross-midnight window should allow early segment")
+ }
+ if state.AllowsAutoRemediationAt("restart", time.Date(2026, 7, 11, 3, 0, 0, 0, time.UTC)) {
+ t.Fatal("outside window must deny")
+ }
+ state.NeverAutoRemediate = true
+ if state.AllowsAutoRemediationAt("restart", time.Date(2026, 7, 10, 23, 30, 0, 0, time.UTC)) {
+ t.Fatal("never-auto-remediate must override explicit scope")
+ }
+}
+
+func TestAutoRemediationPolicySQLiteRoundTrip(t *testing.T) {
+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatalf("NewSQLiteResourceStore: %v", err)
+ }
+ defer store.Close()
+
+ state := ResourceOperatorState{
+ CanonicalID: "docker:container:web",
+ AutoRemediationPolicy: AutoRemediationPolicy{
+ Enabled: true,
+ CapabilityNames: []string{"restart"},
+ Window: &AutoRemediationWindow{
+ Timezone: "Europe/London", StartMinute: 120, EndMinute: 300,
+ },
+ },
+ SetAt: time.Now().UTC(),
+ SetBy: "[email protected]",
+ }
+ if err := store.SetResourceOperatorState(state); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+ got, found, err := store.GetResourceOperatorState(state.CanonicalID)
+ if err != nil || !found {
+ t.Fatalf("GetResourceOperatorState: found=%v err=%v", found, err)
+ }
+ if !got.AutoRemediationPolicy.Enabled || len(got.AutoRemediationPolicy.CapabilityNames) != 1 || got.AutoRemediationPolicy.Window == nil || got.AutoRemediationPolicy.Window.Timezone != "Europe/London" {
+ t.Fatalf("round-trip policy = %#v", got.AutoRemediationPolicy)
+ }
+}
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index 517b2fada9..89ed5cdbd4 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -474,6 +474,7 @@ func (s *SQLiteResourceStore) initSchema() error {
canonical_id TEXT PRIMARY KEY,
intentionally_offline INTEGER NOT NULL DEFAULT 0,
never_auto_remediate INTEGER NOT NULL DEFAULT 0,
+ auto_remediation_policy_json TEXT,
maintenance_start_at DATETIME,
maintenance_end_at DATETIME,
maintenance_reason TEXT,
@@ -533,12 +534,28 @@ func (s *SQLiteResourceStore) initSchema() error {
if err := s.migrateActionAuditsSchema(); err != nil {
return err
}
+ if err := s.migrateResourceOperatorStateSchema(); err != nil {
+ return err
+ }
if err := s.migrateActionAuditRedaction(); err != nil {
return err
}
return nil
}
+func (s *SQLiteResourceStore) migrateResourceOperatorStateSchema() error {
+ columns, err := s.tableColumns("resource_operator_state")
+ if err != nil {
+ return err
+ }
+ if _, ok := columns["auto_remediation_policy_json"]; !ok {
+ if _, err := s.db.Exec("ALTER TABLE resource_operator_state ADD COLUMN auto_remediation_policy_json TEXT"); err != nil {
+ return fmt.Errorf("add resource_operator_state.auto_remediation_policy_json column: %w", err)
+ }
+ }
+ return nil
+}
+
// migrateResourceIdentitiesSchema upgrades the resource_identities table from
// its original schema-only shape (no code ever wrote it before identity pins)
// to the pin layout: a cluster_name column and a unique canonical_id index so
@@ -2291,6 +2308,7 @@ func getResourceOperatorStateSQL(queryer resourceOperatorStateQueryRower, canoni
}
row := queryer.QueryRow(`
SELECT canonical_id, intentionally_offline, never_auto_remediate,
+ auto_remediation_policy_json,
maintenance_start_at, maintenance_end_at, maintenance_reason,
criticality, note, set_at, set_by
FROM resource_operator_state WHERE canonical_id = ?`, canonicalID)
@@ -2309,6 +2327,7 @@ func scanResourceOperatorState(scanner resourceOperatorStateScanner) (ResourceOp
var (
intentional int
neverRemediate int
+ autoPolicyJSON sql.NullString
startAt, endAt sql.NullTime
reason sql.NullString
criticality sql.NullString
@@ -2319,6 +2338,7 @@ func scanResourceOperatorState(scanner resourceOperatorStateScanner) (ResourceOp
&state.CanonicalID,
&intentional,
&neverRemediate,
+ &autoPolicyJSON,
&startAt,
&endAt,
&reason,
@@ -2331,6 +2351,12 @@ func scanResourceOperatorState(scanner resourceOperatorStateScanner) (ResourceOp
}
state.IntentionallyOffline = intentional != 0
state.NeverAutoRemediate = neverRemediate != 0
+ if autoPolicyJSON.Valid && strings.TrimSpace(autoPolicyJSON.String) != "" {
+ if err := json.Unmarshal([]byte(autoPolicyJSON.String), &state.AutoRemediationPolicy); err != nil {
+ return ResourceOperatorState{}, fmt.Errorf("unmarshal auto remediation policy: %w", err)
+ }
+ state.AutoRemediationPolicy = NormalizeAutoRemediationPolicy(state.AutoRemediationPolicy)
+ }
if startAt.Valid {
t := startAt.Time
state.MaintenanceStartAt = &t
@@ -2386,7 +2412,16 @@ func setResourceOperatorStateSQL(execer sqlExecutor, state ResourceOperatorState
criticality sql.NullString
note sql.NullString
setBy sql.NullString
+ autoPolicyJSON sql.NullString
)
+ if policy := NormalizeAutoRemediationPolicy(state.AutoRemediationPolicy); policy.Enabled || len(policy.CapabilityNames) > 0 || policy.Window != nil {
+ encoded, err := json.Marshal(policy)
+ if err != nil {
+ return fmt.Errorf("marshal auto remediation policy: %w", err)
+ }
+ autoPolicyJSON.String = string(encoded)
+ autoPolicyJSON.Valid = true
+ }
if state.MaintenanceStartAt != nil {
startAt.Time = *state.MaintenanceStartAt
startAt.Valid = true
@@ -2414,12 +2449,14 @@ func setResourceOperatorStateSQL(execer sqlExecutor, state ResourceOperatorState
_, err := execer.Exec(`
INSERT INTO resource_operator_state (
canonical_id, intentionally_offline, never_auto_remediate,
+ auto_remediation_policy_json,
maintenance_start_at, maintenance_end_at, maintenance_reason,
criticality, note, set_at, set_by
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(canonical_id) DO UPDATE SET
intentionally_offline = excluded.intentionally_offline,
never_auto_remediate = excluded.never_auto_remediate,
+ auto_remediation_policy_json = excluded.auto_remediation_policy_json,
maintenance_start_at = excluded.maintenance_start_at,
maintenance_end_at = excluded.maintenance_end_at,
maintenance_reason = excluded.maintenance_reason,
@@ -2430,6 +2467,7 @@ func setResourceOperatorStateSQL(execer sqlExecutor, state ResourceOperatorState
state.CanonicalID,
intentional,
neverRemediate,
+ autoPolicyJSON,
startAt,
endAt,
reason,
diff --git a/pkg/aicontracts/action_broker.go b/pkg/aicontracts/action_broker.go
index 784f869de2..56d2455e3f 100644
--- a/pkg/aicontracts/action_broker.go
+++ b/pkg/aicontracts/action_broker.go
@@ -15,8 +15,9 @@ import (
// (the adapter always stamps the fixed Patrol actor), no autonomy, risk,
// approval-policy, or destructive fields (authorization derives from the
// capability's declared policy, never from model or enterprise input), no
-// Decide/Execute methods, and no command or target-host fields. Submit is
-// plan-only; approval and execution stay on the canonical core lifecycle.
+// Decide/Execute methods, and no command or target-host fields. Submit hands
+// the proposal to core; only core may progress it under capability-owned
+// eligibility plus operator policy.
// ---------------------------------------------------------------------------
// ActionProposal is a typed, no-authority remediation proposal produced by
@@ -46,6 +47,7 @@ type ActionCapabilityInfo struct {
Name string `json:"name"`
Description string `json:"description"`
MinimumApprovalLevel string `json:"minimum_approval_level"`
+ AutoAuthorization string `json:"auto_authorization"`
Platform string `json:"platform,omitempty"`
Params []ActionCapabilityParamInfo `json:"params,omitempty"`
}
@@ -65,14 +67,15 @@ type ActionCapabilityParamInfo struct {
}
// ActionDisposition reports what the canonical planner did with a proposal.
-// State reflects the persisted audit state (pending_approval or planned);
-// the proposal never executes as a side effect of submission. Plan reuses
+// State reflects the persisted audit state, including a terminal state when
+// core policy authorized and executed the proposal. Plan reuses
// the existing safe ActionPlanInfo projection shared with approval
// surfaces (see fix_execution.go).
type ActionDisposition struct {
- ActionID string `json:"action_id"`
- State string `json:"state"`
- Plan ActionPlanInfo `json:"plan"`
+ ActionID string `json:"action_id"`
+ State string `json:"state"`
+ VerificationStatus string `json:"verification_status,omitempty"`
+ Plan ActionPlanInfo `json:"plan"`
}
// ActionReference links an investigation to its canonical action lifecycle
@@ -116,8 +119,8 @@ type OrchestratorActionBroker interface {
// Capabilities returns the resource's advertised capability catalog.
Capabilities(ctx context.Context, resourceID string) (ActionCapabilityCatalog, error)
// Submit plans the proposal through the canonical action lifecycle
- // and returns its persisted disposition. Plan-only: even a capability
- // that requires no approval is returned as a planned disposition,
- // never auto-executed by submission.
+ // and returns its persisted disposition. Any policy authorization and
+ // execution is core-owned; the enterprise caller has no decide/execute
+ // authority.
Submit(ctx context.Context, proposal ActionProposal) (ActionDisposition, error)
}
diff --git a/pkg/aicontracts/contracts_test.go b/pkg/aicontracts/contracts_test.go
index e52db609c0..fdc1770c11 100644
--- a/pkg/aicontracts/contracts_test.go
+++ b/pkg/aicontracts/contracts_test.go
@@ -261,6 +261,39 @@ func TestOrchestratorActionBrokerIsProposeOnly(t *testing.T) {
}
}
+func TestActionBrokerPolicyMetadataCarriesNoAuthorizationMethod(t *testing.T) {
+ catalogPayload, err := json.Marshal(ActionCapabilityCatalog{
+ ResourceID: "app-container:demo",
+ Capabilities: []ActionCapabilityInfo{{
+ Name: "restart",
+ AutoAuthorization: "low_risk",
+ }},
+ })
+ if err != nil {
+ t.Fatalf("marshal capability catalog: %v", err)
+ }
+ if !strings.Contains(string(catalogPayload), `"auto_authorization":"low_risk"`) {
+ t.Fatalf("catalog must expose core-owned eligibility: %s", catalogPayload)
+ }
+
+ dispositionPayload, err := json.Marshal(ActionDisposition{
+ ActionID: "act-1",
+ State: "completed",
+ VerificationStatus: "verified",
+ })
+ if err != nil {
+ t.Fatalf("marshal action disposition: %v", err)
+ }
+ if !strings.Contains(string(dispositionPayload), `"verification_status":"verified"`) {
+ t.Fatalf("disposition must carry terminal verification: %s", dispositionPayload)
+ }
+ for _, forbidden := range []string{"authorize", "approve", "execute"} {
+ if strings.Contains(string(catalogPayload), forbidden) || strings.Contains(string(dispositionPayload), forbidden) {
+ t.Fatalf("broker wire metadata must not carry a %s authority field", forbidden)
+ }
+ }
+}
+
func TestOrchestratorDepsExposesTypedActionBroker(t *testing.T) {
depsType := reflect.TypeOf(OrchestratorDeps{})
field, ok := depsType.FieldByName("ActionBroker")
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 35581380d3..d21d35dc33 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -4159,6 +4159,7 @@ class SubsystemLookupTest(unittest.TestCase):
"internal/unifiedresources/registry_test.go",
"internal/unifiedresources/resolve_test.go",
"internal/unifiedresources/resolved_host_set_test.go",
+ "internal/unifiedresources/resource_operator_state_policy_test.go",
"internal/unifiedresources/snapshot_source_filter_test.go",
"internal/unifiedresources/store_test.go",
],
@@ -4186,6 +4187,7 @@ class SubsystemLookupTest(unittest.TestCase):
"internal/unifiedresources/registry_test.go",
"internal/unifiedresources/resolve_test.go",
"internal/unifiedresources/resolved_host_set_test.go",
+ "internal/unifiedresources/resource_operator_state_policy_test.go",
"internal/unifiedresources/snapshot_source_filter_test.go",
"internal/unifiedresources/store_test.go",
],