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.

Enforce server-owned Patrol Autopilot acknowledgement

rcourtman76f1084c9bdf
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 1e080e4b28..d0485fae04 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -4430,6 +4430,75 @@
"evidence_tier": "test-proof"
}
]
+ },
+ {
+ "id": "RA39",
+ "summary": "Patrol Autopilot activation is server-owned: a static per-version contract registry preserves immutable historical scope and limits while effective full mode requires a current-version human acknowledgement bound to organization, actor, credential, and an atomic activation; rotation requires new evidence, and legacy booleans, stale or malformed evidence, cross-tenant records, API tokens, and revoked acknowledgements fail closed without rewriting authority history.",
+ "kind": "invariant",
+ "blocking_level": "repo-ready",
+ "proof_type": "automated",
+ "lane_ids": [
+ "L6",
+ "L10",
+ "L13",
+ "L14",
+ "L15",
+ "L16",
+ "L20"
+ ],
+ "subsystem_ids": [
+ "agent-lifecycle",
+ "ai-runtime",
+ "api-contracts",
+ "organization-settings",
+ "patrol-intelligence",
+ "performance-and-scalability",
+ "security-privacy",
+ "storage-recovery",
+ "unified-resources"
+ ],
+ "release_gate_ids": [],
+ "proof_commands": [
+ {
+ "id": "ra39-server-owned-patrol-autopilot-activation",
+ "run": [
+ "go",
+ "test",
+ "./internal/unifiedresources",
+ "./internal/config",
+ "./internal/ai",
+ "./internal/api",
+ "-run",
+ "TestPatrolAutopilot|TestEvaluatePatrolAutopilot|TestAIConfigPatrolAutopilot|TestServicePatrolAutopilotPolicyProviderControlsRuntimeVersion|TestGetPatrolSystemPrompt_ModeSwitch|TestRouterRouteInventory|TestProtectedAPIRoutesRejectUnauthenticatedRequests",
+ "-count=1"
+ ]
+ }
+ ],
+ "evidence": [
+ {
+ "repo": "pulse",
+ "path": "internal/api/patrol_autopilot_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/config/patrol_autopilot_persistence_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/patrol_autopilot.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/patrol_autopilot_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ }
+ ]
}
],
"evidence_reference_policy": {
@@ -5987,7 +6056,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. Three policy-authorized verticals are live. Docker/Podman restart is capability-owned low-risk eligible. Agent-managed APT host updates are capability-owned elevated eligible and cross a closed typed host_update protocol with no command, package-selection, removal, or reboot authority; the agent owns metadata refresh, preflight simulation, guarded installation, and post-install simulation, while the audit records verified, failed, or honestly inconclusive outcomes plus reboot-required state. Agent-managed package-cache cleanup is capability-owned low-risk eligible and crosses a separate fingerprint-bound host_storage_cleanup protocol with no command, path, package selector, installed-package removal, or reboot authority; it is available only for meaningful reclaimable bytes on the actual pressured cache filesystem, and the audit verifies the bytes reclaimed. All three require explicit per-resource capability allowlists and optional recurring timezone windows, remain bounded by tenant Patrol mode and full-mode unlock, recheck policy/readiness before decision and dispatch, and record server-owned policy approval plus terminal verification in the same audit trail. Never-auto-remediate, missing/unknown policy, unsupported capabilities, stale/error/empty package or cleanup inventories, cleared storage pressure, dry-run/MFA floors, closed windows, and mode downgrades all fail closed. Action continuity is audit-authoritative and now has a Phase B1 durable transport foundation: execution admission atomically creates the deterministic dispatch attempt/outbox, a one-shot pre-send CAS prevents concurrent duplicate sends, expired pre-send claims safely requeue, post-send uncertainty remains receipt-pending for query-only reconciliation, explicit expiry is durable, and canonical detail plus pending/settled reads are tenant-scoped. Generic transport errors cannot fabricate receipts or terminal truth, legacy executing rows without attempts remain inert, 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. Task 08 Phase B1 also makes requester and decision authority server-owned, binds actor and approval requirement into plan identity, rechecks current tenant/RBAC/token scope, and records multi-actor approvals through revision-CAS append-only decision facts plus atomic lifecycle transitions. MFA-required decisions remain explicitly unavailable until a core verifier validates and consumes action-bound cryptographic evidence; labels and local biometrics are not MFA. Task 10 Phase B1 now owns one versioned ActionResultV2 with separate execution and verification axes, bounded trust-domain evidence, fail-closed redaction and stable digesting, nested compensation truth, durable Memory/SQLite compatibility persistence, executor tuple enforcement, and non-collapsing event, finding, context, telemetry, and relay projections. M4, M6, and claim 19 remain open pending Task 05 producer migration, Task 07 recovery, Tasks 06/09 workflow lab observations, Task 11 browser presentation, and Task 12 certification against the final SHA. Remaining post-RC hardening also includes mobile/relay inbox and push-dedup consumption, broader tenant defaults/inheritance and automation rate budgets, richer dry-run providers, multi-actor UI and MSP delegation/inheritance, device-key/WebAuthn enrollment and verifier integration, additional package-manager and bounded cleanup providers beyond APT, separately governed reboot orchestration, 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. Three policy-authorized verticals are live. Docker/Podman restart is capability-owned low-risk eligible. Agent-managed APT host updates are capability-owned elevated eligible and cross a closed typed host_update protocol with no command, package-selection, removal, or reboot authority; the agent owns metadata refresh, preflight simulation, guarded installation, and post-install simulation, while the audit records verified, failed, or honestly inconclusive outcomes plus reboot-required state. Agent-managed package-cache cleanup is capability-owned low-risk eligible and crosses a separate fingerprint-bound host_storage_cleanup protocol with no command, path, package selector, installed-package removal, or reboot authority; it is available only for meaningful reclaimable bytes on the actual pressured cache filesystem, and the audit verifies the bytes reclaimed. All three require explicit per-resource capability allowlists and optional recurring timezone windows, remain bounded by tenant Patrol mode and full-mode unlock, recheck policy/readiness before decision and dispatch, and record server-owned policy approval plus terminal verification in the same audit trail. Never-auto-remediate, missing/unknown policy, unsupported capabilities, stale/error/empty package or cleanup inventories, cleared storage pressure, dry-run/MFA floors, closed windows, and mode downgrades all fail closed. Action continuity is audit-authoritative and now has a Phase B1 durable transport foundation: execution admission atomically creates the deterministic dispatch attempt/outbox, a one-shot pre-send CAS prevents concurrent duplicate sends, expired pre-send claims safely requeue, post-send uncertainty remains receipt-pending for query-only reconciliation, explicit expiry is durable, and canonical detail plus pending/settled reads are tenant-scoped. Generic transport errors cannot fabricate receipts or terminal truth, legacy executing rows without attempts remain inert, 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. Task 08 Phase B1 also makes requester and decision authority server-owned, binds actor and approval requirement into plan identity, rechecks current tenant/RBAC/token scope, and records multi-actor approvals through revision-CAS append-only decision facts plus atomic lifecycle transitions. MFA-required decisions remain explicitly unavailable until a core verifier validates and consumes action-bound cryptographic evidence; labels and local biometrics are not MFA. Task 08 Phase B2 now makes Patrol Autopilot acknowledgement and activation server-owned: immutable human actor, credential, organization, current version, accepted limits, timestamps, and digest are persisted as append-only config evidence; effective full mode requires the exact current activation and falls back safely for legacy booleans, stale, revoked, expired, malformed, API-token, or cross-tenant evidence. This backend prerequisite does not close M7; Task 11 still owns explicit acknowledgement UX and browser/device proof, and Task 12 owns final certification. Task 10 Phase B1 now owns one versioned ActionResultV2 with separate execution and verification axes, bounded trust-domain evidence, fail-closed redaction and stable digesting, nested compensation truth, durable Memory/SQLite compatibility persistence, executor tuple enforcement, and non-collapsing event, finding, context, telemetry, and relay projections. M4, M6, and claim 19 remain open pending Task 05 producer migration, Task 07 recovery, Tasks 06/09 workflow lab observations, Task 11 browser presentation, and Task 12 certification against the final SHA. Remaining post-RC hardening also includes mobile/relay inbox and push-dedup consumption, broader tenant defaults/inheritance and automation rate budgets, richer dry-run providers, multi-actor UI and MSP delegation/inheritance, device-key/WebAuthn enrollment and verifier integration, additional package-manager and bounded cleanup providers beyond APT, separately governed reboot orchestration, and a real-lab detect-plan-execute-verify-rollback journey proof.",
"tracking": [
{
"kind": "lane-followup",
@@ -6232,6 +6301,18 @@
"path": "internal/api/patrol_action_reconciliation.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/patrol_autopilot_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/config/patrol_autopilot_persistence_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/hostagent/package_updates.go",
@@ -6291,6 +6372,17 @@
"kind": "file",
"evidence_tier": "test-proof"
},
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/patrol_autopilot.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/patrol_autopilot_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/unifiedresources/resource_operator_state_policy_test.go",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 596279f110..f4354cc6c8 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -4335,3 +4335,14 @@ not a verified postcondition, and an independently verified label is valid only
when the canonical evidence identifies a distinct trust domain. Agent-side
producer migration and UI wording are downstream governed work, not permission
to add an agent-local truth model.
+
+### Autopilot activation is not action approval
+
+The server-owned Patrol Autopilot acknowledgement authorizes only the effective
+tenant Patrol mode. It does not approve an action, weaken capability policy,
+satisfy an MFA floor, manufacture dispatch authority, or alter agent receipt
+and result semantics. Every resulting action still enters the canonical
+Task 08 actor/RBAC/approval boundary, Task 07 dispatch contract, and Task 10
+two-axis result contract. API tokens are ineligible for the human Autopilot
+acknowledgement even where an owner-bound token remains compatible with an
+authenticated action capability.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index ba9c255eb0..c2874d51eb 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -5781,3 +5781,24 @@ Legacy investigation outcome strings remain projections for compatibility and
must be derived from canonical truth rather than reconstructed locally. The
typed disposition retains the serialized canonical two-axis result so the
legacy single outcome is never the sole durable/read-model truth.
+
+### Server-owned Patrol Autopilot activation
+
+Patrol full mode is now an effective server decision, not the stored
+`patrol_full_mode_unlocked` compatibility boolean. The runtime evaluates a
+versioned acknowledgement and activation bound to one human actor credential
+and organization; missing, stale, expired, revoked, malformed, cross-tenant,
+or API-token evidence falls back to approval mode. Acknowledgement creation is
+separate from activation, lower modes clear activation without rewriting
+history, and version rotation or revocation takes effect before new Patrol
+admission through the existing Task 04 policy-mutation coordinator. The API
+handler and every tenant AI service share the same injected server clock and
+current-version provider, so a newly supported contract cannot activate at the
+API boundary while remaining stale in the runtime that enforces Patrol mode.
+
+The accepted limits promise only policy allowlisting, emergency-stop and
+approval-floor enforcement, reconciliation when supported, disclosed evidence
+class, and honest inconclusive outcomes. They do not promise independent
+verification, and execution success remains separate from outcome truth.
+Task 11 still owns the explicit acknowledgement UX and browser/device proof;
+Task 12 still owns final certification.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 4cc4b34a89..0fc9155f05 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7407,3 +7407,22 @@ enums. Malformed stored V2 fails closed across events, context, findings,
telemetry, dispositions, and relay wording. Producer migration remains Task 05;
receipt/verification-attempt recovery remains Task 07; browser presentation
remains Task 11; final-SHA certification remains Task 12.
+
+### Patrol Autopilot acknowledgement API
+
+`POST /api/ai/patrol/autonomy/acknowledgements` creates immutable
+server-stamped acknowledgement evidence and
+`DELETE /api/ai/patrol/autonomy/acknowledgements/{id}` appends an exact,
+actor-and-reason-bound revocation. Public JSON may supply only the
+acknowledgement idempotency ID or revocation reason; actor, credential,
+organization, version, scope, limits, timestamps, and digest are server-owned,
+and API tokens cannot acknowledge or activate human Autopilot consent.
+
+`PUT /api/ai/patrol/autonomy` requires an eligible acknowledgement ID for full
+mode and commits requested mode plus activation atomically. A bare legacy
+`full_mode_unlocked: true` is compatibility data and cannot authorize. `GET`
+returns requested mode, server-owned effective mode, derived compatibility
+boolean, the current expected versioned contract, and the selected record's
+version/status metadata without rewriting historical evidence. Stable failure codes distinguish
+missing, stale, wrong-organization, wrong-actor, expired, revoked, malformed,
+conflicting, and unavailable-store evidence.
diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md
index 66508d1c8b..a32b067ecf 100644
--- a/docs/release-control/v6/internal/subsystems/organization-settings.md
+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md
@@ -349,3 +349,11 @@ supports quorum/separation semantics with durable decision CAS, but it does not
claim provider/MSP delegation, provider inheritance, tenant policy-default UI,
distributed budgets, or multi-actor UI; those remain governed L20 residuals
rather than organization-settings-local policy models.
+
+Patrol Autopilot acknowledgement is tenant-bound backend authority, not an
+organization-settings-local consent flag. The persisted actor organization,
+activation organization, and evaluated request organization must match; a
+self-digesting foreign revocation or activation cannot be attributed to or
+activate the victim tenant. Each tenant's atomic AI config owns its history,
+while provider/MSP inheritance, delegated acknowledgement, tenant-default UI,
+and multi-actor administration remain explicit residual product work.
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 306cf9dc82..e26126a354 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -1974,3 +1974,13 @@ verified; contradicted verification maps to verification failure; and
not-attempted or inconclusive verification remains verification unknown. A
successful execution never overwrites contradictory verification. Task 11
still owns browser wording and proof for the distinct terminal states.
+
+Patrol now consumes the server-derived effective Autopilot mode. Requested
+`full` is admitted only with a current persisted human acknowledgement and
+exact activation for the same actor credential and organization; legacy
+booleans, revocation, expiry, version rotation, and malformed evidence fall
+back to approval mode before policy-authorized action submission. The accepted
+limits explicitly allow inconclusive verification and never turn execution
+success into outcome truth. Task 11 still owns acknowledgement presentation,
+cancel/no-submit browser proof, and device coverage; M7 remains open until that
+work and Task 12 certification are complete.
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 06c0de9205..0aa6a592d7 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -1875,3 +1875,17 @@ lookup, polling loop, provider call, or evidence fetch. Canonical evidence and
reference counts, text, and identity fields remain bounded by the
unified-resource-owned `ActionResultV2` contract, so event publication cannot
turn terminal action evidence into an unbounded payload or hot-path query.
+
+### Patrol Autopilot config mutation cost and serialization
+
+Acknowledgement creation, revocation, and activation reuse the Task 04
+in-process policy-mutation coordinator and perform one load, pure validation,
+and atomic `SaveAIConfig` replacement. Existing acknowledgement and revocation
+history is compared as an exact immutable prefix, so stale writers cannot
+replace prior authority facts. Activation and requested mode are committed in
+the same write; runtime publication occurs before releasing the same mutation
+boundary. Exact retries do not append evidence or rewrite timestamps.
+
+This is a per-tenant, single-process serialized config boundary, not a claim of
+distributed multi-writer CAS. Provider-wide inheritance, distributed budgets,
+and cross-process policy mutation remain outside this backend prerequisite.
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 8e3400bf21..d9e7b37905 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -1527,11 +1527,12 @@
"frontend-modern/src/utils/aiCostPresentation.ts",
"frontend-modern/src/utils/aiProviderHealthPresentation.ts",
"frontend-modern/src/utils/aiProviderPresentation.ts",
- "internal/api/ai_handler.go",
- "internal/api/ai_handlers.go",
- "internal/api/ai_intelligence_handlers.go",
- "internal/config/ai.go",
- "pkg/aicontracts/action_broker.go",
+ "internal/api/ai_handler.go",
+ "internal/api/ai_handlers.go",
+ "internal/api/ai_intelligence_handlers.go",
+ "internal/config/ai.go",
+ "internal/config/patrol_autopilot_persistence.go",
+ "pkg/aicontracts/action_broker.go",
"pkg/aicontracts/fix_execution.go",
"pkg/aicontracts/investigation.go",
"pkg/aicontracts/orchestrator_deps.go",
@@ -1611,7 +1612,8 @@
"exact_files": [
"internal/api/ai_handler_test.go",
"internal/api/ai_handlers_test.go",
- "internal/api/ai_intelligence_handlers_test.go"
+ "internal/api/ai_intelligence_handlers_test.go",
+ "internal/api/patrol_autopilot_test.go"
]
},
{
@@ -1771,12 +1773,14 @@
"label": "AI runtime config proof",
"match_prefixes": [],
"match_files": [
- "internal/config/ai.go"
+ "internal/config/ai.go",
+ "internal/config/patrol_autopilot_persistence.go"
],
"allow_same_subsystem_tests": false,
"test_prefixes": [],
"exact_files": [
- "internal/config/ai_config_test.go"
+ "internal/config/ai_config_test.go",
+ "internal/config/patrol_autopilot_persistence_test.go"
]
},
{
@@ -2412,7 +2416,8 @@
],
"exact_files": [
"frontend-modern/src/types/api.ts",
- "internal/api/contract_test.go"
+ "internal/api/contract_test.go",
+ "internal/api/patrol_autopilot_test.go"
]
},
{
@@ -6561,6 +6566,19 @@
"internal/unifiedresources/store_test.go"
]
},
+ {
+ "id": "patrol-autopilot-runtime",
+ "label": "Patrol Autopilot authority runtime proof",
+ "match_prefixes": [],
+ "match_files": [
+ "internal/unifiedresources/patrol_autopilot.go"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "internal/unifiedresources/patrol_autopilot_test.go"
+ ]
+ },
{
"id": "unified-resource-runtime-support",
"label": "unified resource runtime support proof",
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index f3a8915f1a..b35d088d06 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1338,3 +1338,18 @@ secret-bearing text do not enter `ActionResultV2` projections. Stable bounded
refusal reason codes such as `resource_remediation_locked:` and `plan_drift:`
may remain visible so authorized consumers can branch without receiving raw
provider output.
+
+### Patrol Autopilot acknowledgement authority
+
+Autopilot acknowledgement and activation stamp the authenticated human session
+as an immutable `ActionActor` binding with organization and credential. Public
+actor, organization, version, scope, limits, time, and digest fields are
+rejected; owner-bound and detached API tokens are both ineligible. Cross-org,
+wrong-credential, tampered, stale, expired, revoked, or conflicting evidence
+fails closed and cannot change effective full mode. The legacy unlock boolean
+is retained only for wire/storage compatibility and is never treated as user
+acknowledgement.
+
+This is not an MFA implementation. No acknowledgement label or local browser
+state may satisfy an action MFA floor without the existing server-verified,
+action-bound cryptographic step-up contract.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 8f9d3098e7..ec70746814 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -2032,6 +2032,24 @@ while storage detail drawers and filter controls must route summary series IDs,
source tones, and disk metrics through the shared storage helpers instead of
reconstructing them from local table state.
+### Patrol Autopilot config recovery
+
+The tenant AI config is the durable owner for immutable Patrol Autopilot
+acknowledgements and revocations plus the current activation. Every initial
+save and rewrite invokes the shared unified-resource validator before mutation,
+then enforces exact immutable history prefixes. Requested full mode and its
+activation are committed through one atomic config-file replacement. Reopen derives
+effective mode from current evidence, so a legacy boolean, stale version,
+revocation, malformed binding, or failed write recovers below full without
+deleting historical evidence. Separate tenant config files may reuse a client
+idempotency ID without sharing authority records.
+
+Version rotation never reinterprets old history through today's scope or
+limits. Each historical record remains valid against its own static registry
+entry, while activation requires a newly issued acknowledgement ID under the
+current supported version. Valid V1 bytes therefore survive V2 issuance,
+activation, reopen, and unrelated later config saves unchanged.
+
Storage and recovery consumers of action events and resource history inherit
the unified-resource-owned `ActionResultV2`. They must preserve execution,
verification, evidence class, and nested compensation independently and must
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 1df046bead..8134fc48d6 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1688,6 +1688,24 @@ through the canonical resource model, but unified-resource consumers must not
reintroduce removed workload aliases or feature-local resource-type shims just
to satisfy one table, drawer, or badge surface.
+### Patrol Autopilot authority evidence
+
+`internal/unifiedresources/patrol_autopilot.go` owns the versioned immutable
+acknowledgement, revocation, activation, accepted-scope/limits, digest, status,
+and evaluation contracts. A static server-owned registry binds every supported
+acknowledgement version to its exact immutable scope, limits, and optional
+lifetime; the current version provider is separate from that historical
+registry. One pure stored-evidence validator checks each record against its own
+registered version, canonical IDs, human actor and organization binding,
+coherent times, digests, activation binding, and unique same-acknowledgement
+revocation before any config mutation. Runtime evaluation uses the current
+registry entry and fails closed; a malformed foreign revocation cannot become
+a valid revocation attributed to the victim organization.
+
+This authority evidence does not replace the governed action lifecycle,
+approval strength, dispatch continuity, or `ActionResultV2`. It only controls
+whether requested Patrol full mode is effective.
+
### Canonical action-result truth
`internal/unifiedresources/action_result_v2.go` is the sole schema authority
diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.go
index b81081b87a..3cc62eb675 100644
--- a/internal/ai/patrol_ai.go
+++ b/internal/ai/patrol_ai.go
@@ -1037,11 +1037,6 @@ func (p *PatrolService) getPatrolSystemPrompt() string {
autonomyLevel := config.PatrolAutonomyMonitor
if p != nil && p.aiService != nil {
autonomyLevel = p.aiService.GetEffectivePatrolAutonomyLevel()
- if cfg := p.aiService.GetConfig(); cfg != nil &&
- autonomyLevel == config.PatrolAutonomyFull &&
- !cfg.PatrolFullModeUnlocked {
- autonomyLevel = config.PatrolAutonomyAssisted
- }
}
basePrompt := `You are Pulse Patrol, an autonomous infrastructure analysis agent. Your job is to find issues that simple threshold-based alerts CANNOT catch — trends, capacity risks, misconfigurations, reliability gaps, and cross-resource correlations.
diff --git a/internal/ai/patrol_ai_more_test.go b/internal/ai/patrol_ai_more_test.go
index 53584599dd..995e95ab90 100644
--- a/internal/ai/patrol_ai_more_test.go
+++ b/internal/ai/patrol_ai_more_test.go
@@ -21,6 +21,40 @@ import (
type noExecutorChatService struct{}
+func TestServicePatrolAutopilotPolicyProviderControlsRuntimeVersion(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ actor := unifiedresources.ActionActor{SubjectID: "admin-one", Kind: unifiedresources.ActionActorUser, CredentialID: "session:one", OrgID: "org-a"}
+ v1Policy := unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: unifiedresources.PatrolAutopilotAcknowledgementVersionV1, Now: now}
+ v1, _, err := unifiedresources.IssuePatrolAutopilotAcknowledgement(nil, "ack-runtime-v1", actor, v1Policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ v2Policy := unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: unifiedresources.PatrolAutopilotAcknowledgementVersionV2, Now: now.Add(time.Hour)}
+ v2, _, err := unifiedresources.IssuePatrolAutopilotAcknowledgement([]unifiedresources.PatrolAutopilotAcknowledgement{v1}, "ack-runtime-v2", actor, v2Policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ activation, _, err := unifiedresources.BindPatrolAutopilotActivation([]unifiedresources.PatrolAutopilotAcknowledgement{v1, v2}, nil, nil, v2.ID, actor, v2Policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ svc := NewService(nil, nil)
+ svc.SetOrgID("org-a")
+ svc.cfg = config.NewDefaultAIConfig()
+ svc.cfg.PatrolAutonomyLevel = config.PatrolAutonomyFull
+ svc.cfg.PatrolAutopilotAcknowledgements = []unifiedresources.PatrolAutopilotAcknowledgement{v1, v2}
+ svc.cfg.PatrolAutopilotActivation = &activation
+ svc.SetPatrolAutopilotServerPolicyProvider(func() unifiedresources.PatrolAutopilotServerPolicy { return v2Policy })
+ if effective := svc.GetEffectivePatrolAutonomyLevel(); effective != config.PatrolAutonomyFull {
+ t.Fatalf("V2 runtime activation effective=%q", effective)
+ }
+ svc.SetPatrolAutopilotServerPolicyProvider(func() unifiedresources.PatrolAutopilotServerPolicy { return v1Policy })
+ if effective := svc.GetEffectivePatrolAutonomyLevel(); effective != config.PatrolAutonomyApproval {
+ t.Fatalf("runtime did not fail closed after current-version change: effective=%q", effective)
+ }
+}
+
func (n *noExecutorChatService) CreateSession(ctx context.Context) (*ChatSession, error) {
return &ChatSession{ID: "noop"}, nil
}
@@ -170,6 +204,25 @@ func TestComputePatrolMaxTurns(t *testing.T) {
}
func TestGetPatrolSystemPrompt_ModeSwitch(t *testing.T) {
+ fullModeConfig := func() *config.AIConfig {
+ now := time.Now().UTC()
+ policy := unifiedresources.CurrentPatrolAutopilotServerPolicy(now)
+ actor := unifiedresources.ActionActor{SubjectID: "admin", Kind: unifiedresources.ActionActorUser, CredentialID: "session:test", OrgID: "default"}
+ acknowledgement, _, err := unifiedresources.IssuePatrolAutopilotAcknowledgement(nil, "ack-prompt-full", actor, policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ activation, _, err := unifiedresources.BindPatrolAutopilotActivation([]unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}, nil, nil, acknowledgement.ID, actor, policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &config.AIConfig{
+ PatrolAutonomyLevel: config.PatrolAutonomyFull,
+ PatrolFullModeUnlocked: true,
+ PatrolAutopilotAcknowledgements: []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement},
+ PatrolAutopilotActivation: &activation,
+ }
+ }
tests := []struct {
name string
cfg *config.AIConfig
@@ -204,10 +257,7 @@ func TestGetPatrolSystemPrompt_ModeSwitch(t *testing.T) {
},
{
name: "full",
- cfg: &config.AIConfig{
- PatrolAutonomyLevel: config.PatrolAutonomyFull,
- PatrolFullModeUnlocked: true,
- },
+ cfg: fullModeConfig(),
contains: []string{
"Patrol Control Mode: Autopilot",
"execute policy-approved fixes automatically, including critical fixes",
@@ -215,13 +265,13 @@ func TestGetPatrolSystemPrompt_ModeSwitch(t *testing.T) {
},
},
{
- name: "locked full downgrades to assisted",
+ name: "locked full downgrades to ask first",
cfg: &config.AIConfig{
PatrolAutonomyLevel: config.PatrolAutonomyFull,
PatrolFullModeUnlocked: false,
},
contains: []string{
- "Patrol Control Mode: Safe Auto-Fix",
+ "Patrol Control Mode: Ask First",
},
notContain: []string{
"Patrol Control Mode: Autopilot",
@@ -244,7 +294,7 @@ func TestGetPatrolSystemPrompt_ModeSwitch(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- svc := &Service{cfg: tt.cfg}
+ svc := &Service{cfg: tt.cfg, orgID: "default"}
ps := NewPatrolService(svc, nil)
prompt := ps.getPatrolSystemPrompt()
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 41797f65ad..d1c4db6a3d 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -240,6 +240,7 @@ type Service struct {
unifiedResourceProvider UnifiedResourceProvider
resourceExportStore unifiedresources.ResourceStore
resourceExportStoreOrgID string
+ patrolAutopilotPolicy func() unifiedresources.PatrolAutopilotServerPolicy
patrolService *PatrolService // Background AI monitoring service
metadataProvider MetadataProvider // Enables AI to update resource URLs
incidentStore *memory.IncidentStore // Alert-scoped investigation memory; not the canonical durable resource history
@@ -1013,7 +1014,63 @@ func (s *Service) GetEffectivePatrolAutonomyLevel() string {
if !s.HasLicenseFeature(FeatureAIAutoFix) {
return config.PatrolAutonomyMonitor
}
- return cfg.GetPatrolAutonomyLevel()
+ s.mu.RLock()
+ orgID := s.orgID
+ policyProvider := s.patrolAutopilotPolicy
+ s.mu.RUnlock()
+ policy := unifiedresources.CurrentPatrolAutopilotServerPolicy(time.Now().UTC())
+ if policyProvider != nil {
+ policy = policyProvider()
+ }
+ level, _ := cfg.GetEffectivePatrolAutonomyWithPolicy(orgID, policy)
+ return level
+}
+
+// SetPatrolAutopilotServerPolicyProvider keeps runtime admission on the same
+// server-owned clock and current-version source as the API boundary.
+func (s *Service) SetPatrolAutopilotServerPolicyProvider(provider func() unifiedresources.PatrolAutopilotServerPolicy) {
+ if s == nil {
+ return
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.patrolAutopilotPolicy = provider
+}
+
+// ApplyPatrolAutonomyConfig publishes an already-persisted autonomy mutation
+// without rebuilding provider clients. Callers must persist first and invoke
+// this while holding the policy-mutation coordinator so revocation and runtime
+// admission observe one ordered boundary.
+func (s *Service) ApplyPatrolAutonomyConfig(cfg *config.AIConfig) error {
+ if s == nil || cfg == nil {
+ return fmt.Errorf("Pulse Patrol config is unavailable")
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.cfg == nil {
+ s.cfg = config.NewDefaultAIConfig()
+ }
+ s.cfg.PatrolAutonomyLevel = cfg.PatrolAutonomyLevel
+ s.cfg.PatrolFullModeUnlocked = cfg.PatrolFullModeUnlocked
+ s.cfg.PatrolInvestigationBudget = cfg.PatrolInvestigationBudget
+ s.cfg.PatrolInvestigationTimeoutSec = cfg.PatrolInvestigationTimeoutSec
+ s.cfg.PatrolAutopilotAcknowledgements = clonePatrolAutopilotAcknowledgements(cfg.PatrolAutopilotAcknowledgements)
+ s.cfg.PatrolAutopilotRevocations = append([]unifiedresources.PatrolAutopilotRevocation(nil), cfg.PatrolAutopilotRevocations...)
+ if cfg.PatrolAutopilotActivation == nil {
+ s.cfg.PatrolAutopilotActivation = nil
+ } else {
+ activation := *cfg.PatrolAutopilotActivation
+ s.cfg.PatrolAutopilotActivation = &activation
+ }
+ return nil
+}
+
+func clonePatrolAutopilotAcknowledgements(records []unifiedresources.PatrolAutopilotAcknowledgement) []unifiedresources.PatrolAutopilotAcknowledgement {
+ cloned := append([]unifiedresources.PatrolAutopilotAcknowledgement(nil), records...)
+ for index := range cloned {
+ cloned[index].AcceptedScope = append([]string(nil), cloned[index].AcceptedScope...)
+ }
+ return cloned
}
func (s *Service) getEffectivePatrolInterval(cfg *config.AIConfig) time.Duration {
@@ -1841,6 +1898,12 @@ func (s *Service) GetConfig() *config.AIConfig {
return nil
}
cfg := *s.cfg
+ cfg.PatrolAutopilotAcknowledgements = clonePatrolAutopilotAcknowledgements(s.cfg.PatrolAutopilotAcknowledgements)
+ cfg.PatrolAutopilotRevocations = append([]unifiedresources.PatrolAutopilotRevocation(nil), s.cfg.PatrolAutopilotRevocations...)
+ if s.cfg.PatrolAutopilotActivation != nil {
+ activation := *s.cfg.PatrolAutopilotActivation
+ cfg.PatrolAutopilotActivation = &activation
+ }
return &cfg
}
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index ca72946aa2..734e2587b6 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -1,6 +1,7 @@
package api
import (
+ "bytes"
"context"
"encoding/csv"
"encoding/json"
@@ -66,6 +67,7 @@ type AISettingsHandler struct {
actionBrokerFactory func(orgID string) aicontracts.OrchestratorActionBroker
proposalCatalogFactory func(orgID string) tools.ProposalCatalog
policyMutation func(func() error) error
+ patrolAutopilotPolicy func() unifiedresources.PatrolAutopilotServerPolicy
metadataProvider ai.MetadataProvider
patrolThresholdProvider ai.ThresholdProvider
metricsHistoryProvider ai.MetricsHistoryProvider
@@ -142,6 +144,31 @@ func (h *AISettingsHandler) SetPolicyMutationCoordinator(coordinator func(func()
h.policyMutation = coordinator
}
+func (h *AISettingsHandler) SetPatrolAutopilotServerPolicyProvider(provider func() unifiedresources.PatrolAutopilotServerPolicy) {
+ h.stateMu.Lock()
+ h.patrolAutopilotPolicy = provider
+ defaultService := h.defaultAIService
+ h.stateMu.Unlock()
+ if defaultService != nil {
+ defaultService.SetPatrolAutopilotServerPolicyProvider(provider)
+ }
+ h.aiServicesMu.RLock()
+ defer h.aiServicesMu.RUnlock()
+ for _, service := range h.aiServices {
+ service.SetPatrolAutopilotServerPolicyProvider(provider)
+ }
+}
+
+func (h *AISettingsHandler) currentPatrolAutopilotServerPolicy() unifiedresources.PatrolAutopilotServerPolicy {
+ h.stateMu.RLock()
+ provider := h.patrolAutopilotPolicy
+ h.stateMu.RUnlock()
+ if provider != nil {
+ return provider()
+ }
+ return unifiedresources.CurrentPatrolAutopilotServerPolicy(time.Now().UTC())
+}
+
// SetActionBrokerFactory installs the per-org typed action proposal broker
// used by the investigation orchestrator. Core-owned: it binds the tenant
// and the fixed Patrol actor, so enterprise code can only propose typed
@@ -258,6 +285,10 @@ func (h *AISettingsHandler) providerSnapshot() aiSettingsProviderSnapshot {
func (h *AISettingsHandler) newFailClosedTenantService(orgID string) *ai.Service {
svc := ai.NewService(nil, h.agentServer)
svc.SetOrgID(orgID)
+ h.stateMu.RLock()
+ patrolAutopilotPolicy := h.patrolAutopilotPolicy
+ h.stateMu.RUnlock()
+ svc.SetPatrolAutopilotServerPolicyProvider(patrolAutopilotPolicy)
svc.SetAlertAnalyzerFactory(getCreateAlertAnalyzer())
svc.SetLicenseChecker(failClosedLicenseChecker{})
return svc
@@ -398,6 +429,10 @@ func (h *AISettingsHandler) GetAIService(ctx context.Context) *ai.Service {
svc = ai.NewService(persistence, h.agentServer)
svc.SetOrgID(orgID)
+ h.stateMu.RLock()
+ patrolAutopilotPolicy := h.patrolAutopilotPolicy
+ h.stateMu.RUnlock()
+ svc.SetPatrolAutopilotServerPolicyProvider(patrolAutopilotPolicy)
svc.SetAlertAnalyzerFactory(getCreateAlertAnalyzer())
if _, err := h.loadAIConfigForPersistence(context.Background(), orgID, persistence); err != nil {
log.Warn().Str("orgID", orgID).Err(err).Msg("Failed to bootstrap Pulse Assistant config for tenant")
@@ -7551,22 +7586,140 @@ func truncateForLog(s string, maxLen int) string {
return s[:maxLen] + "..."
}
-// PatrolAutonomySettings represents the patrol autonomy configuration for API requests
-// Uses pointer for FullModeUnlocked to distinguish "not sent" from "sent as false"
+// PatrolAutonomySettings represents the patrol autonomy configuration for API requests.
+// FullModeUnlocked is a legacy compatibility field only; it is never acknowledgement authority.
type PatrolAutonomySettings struct {
AutonomyLevel string `json:"autonomy_level"` // "monitor", "approval", "assisted", "full"
- FullModeUnlocked *bool `json:"full_mode_unlocked,omitempty"` // User has acknowledged Full mode risks (nil = preserve existing)
- InvestigationBudget int `json:"investigation_budget"` // Max turns per investigation (5-30)
- InvestigationTimeoutSec int `json:"investigation_timeout_sec"` // Max seconds per investigation (60-1800)
+ FullModeUnlocked *bool `json:"full_mode_unlocked,omitempty"` // Deprecated compatibility label (nil = preserve existing)
+ AcknowledgementID string `json:"acknowledgement_id,omitempty"`
+ InvestigationBudget int `json:"investigation_budget"` // Max turns per investigation (5-30)
+ InvestigationTimeoutSec int `json:"investigation_timeout_sec"` // Max seconds per investigation (60-1800)
}
// PatrolAutonomyResponse represents the patrol autonomy configuration for API responses
// Uses plain bool for FullModeUnlocked since responses always include the actual value
type PatrolAutonomyResponse struct {
- AutonomyLevel string `json:"autonomy_level"`
- FullModeUnlocked bool `json:"full_mode_unlocked"`
- InvestigationBudget int `json:"investigation_budget"`
- InvestigationTimeoutSec int `json:"investigation_timeout_sec"`
+ AutonomyLevel string `json:"autonomy_level"`
+ RequestedAutonomyLevel string `json:"requested_autonomy_level"`
+ EffectiveAutonomyLevel string `json:"effective_autonomy_level"`
+ FullModeUnlocked bool `json:"full_mode_unlocked"`
+ AutopilotStatus unifiedresources.PatrolAutopilotStatus `json:"autopilot_acknowledgement"`
+ InvestigationBudget int `json:"investigation_budget"`
+ InvestigationTimeoutSec int `json:"investigation_timeout_sec"`
+}
+
+type patrolAutopilotAcknowledgementRequest struct {
+ AcknowledgementID string `json:"acknowledgement_id"`
+}
+
+type patrolAutopilotRevocationRequest struct {
+ Reason string `json:"reason,omitempty"`
+}
+
+type patrolAutopilotActivationRequest struct {
+ AcknowledgementID string
+ Actor unifiedresources.ActionActor
+}
+
+type patrolAutopilotActivationContextKey struct{}
+
+func patrolAutopilotActivationFromContext(ctx context.Context) (patrolAutopilotActivationRequest, bool) {
+ request, ok := ctx.Value(patrolAutopilotActivationContextKey{}).(patrolAutopilotActivationRequest)
+ return request, ok
+}
+
+func decodeStrictPatrolAutopilotJSONBody(w http.ResponseWriter, r *http.Request, target any, maxBytes int64) error {
+ r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
+ data, err := io.ReadAll(r.Body)
+ if err != nil {
+ return err
+ }
+ return decodeStrictPatrolAutopilotJSONBytes(data, target)
+}
+
+func decodeStrictPatrolAutopilotJSONBytes(data []byte, target any) error {
+ decoder := json.NewDecoder(bytes.NewReader(data))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(target); err != nil {
+ return err
+ }
+ if err := decoder.Decode(&struct{}{}); err != io.EOF {
+ if err == nil {
+ return fmt.Errorf("multiple JSON values are not allowed")
+ }
+ return err
+ }
+ return nil
+}
+
+func cloneAIConfigForPatrolAutopilot(cfg *config.AIConfig) (*config.AIConfig, error) {
+ if cfg == nil {
+ return nil, fmt.Errorf("Pulse Patrol config not configured")
+ }
+ data, err := json.Marshal(cfg)
+ if err != nil {
+ return nil, err
+ }
+ var cloned config.AIConfig
+ if err := json.Unmarshal(data, &cloned); err != nil {
+ return nil, err
+ }
+ return &cloned, nil
+}
+
+func (h *AISettingsHandler) mutatePatrolAutopilotConfig(ctx context.Context, mutate func(*config.AIConfig, unifiedresources.PatrolAutopilotServerPolicy) (bool, error)) error {
+ if h == nil {
+ return fmt.Errorf("Pulse Patrol service not available")
+ }
+ persistence := h.getPersistence(ctx)
+ service := h.GetAIService(ctx)
+ if persistence == nil || service == nil {
+ return fmt.Errorf("Pulse Patrol config persistence unavailable")
+ }
+ write := func() error {
+ current, err := h.loadAIConfig(ctx)
+ if err != nil {
+ return err
+ }
+ next, err := cloneAIConfigForPatrolAutopilot(current)
+ if err != nil {
+ return err
+ }
+ changed, err := mutate(next, h.currentPatrolAutopilotServerPolicy())
+ if err != nil || !changed {
+ return err
+ }
+ if err := persistence.SaveAIConfig(*next); err != nil {
+ return err
+ }
+ return service.ApplyPatrolAutonomyConfig(next)
+ }
+ h.stateMu.RLock()
+ coordinator := h.policyMutation
+ h.stateMu.RUnlock()
+ if coordinator != nil {
+ return coordinator(write)
+ }
+ return write()
+}
+
+func patrolAutonomyResponseForConfig(cfg *config.AIConfig, orgID string, policy unifiedresources.PatrolAutopilotServerPolicy, hasAutoFix bool) PatrolAutonomyResponse {
+ requested := cfg.GetPatrolAutonomyLevel()
+ effective, status := cfg.GetEffectivePatrolAutonomyWithPolicy(orgID, policy)
+ if !hasAutoFix {
+ effective = config.PatrolAutonomyMonitor
+ status.Active = false
+ status.Code = unifiedresources.PatrolAutopilotStatusLicenseRequired
+ }
+ return PatrolAutonomyResponse{
+ AutonomyLevel: effective,
+ RequestedAutonomyLevel: requested,
+ EffectiveAutonomyLevel: effective,
+ FullModeUnlocked: effective == config.PatrolAutonomyFull && status.Active,
+ AutopilotStatus: status,
+ InvestigationBudget: cfg.GetPatrolInvestigationBudget(),
+ InvestigationTimeoutSec: int(cfg.GetPatrolInvestigationTimeout().Seconds()),
+ }
}
// HandleGetPatrolAutonomy returns the current patrol autonomy settings (GET /api/ai/patrol/autonomy)
@@ -7587,28 +7740,190 @@ func (h *AISettingsHandler) HandleGetPatrolAutonomy(w http.ResponseWriter, r *ht
return
}
- autonomyLevel := cfg.GetPatrolAutonomyLevel()
- fullModeUnlocked := cfg.PatrolFullModeUnlocked
- // Community tier lock: without ai_autofix, patrol autonomy is findings-only ("monitor").
- // If config contains a higher level from a previous Pro/trial period, clamp the effective
- // value at read time so the UI reflects runtime enforcement.
hasAutoFix := aiService.HasLicenseFeature(featureAIAutoFixValue)
- if !hasAutoFix && autonomyLevel != config.PatrolAutonomyMonitor {
- autonomyLevel = config.PatrolAutonomyMonitor
+ settings := patrolAutonomyResponseForConfig(cfg, GetOrgID(r.Context()), h.currentPatrolAutopilotServerPolicy(), hasAutoFix)
+
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(settings)
+}
+
+func (h *AISettingsHandler) HandleCreatePatrolAutopilotAcknowledgement(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
}
- if !hasAutoFix {
- fullModeUnlocked = false
+ var request patrolAutopilotAcknowledgementRequest
+ if err := decodeStrictPatrolAutopilotJSONBody(w, r, &request, 16*1024); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid acknowledgement request", nil)
+ return
}
-
- settings := PatrolAutonomyResponse{
- AutonomyLevel: autonomyLevel,
- FullModeUnlocked: fullModeUnlocked,
- InvestigationBudget: cfg.GetPatrolInvestigationBudget(),
- InvestigationTimeoutSec: int(cfg.GetPatrolInvestigationTimeout().Seconds()),
+ orgID := strings.TrimSpace(GetOrgID(r.Context()))
+ if orgID == "" {
+ orgID = "default"
+ }
+ actor, err := actionActorForRequest(h.defaultConfig, r, orgID)
+ if err != nil || actor.Kind != unifiedresources.ActionActorUser {
+ writeErrorResponse(w, http.StatusForbidden, unifiedresources.PatrolAutopilotStatusUserRequired, "Autopilot acknowledgement requires an authenticated human session", nil)
+ return
+ }
+ var acknowledgement unifiedresources.PatrolAutopilotAcknowledgement
+ created := false
+ err = h.mutatePatrolAutopilotConfig(r.Context(), func(cfg *config.AIConfig, policy unifiedresources.PatrolAutopilotServerPolicy) (bool, error) {
+ var issueErr error
+ acknowledgement, created, issueErr = unifiedresources.IssuePatrolAutopilotAcknowledgement(cfg.PatrolAutopilotAcknowledgements, request.AcknowledgementID, actor, policy)
+ if issueErr != nil || !created {
+ return false, issueErr
+ }
+ cfg.PatrolAutopilotAcknowledgements = append(cfg.PatrolAutopilotAcknowledgements, acknowledgement)
+ return true, nil
+ })
+ if err != nil {
+ code := unifiedresources.PatrolAutopilotErrorCode(err)
+ if code == "" {
+ code = unifiedresources.PatrolAutopilotStatusStoreUnavailable
+ }
+ status := http.StatusConflict
+ if code == unifiedresources.PatrolAutopilotStatusStoreUnavailable {
+ status = http.StatusServiceUnavailable
+ }
+ writeErrorResponse(w, status, code, "Autopilot acknowledgement was not recorded", nil)
+ return
}
+ _, acknowledgementStatus := unifiedresources.ValidatePatrolAutopilotAcknowledgement(
+ []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}, nil, acknowledgement.ID, orgID, &actor, h.currentPatrolAutopilotServerPolicy(),
+ )
+ statusCode := http.StatusOK
+ if created {
+ statusCode = http.StatusCreated
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(statusCode)
+ _ = json.NewEncoder(w).Encode(map[string]any{"created": created, "acknowledgement": acknowledgementStatus})
+}
+func (h *AISettingsHandler) HandleRevokePatrolAutopilotAcknowledgement(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodDelete {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ acknowledgementID := strings.TrimSpace(strings.TrimPrefix(r.URL.Path, "/api/ai/patrol/autonomy/acknowledgements/"))
+ if acknowledgementID == "" || strings.Contains(acknowledgementID, "/") {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Acknowledgement id is required", nil)
+ return
+ }
+ var request patrolAutopilotRevocationRequest
+ r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid revocation request", nil)
+ return
+ }
+ if len(bytes.TrimSpace(body)) > 0 {
+ if err := decodeStrictPatrolAutopilotJSONBytes(body, &request); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid revocation request", nil)
+ return
+ }
+ }
+ orgID := strings.TrimSpace(GetOrgID(r.Context()))
+ if orgID == "" {
+ orgID = "default"
+ }
+ actor, err := actionActorForRequest(h.defaultConfig, r, orgID)
+ if err != nil || actor.Kind != unifiedresources.ActionActorUser {
+ writeErrorResponse(w, http.StatusForbidden, unifiedresources.PatrolAutopilotStatusUserRequired, "Autopilot revocation requires an authenticated human session", nil)
+ return
+ }
+ created := false
+ err = h.mutatePatrolAutopilotConfig(r.Context(), func(cfg *config.AIConfig, policy unifiedresources.PatrolAutopilotServerPolicy) (bool, error) {
+ revocation, wasCreated, revokeErr := unifiedresources.RevokePatrolAutopilotAcknowledgement(cfg.PatrolAutopilotAcknowledgements, cfg.PatrolAutopilotRevocations, acknowledgementID, actor, request.Reason, policy)
+ if revokeErr != nil || !wasCreated {
+ created = false
+ return false, revokeErr
+ }
+ created = true
+ cfg.PatrolAutopilotRevocations = append(cfg.PatrolAutopilotRevocations, revocation)
+ cfg.PatrolFullModeUnlocked = false
+ return true, nil
+ })
+ if err != nil {
+ code := unifiedresources.PatrolAutopilotErrorCode(err)
+ if code == "" {
+ code = unifiedresources.PatrolAutopilotStatusStoreUnavailable
+ }
+ status := http.StatusConflict
+ if code == unifiedresources.PatrolAutopilotStatusStoreUnavailable {
+ status = http.StatusServiceUnavailable
+ }
+ writeErrorResponse(w, status, code, "Autopilot acknowledgement was not revoked", nil)
+ return
+ }
w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(settings)
+ _ = json.NewEncoder(w).Encode(map[string]any{"revoked": true, "created": created, "acknowledgement_id": acknowledgementID})
+}
+
+func (h *AISettingsHandler) GatePatrolAutonomyUpdate(next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPut {
+ next(w, r)
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid Patrol autonomy request", nil)
+ return
+ }
+ var settings PatrolAutonomySettings
+ if err := decodeStrictPatrolAutopilotJSONBytes(body, &settings); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid Patrol autonomy request", nil)
+ return
+ }
+ settings.AcknowledgementID = strings.TrimSpace(settings.AcknowledgementID)
+ if settings.AutonomyLevel != config.PatrolAutonomyFull {
+ if settings.AcknowledgementID != "" {
+ writeErrorResponse(w, http.StatusConflict, unifiedresources.PatrolAutopilotStatusNotRequested, "Acknowledgement is only valid for an explicit Autopilot activation", nil)
+ return
+ }
+ r.Body = io.NopCloser(bytes.NewReader(body))
+ r.ContentLength = int64(len(body))
+ next(w, r)
+ return
+ }
+ if settings.AcknowledgementID == "" {
+ writeErrorResponse(w, http.StatusConflict, unifiedresources.PatrolAutopilotStatusAcknowledgementRequired, "Autopilot activation requires a current acknowledgement", nil)
+ return
+ }
+ orgID := strings.TrimSpace(GetOrgID(r.Context()))
+ if orgID == "" {
+ orgID = "default"
+ }
+ actor, err := actionActorForRequest(h.defaultConfig, r, orgID)
+ if err != nil || actor.Kind != unifiedresources.ActionActorUser {
+ writeErrorResponse(w, http.StatusForbidden, unifiedresources.PatrolAutopilotStatusUserRequired, "Autopilot activation requires the human session that owns the acknowledgement", nil)
+ return
+ }
+ cfg, err := h.loadAIConfig(r.Context())
+ if err != nil {
+ writeErrorResponse(w, http.StatusServiceUnavailable, unifiedresources.PatrolAutopilotStatusStoreUnavailable, "Autopilot acknowledgement store is unavailable", nil)
+ return
+ }
+ _, status := unifiedresources.ValidatePatrolAutopilotAcknowledgement(cfg.PatrolAutopilotAcknowledgements, cfg.PatrolAutopilotRevocations, settings.AcknowledgementID, orgID, &actor, h.currentPatrolAutopilotServerPolicy())
+ if !status.Active {
+ writeErrorResponse(w, http.StatusConflict, status.Code, "Autopilot acknowledgement is not eligible for activation", nil)
+ return
+ }
+ compatUnlocked := true
+ settings.FullModeUnlocked = &compatUnlocked
+ normalizedBody, err := json.Marshal(settings)
+ if err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "encoding_failed", "Failed to prepare Patrol autonomy request", nil)
+ return
+ }
+ r.Body = io.NopCloser(bytes.NewReader(normalizedBody))
+ r.ContentLength = int64(len(normalizedBody))
+ activationRequest := patrolAutopilotActivationRequest{AcknowledgementID: settings.AcknowledgementID, Actor: actor}
+ next(w, r.WithContext(context.WithValue(r.Context(), patrolAutopilotActivationContextKey{}, activationRequest)))
+ }
}
// HandleUpdatePatrolAutonomyMonitorOnly persists findings-only Patrol autonomy
@@ -7658,46 +7973,20 @@ func (h *AISettingsHandler) HandleUpdatePatrolAutonomyMonitorOnly(w http.Respons
req.InvestigationTimeoutSec = 1800
}
- // This handler is only used when the safe-remediation extension is not active.
- // Do not preserve stale full-mode acknowledgement or permission state through a
- // monitor-only save.
- effectiveUnlocked := false
-
- persistence := h.getPersistence(r.Context())
- if persistence == nil {
- writeErrorResponse(w, http.StatusServiceUnavailable, "not_configured", "Pulse Patrol not configured", nil)
- return
- }
- write := func() error {
- cfg.PatrolAutonomyLevel = config.PatrolAutonomyMonitor
- cfg.PatrolFullModeUnlocked = effectiveUnlocked
- cfg.PatrolInvestigationBudget = req.InvestigationBudget
- cfg.PatrolInvestigationTimeoutSec = req.InvestigationTimeoutSec
- return persistence.SaveAIConfig(*cfg)
- }
- h.stateMu.RLock()
- coordinator := h.policyMutation
- h.stateMu.RUnlock()
- var saveErr error
- if coordinator != nil {
- saveErr = coordinator(write)
- } else {
- saveErr = write()
- }
- if saveErr != nil {
+ if err := h.mutatePatrolAutopilotConfig(r.Context(), func(current *config.AIConfig, _ unifiedresources.PatrolAutopilotServerPolicy) (bool, error) {
+ changed := current.PatrolAutonomyLevel != config.PatrolAutonomyMonitor || current.PatrolFullModeUnlocked || current.PatrolAutopilotActivation != nil ||
+ current.PatrolInvestigationBudget != req.InvestigationBudget || current.PatrolInvestigationTimeoutSec != req.InvestigationTimeoutSec
+ current.PatrolAutonomyLevel = config.PatrolAutonomyMonitor
+ current.PatrolFullModeUnlocked = false
+ current.PatrolAutopilotActivation = nil
+ current.PatrolInvestigationBudget = req.InvestigationBudget
+ current.PatrolInvestigationTimeoutSec = req.InvestigationTimeoutSec
+ return changed, nil
+ }); err != nil {
writeErrorResponse(w, http.StatusInternalServerError, "save_failed", "Failed to save Pulse Patrol autonomy settings", nil)
return
}
- if err := aiService.LoadConfig(); err != nil {
- log.Warn().Err(err).Msg("Patrol autonomy settings saved but config reload failed")
- }
-
- settings := PatrolAutonomyResponse{
- AutonomyLevel: config.PatrolAutonomyMonitor,
- FullModeUnlocked: effectiveUnlocked,
- InvestigationBudget: req.InvestigationBudget,
- InvestigationTimeoutSec: req.InvestigationTimeoutSec,
- }
+ settings := patrolAutonomyResponseForConfig(aiService.GetConfig(), GetOrgID(r.Context()), h.currentPatrolAutopilotServerPolicy(), aiService.HasLicenseFeature(featureAIAutoFixValue))
if err := utils.WriteJSONResponse(w, map[string]interface{}{
"success": true,
"settings": settings,
diff --git a/internal/api/patrol_autopilot_test.go b/internal/api/patrol_autopilot_test.go
new file mode 100644
index 0000000000..d94fb7de41
--- /dev/null
+++ b/internal/api/patrol_autopilot_test.go
@@ -0,0 +1,312 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
+)
+
+func newPatrolAutopilotTestHandler(t *testing.T, orgID string, now *time.Time) (*AISettingsHandler, *config.ConfigPersistence) {
+ t.Helper()
+ dir := t.TempDir()
+ InitSessionStore(dir)
+ persistence := config.NewConfigPersistence(dir)
+ cfg := config.NewDefaultAIConfig()
+ cfg.PatrolAutonomyLevel = config.PatrolAutonomyApproval
+ if err := persistence.SaveAIConfig(*cfg); err != nil {
+ t.Fatal(err)
+ }
+ handler := newTestAISettingsHandler(&config.Config{DataPath: dir}, persistence, nil)
+ if handler.defaultAIService != nil {
+ handler.defaultAIService.SetOrgID(orgID)
+ }
+ handler.SetPatrolAutopilotServerPolicyProvider(func() unifiedresources.PatrolAutopilotServerPolicy {
+ return unifiedresources.CurrentPatrolAutopilotServerPolicy(*now)
+ })
+ var mutationMu sync.Mutex
+ handler.SetPolicyMutationCoordinator(func(write func() error) error {
+ mutationMu.Lock()
+ defer mutationMu.Unlock()
+ return write()
+ })
+ return handler, persistence
+}
+
+func patrolAutopilotSessionRequest(t *testing.T, method, target, body, orgID, username, sessionToken string) *http.Request {
+ t.Helper()
+ GetSessionStore().CreateSession(sessionToken, time.Hour, "browser", "127.0.0.1", username)
+ t.Cleanup(func() { GetSessionStore().DeleteSession(sessionToken) })
+ req := newLoopbackRequest(method, target, strings.NewReader(body))
+ req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: sessionToken})
+ ctx := auth.WithUser(req.Context(), username)
+ ctx = context.WithValue(ctx, OrgIDContextKey, orgID)
+ return req.WithContext(ctx)
+}
+
+func createPatrolAutopilotAcknowledgement(t *testing.T, handler *AISettingsHandler, orgID, username, sessionToken, acknowledgementID string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := patrolAutopilotSessionRequest(t, http.MethodPost, "/api/ai/patrol/autonomy/acknowledgements", fmt.Sprintf(`{"acknowledgement_id":%q}`, acknowledgementID), orgID, username, sessionToken)
+ rec := httptest.NewRecorder()
+ handler.HandleCreatePatrolAutopilotAcknowledgement(rec, req)
+ return rec
+}
+
+func handlePatrolAutonomyUpdateForTest(handler *AISettingsHandler, rec *httptest.ResponseRecorder, req *http.Request) {
+ handler.GatePatrolAutonomyUpdate(func(w http.ResponseWriter, gated *http.Request) {
+ var settings PatrolAutonomySettings
+ if err := json.NewDecoder(gated.Body).Decode(&settings); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "invalid update", nil)
+ return
+ }
+ adapter := &patrolConfigUpdateAdapter{handler: handler, ctx: gated.Context()}
+ unlocked := settings.FullModeUnlocked != nil && *settings.FullModeUnlocked
+ if err := adapter.SaveAutonomySettings(gated.Context(), settings.AutonomyLevel, unlocked, settings.InvestigationBudget, settings.InvestigationTimeoutSec); err != nil {
+ code := unifiedresources.PatrolAutopilotErrorCode(err)
+ if code == "" {
+ code = "save_failed"
+ }
+ writeErrorResponse(w, http.StatusConflict, code, "update failed", nil)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"success": true})
+ })(rec, req)
+}
+
+func TestPatrolAutopilotAcknowledgementAPIStampsServerAuthorityAndRetriesExactly(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ handler, persistence := newPatrolAutopilotTestHandler(t, "org-a", &now)
+ first := createPatrolAutopilotAcknowledgement(t, handler, "org-a", "alice", "session-ack-one", "ack-api-retry-01")
+ if first.Code != http.StatusCreated {
+ t.Fatalf("first acknowledgement status=%d body=%s", first.Code, first.Body.String())
+ }
+ now = now.Add(time.Minute)
+ retry := createPatrolAutopilotAcknowledgement(t, handler, "org-a", "alice", "session-ack-one", "ack-api-retry-01")
+ if retry.Code != http.StatusOK {
+ t.Fatalf("retry status=%d body=%s", retry.Code, retry.Body.String())
+ }
+ conflict := createPatrolAutopilotAcknowledgement(t, handler, "org-a", "bob", "session-ack-two", "ack-api-retry-01")
+ if conflict.Code != http.StatusConflict || !strings.Contains(conflict.Body.String(), unifiedresources.PatrolAutopilotStatusConflict) {
+ t.Fatalf("conflict status=%d body=%s", conflict.Code, conflict.Body.String())
+ }
+ stored, err := persistence.LoadAIConfig()
+ if err != nil || len(stored.PatrolAutopilotAcknowledgements) != 1 {
+ t.Fatalf("stored acknowledgements err=%v config=%#v", err, stored)
+ }
+ if stored.PatrolAutonomyLevel != config.PatrolAutonomyApproval || stored.PatrolAutopilotActivation != nil {
+ t.Fatalf("acknowledgement creation changed mode or activated Autopilot: %#v", stored)
+ }
+ record := stored.PatrolAutopilotAcknowledgements[0]
+ if record.OrgID != "org-a" || record.Actor.SubjectID != "alice" || record.Actor.Kind != unifiedresources.ActionActorUser || record.Actor.CredentialID == "" || !record.AcceptedAt.Equal(time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)) || record.Version != 1 || record.Digest != unifiedresources.PatrolAutopilotAcknowledgementDigest(record) {
+ t.Fatalf("server-owned record=%#v", record)
+ }
+}
+
+func TestPatrolAutopilotAcknowledgementAPIRejectsPublicAuthorityAndAPIToken(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ handler, persistence := newPatrolAutopilotTestHandler(t, "org-a", &now)
+ for _, field := range []string{"actor", "org_id", "accepted_at", "digest", "version", "accepted_scope", "accepted_limits"} {
+ t.Run(field, func(t *testing.T) {
+ body := fmt.Sprintf(`{"acknowledgement_id":"ack-public-%s","%s":"forged"}`, strings.ReplaceAll(field, "_", ""), field)
+ req := patrolAutopilotSessionRequest(t, http.MethodPost, "/api/ai/patrol/autonomy/acknowledgements", body, "org-a", "alice", "session-public-"+field)
+ rec := httptest.NewRecorder()
+ handler.HandleCreatePatrolAutopilotAcknowledgement(rec, req)
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+ })
+ }
+
+ token := &config.APITokenRecord{ID: "token-one", OrgID: "org-a", Scopes: []string{config.ScopeSettingsWrite}, Metadata: map[string]string{apiTokenMetadataOwnerUserID: "alice"}}
+ req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/autonomy/acknowledgements", strings.NewReader(`{"acknowledgement_id":"ack-token-api-01"}`))
+ ctx := auth.WithUser(req.Context(), "alice")
+ ctx = auth.WithAPIToken(ctx, token)
+ ctx = context.WithValue(ctx, OrgIDContextKey, "org-a")
+ rec := httptest.NewRecorder()
+ handler.HandleCreatePatrolAutopilotAcknowledgement(rec, req.WithContext(ctx))
+ if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), unifiedresources.PatrolAutopilotStatusUserRequired) {
+ t.Fatalf("token status=%d body=%s", rec.Code, rec.Body.String())
+ }
+ stored, err := persistence.LoadAIConfig()
+ if err != nil || len(stored.PatrolAutopilotAcknowledgements) != 0 {
+ t.Fatalf("rejected authority fabricated acknowledgement err=%v config=%#v", err, stored)
+ }
+}
+
+func TestPatrolAutopilotActivationRequiresCurrentBoundAcknowledgement(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ handler, persistence := newPatrolAutopilotTestHandler(t, "org-a", &now)
+
+ bare := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", `{"autonomy_level":"full","full_mode_unlocked":true,"investigation_budget":10,"investigation_timeout_sec":120}`, "org-a", "alice", "session-bare")
+ bareRec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, bareRec, bare)
+ if bareRec.Code != http.StatusConflict || !strings.Contains(bareRec.Body.String(), unifiedresources.PatrolAutopilotStatusAcknowledgementRequired) {
+ t.Fatalf("bare full status=%d body=%s", bareRec.Code, bareRec.Body.String())
+ }
+
+ created := createPatrolAutopilotAcknowledgement(t, handler, "org-a", "alice", "session-bound", "ack-activate-001")
+ if created.Code != http.StatusCreated {
+ t.Fatalf("create status=%d body=%s", created.Code, created.Body.String())
+ }
+ activateBody := `{"autonomy_level":"full","acknowledgement_id":"ack-activate-001","investigation_budget":10,"investigation_timeout_sec":120}`
+ activate := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", activateBody, "org-a", "alice", "session-bound")
+ activateRec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, activateRec, activate)
+ if activateRec.Code != http.StatusOK {
+ t.Fatalf("activate status=%d body=%s", activateRec.Code, activateRec.Body.String())
+ }
+ stored, err := persistence.LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ effective, status := stored.GetEffectivePatrolAutonomyWithPolicy("org-a", unifiedresources.CurrentPatrolAutopilotServerPolicy(now))
+ if stored.PatrolAutonomyLevel != config.PatrolAutonomyFull || effective != config.PatrolAutonomyFull || !status.Active || stored.PatrolAutopilotActivation == nil || len(stored.PatrolAutopilotAcknowledgements) != 1 {
+ t.Fatalf("stored activation effective=%q status=%#v config=%#v", effective, status, stored)
+ }
+ getReq := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/autonomy", nil)
+ getReq = getReq.WithContext(context.WithValue(getReq.Context(), OrgIDContextKey, "org-a"))
+ getRec := httptest.NewRecorder()
+ handler.HandleGetPatrolAutonomy(getRec, getReq)
+ var response PatrolAutonomyResponse
+ if getRec.Code != http.StatusOK || json.Unmarshal(getRec.Body.Bytes(), &response) != nil || response.RequestedAutonomyLevel != config.PatrolAutonomyFull || response.EffectiveAutonomyLevel != config.PatrolAutonomyFull || response.AutonomyLevel != config.PatrolAutonomyFull || !response.FullModeUnlocked || !response.AutopilotStatus.Active || response.AutopilotStatus.AcknowledgementID != "ack-activate-001" {
+ t.Fatalf("effective response status=%d body=%s decoded=%#v", getRec.Code, getRec.Body.String(), response)
+ }
+ activatedAt := stored.PatrolAutopilotActivation.ActivatedAt
+
+ now = now.Add(time.Minute)
+ retry := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", activateBody, "org-a", "alice", "session-bound")
+ retryRec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, retryRec, retry)
+ if retryRec.Code != http.StatusOK {
+ t.Fatalf("retry status=%d body=%s", retryRec.Code, retryRec.Body.String())
+ }
+ retried, _ := persistence.LoadAIConfig()
+ if len(retried.PatrolAutopilotAcknowledgements) != 1 || retried.PatrolAutopilotActivation == nil || !retried.PatrolAutopilotActivation.ActivatedAt.Equal(activatedAt) {
+ t.Fatalf("retry fabricated evidence: %#v", retried)
+ }
+
+ wrongCredential := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", activateBody, "org-a", "alice", "session-different")
+ wrongCredentialRec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, wrongCredentialRec, wrongCredential)
+ if wrongCredentialRec.Code != http.StatusConflict || !strings.Contains(wrongCredentialRec.Body.String(), unifiedresources.PatrolAutopilotStatusWrongActor) {
+ t.Fatalf("wrong credential status=%d body=%s", wrongCredentialRec.Code, wrongCredentialRec.Body.String())
+ }
+}
+
+func TestPatrolAutopilotLowerModeDoesNotCreateOrRefreshAcknowledgement(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ handler, persistence := newPatrolAutopilotTestHandler(t, "org-a", &now)
+ if rec := createPatrolAutopilotAcknowledgement(t, handler, "org-a", "alice", "session-lower", "ack-lower-0001"); rec.Code != http.StatusCreated {
+ t.Fatal(rec.Body.String())
+ }
+ activate := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", `{"autonomy_level":"full","acknowledgement_id":"ack-lower-0001","investigation_budget":10,"investigation_timeout_sec":120}`, "org-a", "alice", "session-lower")
+ activateRec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, activateRec, activate)
+ if activateRec.Code != http.StatusOK {
+ t.Fatal(activateRec.Body.String())
+ }
+ before, _ := persistence.LoadAIConfig()
+ lower := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", `{"autonomy_level":"approval","full_mode_unlocked":true,"investigation_budget":10,"investigation_timeout_sec":120}`, "org-a", "alice", "session-lower")
+ lowerRec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, lowerRec, lower)
+ if lowerRec.Code != http.StatusOK {
+ t.Fatal(lowerRec.Body.String())
+ }
+ after, _ := persistence.LoadAIConfig()
+ if after.PatrolAutonomyLevel != config.PatrolAutonomyApproval || after.PatrolAutopilotActivation != nil || after.PatrolFullModeUnlocked || len(after.PatrolAutopilotAcknowledgements) != len(before.PatrolAutopilotAcknowledgements) || after.PatrolAutopilotAcknowledgements[0].Digest != before.PatrolAutopilotAcknowledgements[0].Digest {
+ t.Fatalf("lower mode fabricated or changed acknowledgement: before=%#v after=%#v", before, after)
+ }
+}
+
+func TestPatrolAutopilotVersionRotationAndRevocationRaceFailClosed(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ handler, persistence := newPatrolAutopilotTestHandler(t, "org-a", &now)
+ if rec := createPatrolAutopilotAcknowledgement(t, handler, "org-a", "alice", "session-race", "ack-race-00001"); rec.Code != http.StatusCreated {
+ t.Fatal(rec.Body.String())
+ }
+
+ // Server-owned version rotation between acknowledgement and activation.
+ handler.SetPatrolAutopilotServerPolicyProvider(func() unifiedresources.PatrolAutopilotServerPolicy {
+ return unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: 2, Now: now.Add(time.Minute)}
+ })
+ stale := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", `{"autonomy_level":"full","acknowledgement_id":"ack-race-00001","investigation_budget":10,"investigation_timeout_sec":120}`, "org-a", "alice", "session-race")
+ staleRec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, staleRec, stale)
+ if staleRec.Code != http.StatusConflict || !strings.Contains(staleRec.Body.String(), unifiedresources.PatrolAutopilotStatusStaleVersion) {
+ t.Fatalf("stale status=%d body=%s", staleRec.Code, staleRec.Body.String())
+ }
+ reused := createPatrolAutopilotAcknowledgement(t, handler, "org-a", "alice", "session-race", "ack-race-00001")
+ if reused.Code != http.StatusConflict || !strings.Contains(reused.Body.String(), unifiedresources.PatrolAutopilotStatusConflict) {
+ t.Fatalf("V1 id reuse under V2 status=%d body=%s", reused.Code, reused.Body.String())
+ }
+ createdV2 := createPatrolAutopilotAcknowledgement(t, handler, "org-a", "alice", "session-race", "ack-race-v2-001")
+ if createdV2.Code != http.StatusCreated {
+ t.Fatalf("V2 acknowledgement status=%d body=%s", createdV2.Code, createdV2.Body.String())
+ }
+
+ // Activate the new V2 evidence, then race an exact activation retry with
+ // revocation. Both mutations share the same policy coordinator; either
+ // order must leave the effective mode below full.
+ activateBody := `{"autonomy_level":"full","acknowledgement_id":"ack-race-v2-001","investigation_budget":10,"investigation_timeout_sec":120}`
+ initial := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", activateBody, "org-a", "alice", "session-race")
+ initialRec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, initialRec, initial)
+ if initialRec.Code != http.StatusOK {
+ t.Fatal(initialRec.Body.String())
+ }
+ if effective := handler.GetAIService(initial.Context()).GetEffectivePatrolAutonomyLevel(); effective != config.PatrolAutonomyFull {
+ t.Fatalf("V2 API activation was not effective at runtime: %q", effective)
+ }
+
+ start := make(chan struct{})
+ results := make(chan int, 2)
+ retryRequest := patrolAutopilotSessionRequest(t, http.MethodPut, "/api/ai/patrol/autonomy", activateBody, "org-a", "alice", "session-race")
+ revokeRequest := patrolAutopilotSessionRequest(t, http.MethodDelete, "/api/ai/patrol/autonomy/acknowledgements/ack-race-v2-001", `{"reason":"operator stop"}`, "org-a", "alice", "session-race")
+ go func() {
+ <-start
+ rec := httptest.NewRecorder()
+ handlePatrolAutonomyUpdateForTest(handler, rec, retryRequest)
+ results <- rec.Code
+ }()
+ go func() {
+ <-start
+ rec := httptest.NewRecorder()
+ handler.HandleRevokePatrolAutopilotAcknowledgement(rec, revokeRequest)
+ results <- rec.Code
+ }()
+ close(start)
+ <-results
+ <-results
+ stored, err := persistence.LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ effective, status := stored.GetEffectivePatrolAutonomyWithPolicy("org-a", unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: unifiedresources.PatrolAutopilotAcknowledgementVersionV2, Now: now.Add(3 * time.Minute)})
+ if effective == config.PatrolAutonomyFull || status.Active || len(stored.PatrolAutopilotAcknowledgements) != 2 || len(stored.PatrolAutopilotRevocations) != 1 {
+ t.Fatalf("race left full effective=%q status=%#v config=%#v", effective, status, stored)
+ }
+}
+
+func TestPatrolAutopilotStoreUnavailableDoesNotChangeModeOrFabricateEvidence(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ handler := newTestAISettingsHandler(&config.Config{}, nil, nil)
+ handler.SetPatrolAutopilotServerPolicyProvider(func() unifiedresources.PatrolAutopilotServerPolicy {
+ return unifiedresources.CurrentPatrolAutopilotServerPolicy(now)
+ })
+ req := patrolAutopilotSessionRequest(t, http.MethodPost, "/api/ai/patrol/autonomy/acknowledgements", `{"acknowledgement_id":"ack-no-store-01"}`, "org-a", "alice", "session-store")
+ rec := httptest.NewRecorder()
+ handler.HandleCreatePatrolAutopilotAcknowledgement(rec, req)
+ if rec.Code != http.StatusServiceUnavailable || !strings.Contains(rec.Body.String(), unifiedresources.PatrolAutopilotStatusStoreUnavailable) {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+}
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index 99a5014620..9c7737c61d 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -634,6 +634,8 @@ var allRouteAllowlist = []string{
"/api/ai/patrol/suppressions/",
"/api/ai/patrol/dismissed",
"/api/ai/patrol/autonomy",
+ "/api/ai/patrol/autonomy/acknowledgements",
+ "/api/ai/patrol/autonomy/acknowledgements/",
"/api/ai/findings/",
"/api/ai/intelligence",
"/api/ai/intelligence/patterns",
diff --git a/internal/api/router.go b/internal/api/router.go
index 361954d573..ae72c0ffc5 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -686,9 +686,10 @@ func (r *Router) setupRoutes() {
if cfg == nil {
return PatrolActionPolicySnapshot{}, nil
}
+ effectiveAutonomyLevel := svc.GetEffectivePatrolAutonomyLevel()
return PatrolActionPolicySnapshot{
- EffectiveAutonomyLevel: svc.GetEffectivePatrolAutonomyLevel(),
- FullModeUnlocked: cfg.PatrolFullModeUnlocked,
+ EffectiveAutonomyLevel: effectiveAutonomyLevel,
+ FullModeUnlocked: effectiveAutonomyLevel == config.PatrolAutonomyFull,
EmergencyStop: cfg.PatrolActionEmergencyStop,
}, nil
})
diff --git a/internal/api/router_routes_ai_relay.go b/internal/api/router_routes_ai_relay.go
index 7685a637f7..335f64b256 100644
--- a/internal/api/router_routes_ai_relay.go
+++ b/internal/api/router_routes_ai_relay.go
@@ -165,12 +165,14 @@ func (r *Router) registerAIRelayRoutesGroup() {
// Patrol Autonomy - GET stays in core; PUT is extension-gated for premium
// modes while the free adapter persists findings-only monitor settings.
+ r.mux.HandleFunc("/api/ai/patrol/autonomy/acknowledgements", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleCreatePatrolAutopilotAcknowledgement)))
+ r.mux.HandleFunc("/api/ai/patrol/autonomy/acknowledgements/", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.aiSettingsHandler.HandleRevokePatrolAutopilotAcknowledgement)))
r.mux.HandleFunc("/api/ai/patrol/autonomy", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, func(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
r.aiSettingsHandler.HandleGetPatrolAutonomy(w, req)
case http.MethodPut:
- r.aiAutoFixEndpoints.HandleUpdatePatrolAutonomy(w, req)
+ r.aiSettingsHandler.GatePatrolAutonomyUpdate(r.aiAutoFixEndpoints.HandleUpdatePatrolAutonomy)(w, req)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
@@ -841,11 +843,7 @@ func (p *patrolConfigAdapter) GetPatrolFullModeUnlocked() bool {
if p.svc == nil {
return false
}
- cfg := p.svc.GetConfig()
- if cfg == nil {
- return false
- }
- return cfg.PatrolFullModeUnlocked
+ return p.svc.GetEffectivePatrolAutonomyLevel() == config.PatrolAutonomyFull
}
func (p *patrolConfigAdapter) GetPatrolAutonomyLevel() string {
@@ -873,33 +871,52 @@ type patrolConfigUpdateAdapter struct {
var _ aicontracts.PatrolConfigUpdater = (*patrolConfigUpdateAdapter)(nil)
func (u *patrolConfigUpdateAdapter) SaveAutonomySettings(ctx context.Context, level string, unlocked bool, budget, timeoutSec int) error {
- svc := u.handler.GetAIService(ctx)
- if svc == nil {
- return fmt.Errorf("AI service not available")
- }
- cfg := svc.GetConfig()
- if cfg == nil {
- return fmt.Errorf("AI config not available")
- }
- write := func() error {
- cfg.PatrolFullModeUnlocked = unlocked
+ _ = unlocked // legacy extension input is compatibility data, never authority.
+ if ctx == nil {
+ ctx = u.ctx
+ }
+ if u == nil || u.handler == nil || !config.IsValidPatrolAutonomyLevel(level) {
+ return fmt.Errorf("invalid Patrol autonomy update")
+ }
+ return u.handler.mutatePatrolAutopilotConfig(ctx, func(cfg *config.AIConfig, policy unifiedresources.PatrolAutopilotServerPolicy) (bool, error) {
+ changed := cfg.PatrolAutonomyLevel != level || cfg.PatrolInvestigationBudget != budget || cfg.PatrolInvestigationTimeoutSec != timeoutSec
+ if level == config.PatrolAutonomyFull {
+ activationRequest, ok := patrolAutopilotActivationFromContext(ctx)
+ if !ok {
+ return false, &unifiedresources.PatrolAutopilotContractError{Code: unifiedresources.PatrolAutopilotStatusAcknowledgementRequired}
+ }
+ binding, bindingChanged, err := unifiedresources.BindPatrolAutopilotActivation(
+ cfg.PatrolAutopilotAcknowledgements,
+ cfg.PatrolAutopilotRevocations,
+ cfg.PatrolAutopilotActivation,
+ activationRequest.AcknowledgementID,
+ activationRequest.Actor,
+ policy,
+ )
+ if err != nil {
+ return false, err
+ }
+ changed = changed || bindingChanged || !cfg.PatrolFullModeUnlocked
+ cfg.PatrolAutopilotActivation = &binding
+ cfg.PatrolFullModeUnlocked = true
+ } else {
+ changed = changed || cfg.PatrolAutopilotActivation != nil || cfg.PatrolFullModeUnlocked
+ cfg.PatrolAutopilotActivation = nil
+ cfg.PatrolFullModeUnlocked = false
+ }
cfg.PatrolAutonomyLevel = level
cfg.PatrolInvestigationBudget = budget
cfg.PatrolInvestigationTimeoutSec = timeoutSec
- return u.handler.getPersistence(ctx).SaveAIConfig(*cfg)
- }
- if u.resources != nil {
- return u.resources.ActionLifecycle().WithPolicyMutation(write)
- }
- return write()
+ return changed, nil
+ })
}
func (u *patrolConfigUpdateAdapter) ReloadConfig(ctx context.Context) error {
- svc := u.handler.GetAIService(ctx)
- if svc == nil {
- return fmt.Errorf("AI service not available")
- }
- return svc.LoadConfig()
+ // SaveAutonomySettings publishes the persisted autonomy fields while the
+ // Task 04 policy-mutation lock is still held. A second reload would split
+ // activation/revocation from the runtime boundary and is intentionally a
+ // no-op for this adapter.
+ return nil
}
// ---------------------------------------------------------------------------
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 5e16e865a6..65b124840a 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -2740,6 +2740,8 @@ func TestProxyAuthNonAdminDeniedAdminEndpoints(t *testing.T) {
{method: http.MethodPost, path: "/api/ai/remediation/rollback", body: `{}`},
{method: http.MethodPost, path: "/api/ai/patrol/run", body: `{}`},
{method: http.MethodGet, path: "/api/ai/patrol/autonomy", body: ""},
+ {method: http.MethodPost, path: "/api/ai/patrol/autonomy/acknowledgements", body: `{}`},
+ {method: http.MethodDelete, path: "/api/ai/patrol/autonomy/acknowledgements/ack-test", body: `{}`},
{method: http.MethodPost, path: "/api/ai/cost/reset", body: `{}`},
{method: http.MethodGet, path: "/api/ai/cost/export", body: ""},
{method: http.MethodPost, path: "/api/ai/oauth/start", body: `{}`},
diff --git a/internal/config/ai.go b/internal/config/ai.go
index b35bf75238..b50df62bbb 100644
--- a/internal/config/ai.go
+++ b/internal/config/ai.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
// AuthMethod represents how Anthropic authentication is performed
@@ -104,11 +105,14 @@ type AIConfig struct {
ProtectedGuests []string `json:"protected_guests,omitempty"` // VMIDs or names that AI cannot control
// Patrol Autonomy settings - controls automatic investigation and remediation of findings
- PatrolAutonomyLevel string `json:"patrol_autonomy_level,omitempty"` // "monitor", "approval", "assisted", "full"
- PatrolFullModeUnlocked bool `json:"patrol_full_mode_unlocked"` // User has acknowledged Full mode risks (required to use "full")
- PatrolActionEmergencyStop bool `json:"patrol_action_emergency_stop"` // Blocks new human and policy action admission; does not imply rollback
- PatrolInvestigationBudget int `json:"patrol_investigation_budget,omitempty"` // Max turns per investigation (default: 15)
- PatrolInvestigationTimeoutSec int `json:"patrol_investigation_timeout_sec,omitempty"` // Max seconds per investigation (default: 300)
+ PatrolAutonomyLevel string `json:"patrol_autonomy_level,omitempty"` // "monitor", "approval", "assisted", "full"
+ PatrolFullModeUnlocked bool `json:"patrol_full_mode_unlocked"` // Legacy wire/storage compatibility only; never authority for effective full mode.
+ PatrolAutopilotAcknowledgements []unifiedresources.PatrolAutopilotAcknowledgement `json:"patrol_autopilot_acknowledgements,omitempty"`
+ PatrolAutopilotRevocations []unifiedresources.PatrolAutopilotRevocation `json:"patrol_autopilot_revocations,omitempty"`
+ PatrolAutopilotActivation *unifiedresources.PatrolAutopilotActivation `json:"patrol_autopilot_activation,omitempty"`
+ PatrolActionEmergencyStop bool `json:"patrol_action_emergency_stop"` // Blocks new human and policy action admission; does not imply rollback
+ PatrolInvestigationBudget int `json:"patrol_investigation_budget,omitempty"` // Max turns per investigation (default: 15)
+ PatrolInvestigationTimeoutSec int `json:"patrol_investigation_timeout_sec,omitempty"` // Max seconds per investigation (default: 300)
// Discovery settings - controls automatic infrastructure discovery
DiscoveryEnabled bool `json:"discovery_enabled"` // Enable infrastructure discovery
@@ -864,6 +868,41 @@ func (c *AIConfig) GetPatrolAutonomyLevel() string {
}
}
+// GetEffectivePatrolAutonomy evaluates the requested Patrol mode against the
+// server-owned Autopilot acknowledgement and activation evidence. The legacy
+// PatrolFullModeUnlocked boolean is intentionally passed only so the evaluator
+// can report that it was ignored; it can never authorize full mode.
+func (c *AIConfig) GetEffectivePatrolAutonomy(orgID string, now time.Time) (string, unifiedresources.PatrolAutopilotStatus) {
+ return c.GetEffectivePatrolAutonomyWithPolicy(orgID, unifiedresources.CurrentPatrolAutopilotServerPolicy(now))
+}
+
+func (c *AIConfig) GetEffectivePatrolAutonomyWithPolicy(orgID string, policy unifiedresources.PatrolAutopilotServerPolicy) (string, unifiedresources.PatrolAutopilotStatus) {
+ if c == nil {
+ contract, _ := unifiedresources.PatrolAutopilotContractForVersion(policy.CurrentVersion)
+ return PatrolAutonomyMonitor, unifiedresources.PatrolAutopilotStatus{
+ Code: unifiedresources.PatrolAutopilotStatusAcknowledgementRequired,
+ CurrentVersion: policy.CurrentVersion,
+ AcceptedScope: contract.AcceptedScope,
+ AcceptedLimits: contract.AcceptedLimits,
+ }
+ }
+ return unifiedresources.EvaluatePatrolAutopilot(
+ c.GetPatrolAutonomyLevel(),
+ PatrolAutonomyApproval,
+ strings.TrimSpace(orgID),
+ c.PatrolFullModeUnlocked,
+ c.PatrolAutopilotAcknowledgements,
+ c.PatrolAutopilotRevocations,
+ c.PatrolAutopilotActivation,
+ policy,
+ )
+}
+
+func (c *AIConfig) IsPatrolFullModeActive(orgID string, now time.Time) bool {
+ level, status := c.GetEffectivePatrolAutonomy(orgID, now)
+ return level == PatrolAutonomyFull && status.Active
+}
+
// GetPatrolInvestigationBudget returns the max turns per investigation
func (c *AIConfig) GetPatrolInvestigationBudget() int {
if c.PatrolInvestigationBudget <= 0 {
diff --git a/internal/config/patrol_autopilot_persistence.go b/internal/config/patrol_autopilot_persistence.go
new file mode 100644
index 0000000000..035663a2b7
--- /dev/null
+++ b/internal/config/patrol_autopilot_persistence.go
@@ -0,0 +1,47 @@
+package config
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// validatePatrolAutopilotHistoryRewrite makes the encrypted AI config an
+// append-only authority ledger for acknowledgement and revocation facts. The
+// requested mode and current activation may change, but existing history may
+// never be removed, reordered, or edited by a stale config writer.
+func validatePatrolAutopilotHistoryRewrite(previous, next AIConfig) error {
+ if err := unifiedresources.ValidatePatrolAutopilotStoredEvidence(
+ next.PatrolAutopilotAcknowledgements,
+ next.PatrolAutopilotRevocations,
+ next.PatrolAutopilotActivation,
+ ); err != nil {
+ return err
+ }
+ if len(next.PatrolAutopilotAcknowledgements) < len(previous.PatrolAutopilotAcknowledgements) || len(next.PatrolAutopilotRevocations) < len(previous.PatrolAutopilotRevocations) {
+ return fmt.Errorf("patrol autopilot authority history cannot be removed")
+ }
+ for index := range previous.PatrolAutopilotAcknowledgements {
+ if !canonicalPatrolAutopilotPersistenceEqual(previous.PatrolAutopilotAcknowledgements[index], next.PatrolAutopilotAcknowledgements[index]) {
+ return fmt.Errorf("patrol autopilot acknowledgement history is immutable")
+ }
+ }
+ for index := range previous.PatrolAutopilotRevocations {
+ if !canonicalPatrolAutopilotPersistenceEqual(previous.PatrolAutopilotRevocations[index], next.PatrolAutopilotRevocations[index]) {
+ return fmt.Errorf("patrol autopilot revocation history is immutable")
+ }
+ }
+ if next.PatrolAutopilotActivation != nil {
+ if next.GetPatrolAutonomyLevel() != PatrolAutonomyFull {
+ return fmt.Errorf("patrol autopilot activation requires requested full mode")
+ }
+ }
+ return nil
+}
+
+func canonicalPatrolAutopilotPersistenceEqual(left, right any) bool {
+ leftJSON, leftErr := json.Marshal(left)
+ rightJSON, rightErr := json.Marshal(right)
+ return leftErr == nil && rightErr == nil && string(leftJSON) == string(rightJSON)
+}
diff --git a/internal/config/patrol_autopilot_persistence_test.go b/internal/config/patrol_autopilot_persistence_test.go
new file mode 100644
index 0000000000..85e7091e92
--- /dev/null
+++ b/internal/config/patrol_autopilot_persistence_test.go
@@ -0,0 +1,446 @@
+package config
+
+import (
+ "encoding/json"
+ "errors"
+ "os"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func configPatrolAutopilotActor(subject, credential, orgID string) unifiedresources.ActionActor {
+ return unifiedresources.ActionActor{SubjectID: subject, Kind: unifiedresources.ActionActorUser, CredentialID: credential, OrgID: orgID}
+}
+
+func TestAIConfigPatrolAutopilotStoredEvidenceRejectsMaliciousTwoTenantRewrite(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ policy := unifiedresources.CurrentPatrolAutopilotServerPolicy(now)
+
+ tests := []struct {
+ name string
+ mutate func(*AIConfig, unifiedresources.ActionActor)
+ }{
+ {name: "self digesting cross org revocation", mutate: func(cfg *AIConfig, foreignActor unifiedresources.ActionActor) {
+ revocation := unifiedresources.PatrolAutopilotRevocation{
+ Version: unifiedresources.PatrolAutopilotRevocationVersion,
+ AcknowledgementID: cfg.PatrolAutopilotAcknowledgements[0].ID,
+ OrgID: foreignActor.OrgID,
+ Actor: foreignActor,
+ Reason: "foreign mutation",
+ RevokedAt: now.Add(time.Minute),
+ }
+ revocation.Digest = unifiedresources.PatrolAutopilotRevocationDigest(revocation)
+ cfg.PatrolAutopilotRevocations = append(cfg.PatrolAutopilotRevocations, revocation)
+ }},
+ {name: "wrong acknowledgement actor org", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ cfg.PatrolAutopilotAcknowledgements[0].Actor.OrgID = "org-b"
+ cfg.PatrolAutopilotAcknowledgements[0].Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(cfg.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "unsupported acknowledgement version", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ cfg.PatrolAutopilotAcknowledgements[0].Version = 99
+ cfg.PatrolAutopilotAcknowledgements[0].Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(cfg.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "unsupported revocation version", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ acknowledgement := cfg.PatrolAutopilotAcknowledgements[0]
+ revocation := unifiedresources.PatrolAutopilotRevocation{
+ Version: 99,
+ AcknowledgementID: acknowledgement.ID,
+ OrgID: acknowledgement.OrgID,
+ Actor: acknowledgement.Actor,
+ Reason: "unsupported",
+ RevokedAt: now.Add(time.Minute),
+ }
+ revocation.Digest = unifiedresources.PatrolAutopilotRevocationDigest(revocation)
+ cfg.PatrolAutopilotRevocations = append(cfg.PatrolAutopilotRevocations, revocation)
+ }},
+ {name: "invalid acknowledgement id syntax", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ cfg.PatrolAutopilotAcknowledgements[0].ID = "bad"
+ cfg.PatrolAutopilotAcknowledgements[0].Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(cfg.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "altered accepted scope", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ cfg.PatrolAutopilotAcknowledgements[0].AcceptedScope = []string{"self_authored_scope"}
+ cfg.PatrolAutopilotAcknowledgements[0].Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(cfg.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "altered accepted limits", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ cfg.PatrolAutopilotAcknowledgements[0].AcceptedLimits.EmergencyStopHonored = false
+ cfg.PatrolAutopilotAcknowledgements[0].Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(cfg.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "V1 record carrying V2 limits", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ v2Contract, ok := unifiedresources.PatrolAutopilotContractForVersion(unifiedresources.PatrolAutopilotAcknowledgementVersionV2)
+ if !ok {
+ t.Fatal("V2 contract is not registered")
+ }
+ cfg.PatrolAutopilotAcknowledgements[0].AcceptedLimits = v2Contract.AcceptedLimits
+ cfg.PatrolAutopilotAcknowledgements[0].Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(cfg.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "invalid acknowledgement time", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ cfg.PatrolAutopilotAcknowledgements[0].ExpiresAt = cfg.PatrolAutopilotAcknowledgements[0].AcceptedAt
+ cfg.PatrolAutopilotAcknowledgements[0].Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(cfg.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "duplicate acknowledgement id", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ cfg.PatrolAutopilotAcknowledgements = append(cfg.PatrolAutopilotAcknowledgements, cfg.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "duplicate revocation", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ acknowledgement := cfg.PatrolAutopilotAcknowledgements[0]
+ revocation := unifiedresources.PatrolAutopilotRevocation{
+ Version: unifiedresources.PatrolAutopilotRevocationVersion,
+ AcknowledgementID: acknowledgement.ID,
+ OrgID: acknowledgement.OrgID,
+ Actor: acknowledgement.Actor,
+ Reason: "duplicate",
+ RevokedAt: now.Add(time.Minute),
+ }
+ revocation.Digest = unifiedresources.PatrolAutopilotRevocationDigest(revocation)
+ cfg.PatrolAutopilotRevocations = append(cfg.PatrolAutopilotRevocations, revocation, revocation)
+ }},
+ {name: "activation actor mismatch", mutate: func(cfg *AIConfig, _ unifiedresources.ActionActor) {
+ cfg.PatrolAutopilotActivation.Actor.CredentialID = "session:other"
+ cfg.PatrolAutopilotActivation.Digest = unifiedresources.PatrolAutopilotActivationDigest(*cfg.PatrolAutopilotActivation)
+ }},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ root := t.TempDir()
+ persistences := map[string]*ConfigPersistence{}
+ before := map[string][]byte{}
+ for _, orgID := range []string{"org-a", "org-b"} {
+ persistence := NewConfigPersistence(root + "/" + orgID)
+ actor := configPatrolAutopilotActor("admin", "session:"+orgID, orgID)
+ acknowledgement, activation := configPatrolAutopilotEvidence(t, "ack-shared-malicious", actor, policy)
+ cfg := NewDefaultAIConfig()
+ cfg.PatrolAutonomyLevel = PatrolAutonomyFull
+ cfg.PatrolAutopilotAcknowledgements = []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}
+ cfg.PatrolAutopilotActivation = &activation
+ if err := persistence.SaveAIConfig(*cfg); err != nil {
+ t.Fatal(err)
+ }
+ persistences[orgID] = persistence
+ data, err := os.ReadFile(persistence.aiFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ before[orgID] = data
+ }
+
+ malicious, err := persistences["org-a"].LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ tc.mutate(malicious, configPatrolAutopilotActor("foreign-admin", "session:org-b", "org-b"))
+ if err := persistences["org-a"].SaveAIConfig(*malicious); err == nil {
+ t.Fatal("malicious stored evidence unexpectedly persisted")
+ }
+
+ for _, orgID := range []string{"org-a", "org-b"} {
+ after, err := os.ReadFile(persistences[orgID].aiFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(before[orgID]) {
+ t.Fatalf("tenant %s file changed after rejected mutation", orgID)
+ }
+ reopened, err := NewConfigPersistence(root + "/" + orgID).LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ effective, status := reopened.GetEffectivePatrolAutonomyWithPolicy(orgID, policy)
+ if effective != PatrolAutonomyFull || !status.Active || len(reopened.PatrolAutopilotAcknowledgements) != 1 || len(reopened.PatrolAutopilotRevocations) != 0 {
+ t.Fatalf("tenant %s authoritative state changed: effective=%q status=%#v config=%#v", orgID, effective, status, reopened)
+ }
+ }
+ })
+ }
+}
+
+func configPatrolAutopilotEvidence(t *testing.T, id string, actor unifiedresources.ActionActor, policy unifiedresources.PatrolAutopilotServerPolicy) (unifiedresources.PatrolAutopilotAcknowledgement, unifiedresources.PatrolAutopilotActivation) {
+ t.Helper()
+ acknowledgement, _, err := unifiedresources.IssuePatrolAutopilotAcknowledgement(nil, id, actor, policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ activation, _, err := unifiedresources.BindPatrolAutopilotActivation([]unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}, nil, nil, id, actor, policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return acknowledgement, activation
+}
+
+func TestAIConfigPatrolAutopilotHistoryIsImmutableAcrossRewriteAndReopen(t *testing.T) {
+ dir := t.TempDir()
+ persistence := NewConfigPersistence(dir)
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ policy := unifiedresources.CurrentPatrolAutopilotServerPolicy(now)
+ actor := configPatrolAutopilotActor("admin-one", "session:one", "org-a")
+ acknowledgement, _ := configPatrolAutopilotEvidence(t, "ack-history-001", actor, policy)
+
+ cfg := NewDefaultAIConfig()
+ cfg.PatrolAutopilotAcknowledgements = []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}
+ if err := persistence.SaveAIConfig(*cfg); err != nil {
+ t.Fatal(err)
+ }
+
+ reopened := NewConfigPersistence(dir)
+ loaded, err := reopened.LoadAIConfig()
+ if err != nil || len(loaded.PatrolAutopilotAcknowledgements) != 1 || loaded.PatrolAutopilotAcknowledgements[0].Digest != acknowledgement.Digest {
+ t.Fatalf("reopen err=%v config=%#v", err, loaded)
+ }
+ secondActor := configPatrolAutopilotActor("admin-two", "session:two", "org-a")
+ second, _, err := unifiedresources.IssuePatrolAutopilotAcknowledgement(loaded.PatrolAutopilotAcknowledgements, "ack-history-002", secondActor, unifiedresources.CurrentPatrolAutopilotServerPolicy(now.Add(time.Minute)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ loaded.PatrolAutopilotAcknowledgements = append(loaded.PatrolAutopilotAcknowledgements, second)
+ loaded.PatrolInvestigationBudget = 20
+ if err := reopened.SaveAIConfig(*loaded); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, tc := range []struct {
+ name string
+ mutate func(*AIConfig)
+ }{
+ {name: "removed", mutate: func(record *AIConfig) {
+ record.PatrolAutopilotAcknowledgements = record.PatrolAutopilotAcknowledgements[1:]
+ }},
+ {name: "reordered", mutate: func(record *AIConfig) {
+ record.PatrolAutopilotAcknowledgements[0], record.PatrolAutopilotAcknowledgements[1] = record.PatrolAutopilotAcknowledgements[1], record.PatrolAutopilotAcknowledgements[0]
+ }},
+ {name: "edited", mutate: func(record *AIConfig) {
+ record.PatrolAutopilotAcknowledgements[0].AcceptedAt = record.PatrolAutopilotAcknowledgements[0].AcceptedAt.Add(time.Second)
+ record.PatrolAutopilotAcknowledgements[0].Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(record.PatrolAutopilotAcknowledgements[0])
+ }},
+ {name: "duplicate", mutate: func(record *AIConfig) {
+ record.PatrolAutopilotAcknowledgements = append(record.PatrolAutopilotAcknowledgements, record.PatrolAutopilotAcknowledgements[0])
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ current, loadErr := reopened.LoadAIConfig()
+ if loadErr != nil {
+ t.Fatal(loadErr)
+ }
+ tc.mutate(current)
+ if err := reopened.SaveAIConfig(*current); err == nil {
+ t.Fatal("malicious history rewrite unexpectedly persisted")
+ }
+ authoritative, loadErr := NewConfigPersistence(dir).LoadAIConfig()
+ if loadErr != nil || len(authoritative.PatrolAutopilotAcknowledgements) != 2 || authoritative.PatrolAutopilotAcknowledgements[0].Digest != acknowledgement.Digest || authoritative.PatrolAutopilotAcknowledgements[1].Digest != second.Digest {
+ t.Fatalf("authoritative history changed err=%v config=%#v", loadErr, authoritative)
+ }
+ })
+ }
+}
+
+func TestAIConfigPatrolAutopilotSupportedVersionRotationPreservesHistory(t *testing.T) {
+ dir := t.TempDir()
+ persistence := NewConfigPersistence(dir)
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ actor := configPatrolAutopilotActor("admin-one", "session:one", "org-a")
+ v1Policy := unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: unifiedresources.PatrolAutopilotAcknowledgementVersion, Now: now}
+ v1, _, err := unifiedresources.IssuePatrolAutopilotAcknowledgement(nil, "ack-rotation-v1", actor, v1Policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ v1Bytes, err := json.Marshal(v1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ initial := NewDefaultAIConfig()
+ initial.PatrolAutonomyLevel = PatrolAutonomyApproval
+ initial.PatrolAutopilotAcknowledgements = []unifiedresources.PatrolAutopilotAcknowledgement{v1}
+ if err := persistence.SaveAIConfig(*initial); err != nil {
+ t.Fatal(err)
+ }
+
+ v2Policy := unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: unifiedresources.PatrolAutopilotAcknowledgementVersionV2, Now: now.Add(time.Hour)}
+ reopenedV1, err := NewConfigPersistence(dir).LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A server version rotation must not make unrelated config writes reject
+ // valid immutable history from an older supported contract.
+ reopenedV1.PatrolInvestigationBudget = 23
+ if err := persistence.SaveAIConfig(*reopenedV1); err != nil {
+ t.Fatalf("unrelated save with valid V1 history failed: %v", err)
+ }
+
+ beforeConflict, err := os.ReadFile(persistence.aiFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := unifiedresources.IssuePatrolAutopilotAcknowledgement(reopenedV1.PatrolAutopilotAcknowledgements, v1.ID, actor, v2Policy); unifiedresources.PatrolAutopilotErrorCode(err) != unifiedresources.PatrolAutopilotStatusConflict {
+ t.Fatalf("V1 id reuse under V2 error=%v code=%q", err, unifiedresources.PatrolAutopilotErrorCode(err))
+ }
+ afterConflict, err := os.ReadFile(persistence.aiFile)
+ if err != nil || string(afterConflict) != string(beforeConflict) {
+ t.Fatalf("conflicting V1 id reuse changed persisted config: err=%v", err)
+ }
+ if _, _, err := unifiedresources.BindPatrolAutopilotActivation(reopenedV1.PatrolAutopilotAcknowledgements, nil, nil, v1.ID, actor, v2Policy); unifiedresources.PatrolAutopilotErrorCode(err) != unifiedresources.PatrolAutopilotStatusStaleVersion {
+ t.Fatalf("stale V1 activation error=%v code=%q", err, unifiedresources.PatrolAutopilotErrorCode(err))
+ }
+
+ v2, created, err := unifiedresources.IssuePatrolAutopilotAcknowledgement(reopenedV1.PatrolAutopilotAcknowledgements, "ack-rotation-v2", actor, v2Policy)
+ if err != nil || !created {
+ t.Fatalf("issue V2 created=%v err=%v", created, err)
+ }
+ if v2.Version != unifiedresources.PatrolAutopilotAcknowledgementVersionV2 || len(v2.AcceptedScope) == len(v1.AcceptedScope) || v2.AcceptedLimits == v1.AcceptedLimits {
+ t.Fatalf("V2 did not use its registered contract: v1=%#v v2=%#v", v1, v2)
+ }
+ reopenedV1.PatrolAutopilotAcknowledgements = append(reopenedV1.PatrolAutopilotAcknowledgements, v2)
+ if err := persistence.SaveAIConfig(*reopenedV1); err != nil {
+ t.Fatalf("persist V2 alongside V1: %v", err)
+ }
+ activation, created, err := unifiedresources.BindPatrolAutopilotActivation(reopenedV1.PatrolAutopilotAcknowledgements, nil, nil, v2.ID, actor, v2Policy)
+ if err != nil || !created {
+ t.Fatalf("activate V2 created=%v err=%v", created, err)
+ }
+ reopenedV1.PatrolAutonomyLevel = PatrolAutonomyFull
+ reopenedV1.PatrolAutopilotActivation = &activation
+ if err := persistence.SaveAIConfig(*reopenedV1); err != nil {
+ t.Fatalf("persist V2 activation: %v", err)
+ }
+
+ finalConfig, err := NewConfigPersistence(dir).LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(finalConfig.PatrolAutopilotAcknowledgements) != 2 {
+ t.Fatalf("rotation history=%#v", finalConfig.PatrolAutopilotAcknowledgements)
+ }
+ finalV1Bytes, err := json.Marshal(finalConfig.PatrolAutopilotAcknowledgements[0])
+ if err != nil || string(finalV1Bytes) != string(v1Bytes) {
+ t.Fatalf("V1 history changed during rotation: err=%v before=%s after=%s", err, v1Bytes, finalV1Bytes)
+ }
+ effective, status := finalConfig.GetEffectivePatrolAutonomyWithPolicy("org-a", unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: unifiedresources.PatrolAutopilotAcknowledgementVersionV2, Now: now.Add(2 * time.Hour)})
+ if effective != PatrolAutonomyFull || !status.Active || status.CurrentVersion != unifiedresources.PatrolAutopilotAcknowledgementVersionV2 || status.AcknowledgementVersion != unifiedresources.PatrolAutopilotAcknowledgementVersionV2 || status.AcknowledgementID != v2.ID || !slices.Equal(status.AcceptedScope, v2.AcceptedScope) || status.AcceptedLimits != v2.AcceptedLimits {
+ t.Fatalf("V2 activation did not survive reopen: effective=%q status=%#v", effective, status)
+ }
+}
+
+func TestAIConfigPatrolAutopilotRejectsMalformedEvidenceOnInitialSave(t *testing.T) {
+ dir := t.TempDir()
+ persistence := NewConfigPersistence(dir)
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ actor := configPatrolAutopilotActor("admin-one", "session:one", "org-a")
+ acknowledgement, _ := configPatrolAutopilotEvidence(t, "ack-initial-bad", actor, unifiedresources.CurrentPatrolAutopilotServerPolicy(now))
+ acknowledgement.AcceptedLimits.PolicyAllowlistRequired = false
+ acknowledgement.Digest = unifiedresources.PatrolAutopilotAcknowledgementDigest(acknowledgement)
+ cfg := NewDefaultAIConfig()
+ cfg.PatrolAutopilotAcknowledgements = []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}
+ if err := persistence.SaveAIConfig(*cfg); err == nil {
+ t.Fatal("malformed initial authority evidence unexpectedly persisted")
+ }
+ if _, err := os.Stat(persistence.aiFile); !os.IsNotExist(err) {
+ t.Fatalf("rejected initial save created authority file: %v", err)
+ }
+}
+
+func TestAIConfigPatrolAutopilotActivationAndRequestedModeCommitAtomically(t *testing.T) {
+ dir := t.TempDir()
+ persistence := NewConfigPersistence(dir)
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ policy := unifiedresources.CurrentPatrolAutopilotServerPolicy(now)
+ actor := configPatrolAutopilotActor("admin-one", "session:one", "org-a")
+ acknowledgement, activation := configPatrolAutopilotEvidence(t, "ack-atomic-0001", actor, policy)
+
+ baseline := NewDefaultAIConfig()
+ baseline.PatrolAutonomyLevel = PatrolAutonomyApproval
+ baseline.PatrolAutopilotAcknowledgements = []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}
+ if err := persistence.SaveAIConfig(*baseline); err != nil {
+ t.Fatal(err)
+ }
+
+ desired := *baseline
+ desired.PatrolAutonomyLevel = PatrolAutonomyFull
+ desired.PatrolFullModeUnlocked = true
+ desired.PatrolAutopilotActivation = &activation
+ persistence.fs = &mockFSError{FileSystem: defaultFileSystem{}, writeError: errors.New("write failed")}
+ if err := persistence.SaveAIConfig(desired); err == nil {
+ t.Fatal("write failure unexpectedly succeeded")
+ }
+ persistence.fs = defaultFileSystem{}
+ afterFailure, err := NewConfigPersistence(dir).LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if effective, status := afterFailure.GetEffectivePatrolAutonomyWithPolicy("org-a", policy); effective != PatrolAutonomyApproval || status.Active || afterFailure.PatrolAutopilotActivation != nil {
+ t.Fatalf("failed atomic write changed effective mode: effective=%q status=%#v config=%#v", effective, status, afterFailure)
+ }
+
+ if err := persistence.SaveAIConfig(desired); err != nil {
+ t.Fatal(err)
+ }
+ reopened, err := NewConfigPersistence(dir).LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if effective, status := reopened.GetEffectivePatrolAutonomyWithPolicy("org-a", policy); effective != PatrolAutonomyFull || !status.Active || reopened.PatrolAutopilotActivation == nil {
+ t.Fatalf("atomic activation did not reopen: effective=%q status=%#v config=%#v", effective, status, reopened)
+ }
+}
+
+func TestAIConfigPatrolAutopilotTenantFilesDoNotCollide(t *testing.T) {
+ root := t.TempDir()
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ policy := unifiedresources.CurrentPatrolAutopilotServerPolicy(now)
+ for _, orgID := range []string{"org-a", "org-b"} {
+ persistence := NewConfigPersistence(root + "/" + orgID)
+ actor := configPatrolAutopilotActor("admin", "session:"+orgID, orgID)
+ acknowledgement, _ := configPatrolAutopilotEvidence(t, "ack-shared-id", actor, policy)
+ cfg := NewDefaultAIConfig()
+ cfg.PatrolAutopilotAcknowledgements = []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}
+ if err := persistence.SaveAIConfig(*cfg); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, orgID := range []string{"org-a", "org-b"} {
+ loaded, err := NewConfigPersistence(root + "/" + orgID).LoadAIConfig()
+ if err != nil || len(loaded.PatrolAutopilotAcknowledgements) != 1 || loaded.PatrolAutopilotAcknowledgements[0].OrgID != orgID || loaded.PatrolAutopilotAcknowledgements[0].Actor.CredentialID != "session:"+orgID {
+ t.Fatalf("tenant %s collision err=%v config=%#v", orgID, err, loaded)
+ }
+ }
+}
+
+func TestAIConfigLegacyFullUnlockAndStaleVersionFailClosedAfterRestart(t *testing.T) {
+ dir := t.TempDir()
+ persistence := NewConfigPersistence(dir)
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ actor := configPatrolAutopilotActor("admin-one", "session:one", "org-a")
+ oldPolicy := unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: 1, Now: now}
+ acknowledgement, activation := configPatrolAutopilotEvidence(t, "ack-stale-0001", actor, oldPolicy)
+ cfg := NewDefaultAIConfig()
+ cfg.PatrolAutonomyLevel = PatrolAutonomyFull
+ cfg.PatrolFullModeUnlocked = true
+ cfg.PatrolAutopilotAcknowledgements = []unifiedresources.PatrolAutopilotAcknowledgement{acknowledgement}
+ cfg.PatrolAutopilotActivation = &activation
+ if err := persistence.SaveAIConfig(*cfg); err != nil {
+ t.Fatal(err)
+ }
+ reopened, err := NewConfigPersistence(dir).LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ effective, status := reopened.GetEffectivePatrolAutonomyWithPolicy("org-a", unifiedresources.PatrolAutopilotServerPolicy{CurrentVersion: 2, Now: now.Add(time.Hour)})
+ if effective != PatrolAutonomyApproval || status.Active || status.Code != unifiedresources.PatrolAutopilotStatusStaleVersion {
+ t.Fatalf("stale restart effective=%q status=%#v", effective, status)
+ }
+
+ legacy := NewDefaultAIConfig()
+ legacy.PatrolAutonomyLevel = PatrolAutonomyFull
+ legacy.PatrolFullModeUnlocked = true
+ legacyDir := t.TempDir()
+ if err := NewConfigPersistence(legacyDir).SaveAIConfig(*legacy); err != nil {
+ t.Fatal(err)
+ }
+ legacyReopened, err := NewConfigPersistence(legacyDir).LoadAIConfig()
+ if err != nil {
+ t.Fatal(err)
+ }
+ effective, status = legacyReopened.GetEffectivePatrolAutonomyWithPolicy("org-a", oldPolicy)
+ if effective != PatrolAutonomyApproval || status.Active || status.Code != unifiedresources.PatrolAutopilotStatusLegacyBooleanIgnored {
+ t.Fatalf("legacy restart effective=%q status=%#v", effective, status)
+ }
+}
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index ada1c88c7f..8ecb60ebe6 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -2091,6 +2091,23 @@ func (c *ConfigPersistence) SaveAIConfig(settings AIConfig) error {
c.mu.Lock()
defer c.mu.Unlock()
+ var previous AIConfig
+ if existingData, readErr := c.fs.ReadFile(c.aiFile); readErr == nil {
+ if c.crypto != nil {
+ if decrypted, decryptErr := c.crypto.Decrypt(existingData); decryptErr == nil {
+ existingData = decrypted
+ }
+ }
+ if unmarshalErr := json.Unmarshal(existingData, &previous); unmarshalErr != nil {
+ return fmt.Errorf("load existing ai config for patrol autopilot history validation: %w", unmarshalErr)
+ }
+ } else if !os.IsNotExist(readErr) {
+ return fmt.Errorf("load existing ai config for patrol autopilot history validation: %w", readErr)
+ }
+ if err := validatePatrolAutopilotHistoryRewrite(previous, settings); err != nil {
+ return err
+ }
+
settings.NormalizePatrolEventTriggerSettings()
settings.NormalizeQuickstartModelAliases()
ollamaKeepAlive, err := NormalizeOllamaKeepAlive(settings.OllamaKeepAlive)
diff --git a/internal/unifiedresources/patrol_autopilot.go b/internal/unifiedresources/patrol_autopilot.go
new file mode 100644
index 0000000000..9af61ed39d
--- /dev/null
+++ b/internal/unifiedresources/patrol_autopilot.go
@@ -0,0 +1,565 @@
+package unifiedresources
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "regexp"
+ "slices"
+ "sort"
+ "strings"
+ "time"
+)
+
+const (
+ PatrolAutopilotAcknowledgementVersionV1 = 1
+ PatrolAutopilotAcknowledgementVersion = PatrolAutopilotAcknowledgementVersionV1
+ PatrolAutopilotAcknowledgementVersionV2 = 2
+ PatrolAutopilotCurrentAcknowledgementVersion = PatrolAutopilotAcknowledgementVersionV1
+ PatrolAutopilotActivationVersion = 1
+ PatrolAutopilotRevocationVersion = 1
+
+ PatrolAutopilotStatusActive = "active"
+ PatrolAutopilotStatusNotRequested = "not_requested"
+ PatrolAutopilotStatusAcknowledgementRequired = "acknowledgement_required"
+ PatrolAutopilotStatusStaleVersion = "acknowledgement_stale_version"
+ PatrolAutopilotStatusWrongOrg = "acknowledgement_wrong_org"
+ PatrolAutopilotStatusWrongActor = "acknowledgement_wrong_actor"
+ PatrolAutopilotStatusUserRequired = "acknowledgement_user_required"
+ PatrolAutopilotStatusDigestInvalid = "acknowledgement_digest_invalid"
+ PatrolAutopilotStatusExpired = "acknowledgement_expired"
+ PatrolAutopilotStatusRevoked = "acknowledgement_revoked"
+ PatrolAutopilotStatusConflict = "acknowledgement_conflict"
+ PatrolAutopilotStatusActivationDigestInvalid = "activation_digest_invalid"
+ PatrolAutopilotStatusLegacyBooleanIgnored = "legacy_unlock_ignored"
+ PatrolAutopilotStatusStoreUnavailable = "acknowledgement_store_unavailable"
+ PatrolAutopilotStatusActivationRace = "acknowledgement_activation_raced"
+ PatrolAutopilotStatusLicenseRequired = "license_required"
+ PatrolAutopilotScopePolicyAuthorizedActions = "policy_authorized_actions"
+ PatrolAutopilotScopeCapabilityAllowlistedOnly = "capability_allowlisted_only"
+ PatrolAutopilotScopeOutcomeTruthNotInferred = "outcome_truth_not_inferred"
+ PatrolAutopilotScopeRevocationVersionBound = "revocation_and_version_rotation_bound"
+)
+
+var patrolAutopilotAcknowledgementIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$`)
+
+// PatrolAutopilotAcceptedLimits is the server-owned risk envelope accepted by
+// one acknowledgement version. Clients may display it, but cannot author it.
+type PatrolAutopilotAcceptedLimits struct {
+ PolicyAllowlistRequired bool `json:"policyAllowlistRequired"`
+ EmergencyStopHonored bool `json:"emergencyStopHonored"`
+ ApprovalFloorsHonored bool `json:"approvalFloorsHonored"`
+ VerificationReconciledWhenSupported bool `json:"verificationReconciledWhenSupported"`
+ EvidenceClassDisclosed bool `json:"evidenceClassDisclosed"`
+ InconclusiveOutcomeAllowed bool `json:"inconclusiveOutcomeAllowed"`
+ ExecutionSuccessIsNotOutcomeTruth bool `json:"executionSuccessIsNotOutcomeTruth"`
+ ActivationRevocationBound bool `json:"activationRevocationBound,omitempty"`
+}
+
+// PatrolAutopilotAcknowledgementContract is the immutable server-owned risk
+// contract for one supported acknowledgement version. Historical records are
+// always validated against their own version's entry.
+type PatrolAutopilotAcknowledgementContract struct {
+ Version int
+ AcceptedScope []string
+ AcceptedLimits PatrolAutopilotAcceptedLimits
+ Lifetime time.Duration
+}
+
+func PatrolAutopilotContractForVersion(version int) (PatrolAutopilotAcknowledgementContract, bool) {
+ baseScope := []string{
+ PatrolAutopilotScopePolicyAuthorizedActions,
+ PatrolAutopilotScopeCapabilityAllowlistedOnly,
+ PatrolAutopilotScopeOutcomeTruthNotInferred,
+ }
+ baseLimits := PatrolAutopilotAcceptedLimits{
+ PolicyAllowlistRequired: true,
+ EmergencyStopHonored: true,
+ ApprovalFloorsHonored: true,
+ VerificationReconciledWhenSupported: true,
+ EvidenceClassDisclosed: true,
+ InconclusiveOutcomeAllowed: true,
+ ExecutionSuccessIsNotOutcomeTruth: true,
+ }
+ switch version {
+ case PatrolAutopilotAcknowledgementVersionV1:
+ return PatrolAutopilotAcknowledgementContract{Version: version, AcceptedScope: baseScope, AcceptedLimits: baseLimits}, true
+ case PatrolAutopilotAcknowledgementVersionV2:
+ baseScope = append(baseScope, PatrolAutopilotScopeRevocationVersionBound)
+ baseLimits.ActivationRevocationBound = true
+ return PatrolAutopilotAcknowledgementContract{Version: version, AcceptedScope: baseScope, AcceptedLimits: baseLimits}, true
+ default:
+ return PatrolAutopilotAcknowledgementContract{}, false
+ }
+}
+
+func CurrentPatrolAutopilotAcceptedScope() []string {
+ contract, _ := PatrolAutopilotContractForVersion(PatrolAutopilotCurrentAcknowledgementVersion)
+ return contract.AcceptedScope
+}
+
+func CurrentPatrolAutopilotAcceptedLimits() PatrolAutopilotAcceptedLimits {
+ contract, _ := PatrolAutopilotContractForVersion(PatrolAutopilotCurrentAcknowledgementVersion)
+ return contract.AcceptedLimits
+}
+
+// PatrolAutopilotServerPolicy is injected by the server boundary. It is never
+// decoded from a public request, which keeps version and lifetime rotation
+// deterministic and server-owned.
+type PatrolAutopilotServerPolicy struct {
+ CurrentVersion int
+ Now time.Time
+ Lifetime time.Duration
+}
+
+func CurrentPatrolAutopilotServerPolicy(now time.Time) PatrolAutopilotServerPolicy {
+ return PatrolAutopilotServerPolicy{CurrentVersion: PatrolAutopilotCurrentAcknowledgementVersion, Now: now.UTC()}
+}
+
+func normalizePatrolAutopilotServerPolicy(policy PatrolAutopilotServerPolicy) (PatrolAutopilotServerPolicy, error) {
+ if policy.CurrentVersion <= 0 || policy.Now.IsZero() || policy.Lifetime < 0 {
+ return PatrolAutopilotServerPolicy{}, fmt.Errorf("invalid server acknowledgement policy")
+ }
+ if _, supported := PatrolAutopilotContractForVersion(policy.CurrentVersion); !supported {
+ return PatrolAutopilotServerPolicy{}, fmt.Errorf("unsupported server acknowledgement version %d", policy.CurrentVersion)
+ }
+ policy.Now = policy.Now.UTC()
+ return policy, nil
+}
+
+// PatrolAutopilotAcknowledgement is immutable evidence that a human accepted
+// the current server-owned Autopilot scope and limits.
+type PatrolAutopilotAcknowledgement struct {
+ Version int `json:"version"`
+ ID string `json:"id"`
+ OrgID string `json:"orgId"`
+ Actor ActionActor `json:"actor"`
+ AcceptedScope []string `json:"acceptedScope"`
+ AcceptedLimits PatrolAutopilotAcceptedLimits `json:"acceptedLimits"`
+ AcceptedAt time.Time `json:"acceptedAt"`
+ ExpiresAt time.Time `json:"expiresAt,omitempty"`
+ Digest string `json:"digest"`
+}
+
+// PatrolAutopilotRevocation is an append-only fact. Revoking activation never
+// mutates or deletes the acknowledgement that was originally accepted.
+type PatrolAutopilotRevocation struct {
+ Version int `json:"version"`
+ AcknowledgementID string `json:"acknowledgementId"`
+ OrgID string `json:"orgId"`
+ Actor ActionActor `json:"actor"`
+ Reason string `json:"reason,omitempty"`
+ RevokedAt time.Time `json:"revokedAt"`
+ Digest string `json:"digest"`
+}
+
+// PatrolAutopilotActivation binds a requested full-mode setting to one
+// persisted acknowledgement. The binding is replaced only by a new explicit
+// activation and is cleared when a lower mode is selected.
+type PatrolAutopilotActivation struct {
+ Version int `json:"version"`
+ AcknowledgementID string `json:"acknowledgementId"`
+ AcknowledgementDigest string `json:"acknowledgementDigest"`
+ OrgID string `json:"orgId"`
+ Actor ActionActor `json:"actor"`
+ ActivatedAt time.Time `json:"activatedAt"`
+ Digest string `json:"digest"`
+}
+
+type PatrolAutopilotStatus struct {
+ Code string `json:"code"`
+ Active bool `json:"active"`
+ CurrentVersion int `json:"currentVersion"`
+ AcknowledgementVersion int `json:"acknowledgementVersion,omitempty"`
+ AcknowledgementID string `json:"acknowledgementId,omitempty"`
+ AcknowledgementDigest string `json:"acknowledgementDigest,omitempty"`
+ AcknowledgedBy string `json:"acknowledgedBy,omitempty"`
+ AcceptedAt time.Time `json:"acceptedAt,omitempty"`
+ ExpiresAt time.Time `json:"expiresAt,omitempty"`
+ AcceptedScope []string `json:"acceptedScope"`
+ AcceptedLimits PatrolAutopilotAcceptedLimits `json:"acceptedLimits"`
+}
+
+type PatrolAutopilotContractError struct {
+ Code string
+ Err error
+}
+
+func (e *PatrolAutopilotContractError) Error() string {
+ if e == nil {
+ return ""
+ }
+ if e.Err == nil {
+ return e.Code
+ }
+ return e.Code + ": " + e.Err.Error()
+}
+
+func (e *PatrolAutopilotContractError) Unwrap() error { return e.Err }
+
+func PatrolAutopilotErrorCode(err error) string {
+ var contractErr *PatrolAutopilotContractError
+ if errors.As(err, &contractErr) {
+ return contractErr.Code
+ }
+ return ""
+}
+
+func patrolAutopilotError(code string, err error) error {
+ return &PatrolAutopilotContractError{Code: code, Err: err}
+}
+
+func canonicalPatrolAutopilotDigest(value any) string {
+ data, err := json.Marshal(value)
+ if err != nil {
+ return ""
+ }
+ sum := sha256.Sum256(data)
+ return "sha256:" + hex.EncodeToString(sum[:])
+}
+
+func PatrolAutopilotAcknowledgementDigest(record PatrolAutopilotAcknowledgement) string {
+ record.Digest = ""
+ record.Actor = NormalizeActionActor(record.Actor)
+ record.ID = strings.TrimSpace(record.ID)
+ record.OrgID = strings.TrimSpace(record.OrgID)
+ record.AcceptedAt = record.AcceptedAt.UTC()
+ if !record.ExpiresAt.IsZero() {
+ record.ExpiresAt = record.ExpiresAt.UTC()
+ }
+ record.AcceptedScope = append([]string(nil), record.AcceptedScope...)
+ sort.Strings(record.AcceptedScope)
+ return canonicalPatrolAutopilotDigest(record)
+}
+
+func PatrolAutopilotRevocationDigest(record PatrolAutopilotRevocation) string {
+ record.Digest = ""
+ record.AcknowledgementID = strings.TrimSpace(record.AcknowledgementID)
+ record.OrgID = strings.TrimSpace(record.OrgID)
+ record.Actor = NormalizeActionActor(record.Actor)
+ record.Reason = strings.TrimSpace(record.Reason)
+ record.RevokedAt = record.RevokedAt.UTC()
+ return canonicalPatrolAutopilotDigest(record)
+}
+
+func PatrolAutopilotActivationDigest(record PatrolAutopilotActivation) string {
+ record.Digest = ""
+ record.AcknowledgementID = strings.TrimSpace(record.AcknowledgementID)
+ record.AcknowledgementDigest = strings.TrimSpace(record.AcknowledgementDigest)
+ record.OrgID = strings.TrimSpace(record.OrgID)
+ record.Actor = NormalizeActionActor(record.Actor)
+ record.ActivatedAt = record.ActivatedAt.UTC()
+ return canonicalPatrolAutopilotDigest(record)
+}
+
+// ValidatePatrolAutopilotStoredEvidence is the single captured-evidence
+// validator used before durable config mutation. It validates immutable fact
+// shape and binding only; current authorization and version/lifetime policy are
+// enforced by the API/runtime boundary.
+func ValidatePatrolAutopilotStoredEvidence(acknowledgements []PatrolAutopilotAcknowledgement, revocations []PatrolAutopilotRevocation, activation *PatrolAutopilotActivation) error {
+ acknowledgementByID := make(map[string]PatrolAutopilotAcknowledgement, len(acknowledgements))
+ for _, record := range acknowledgements {
+ normalizedActor := NormalizeActionActor(record.Actor)
+ if record.ID != strings.TrimSpace(record.ID) || record.OrgID != strings.TrimSpace(record.OrgID) || record.Actor != normalizedActor || !patrolAutopilotAcknowledgementIDPattern.MatchString(record.ID) {
+ return fmt.Errorf("patrol autopilot acknowledgement id is invalid")
+ }
+ if _, duplicate := acknowledgementByID[record.ID]; duplicate {
+ return fmt.Errorf("patrol autopilot acknowledgement id is duplicated")
+ }
+ contract, supported := PatrolAutopilotContractForVersion(record.Version)
+ if !supported {
+ return fmt.Errorf("patrol autopilot acknowledgement version is unsupported")
+ }
+ if err := ValidateActionActor(record.Actor); err != nil || record.Actor.Kind != ActionActorUser || record.Actor.OrgID != record.OrgID {
+ return fmt.Errorf("patrol autopilot acknowledgement actor binding is invalid")
+ }
+ if !slices.Equal(record.AcceptedScope, contract.AcceptedScope) || record.AcceptedLimits != contract.AcceptedLimits {
+ return fmt.Errorf("patrol autopilot acknowledgement scope or limits are invalid")
+ }
+ if record.AcceptedAt.IsZero() || (!record.ExpiresAt.IsZero() && !record.ExpiresAt.After(record.AcceptedAt)) {
+ return fmt.Errorf("patrol autopilot acknowledgement validity interval is invalid")
+ }
+ if record.Digest == "" || record.Digest != PatrolAutopilotAcknowledgementDigest(record) {
+ return fmt.Errorf("patrol autopilot acknowledgement digest is invalid")
+ }
+ acknowledgementByID[record.ID] = record
+ }
+
+ revokedIDs := make(map[string]struct{}, len(revocations))
+ for _, record := range revocations {
+ acknowledgement, found := acknowledgementByID[record.AcknowledgementID]
+ if !found {
+ return fmt.Errorf("patrol autopilot revocation has no acknowledgement")
+ }
+ if _, duplicate := revokedIDs[record.AcknowledgementID]; duplicate {
+ return fmt.Errorf("patrol autopilot acknowledgement is revoked more than once")
+ }
+ if err := validatePatrolAutopilotRevocationForAcknowledgement(record, acknowledgement); err != nil {
+ return err
+ }
+ revokedIDs[record.AcknowledgementID] = struct{}{}
+ }
+
+ if activation != nil {
+ record := *activation
+ acknowledgement, found := acknowledgementByID[record.AcknowledgementID]
+ if !found {
+ return fmt.Errorf("patrol autopilot activation has no acknowledgement")
+ }
+ normalizedActor := NormalizeActionActor(record.Actor)
+ if record.Version != PatrolAutopilotActivationVersion || record.ActivatedAt.IsZero() || record.ActivatedAt.Before(acknowledgement.AcceptedAt) ||
+ (!acknowledgement.ExpiresAt.IsZero() && !record.ActivatedAt.Before(acknowledgement.ExpiresAt)) ||
+ record.AcknowledgementID != strings.TrimSpace(record.AcknowledgementID) || record.AcknowledgementDigest != strings.TrimSpace(record.AcknowledgementDigest) || record.OrgID != strings.TrimSpace(record.OrgID) || record.Actor != normalizedActor ||
+ ValidateActionActor(record.Actor) != nil || record.Actor.Kind != ActionActorUser || record.OrgID != acknowledgement.OrgID || record.Actor.OrgID != acknowledgement.OrgID ||
+ !ActionActorsEqual(record.Actor, acknowledgement.Actor) || record.AcknowledgementDigest != acknowledgement.Digest || record.Digest == "" || record.Digest != PatrolAutopilotActivationDigest(record) {
+ return fmt.Errorf("patrol autopilot activation binding is invalid")
+ }
+ }
+ return nil
+}
+
+func validatePatrolAutopilotRevocationForAcknowledgement(record PatrolAutopilotRevocation, acknowledgement PatrolAutopilotAcknowledgement) error {
+ normalizedActor := NormalizeActionActor(record.Actor)
+ if record.Version != PatrolAutopilotRevocationVersion || record.RevokedAt.IsZero() || record.RevokedAt.Before(acknowledgement.AcceptedAt) ||
+ record.AcknowledgementID != strings.TrimSpace(record.AcknowledgementID) || record.OrgID != strings.TrimSpace(record.OrgID) || record.Reason != strings.TrimSpace(record.Reason) || record.Actor != normalizedActor ||
+ ValidateActionActor(record.Actor) != nil || record.Actor.Kind != ActionActorUser || record.OrgID != acknowledgement.OrgID || record.Actor.OrgID != acknowledgement.OrgID ||
+ record.Digest == "" || record.Digest != PatrolAutopilotRevocationDigest(record) {
+ return fmt.Errorf("patrol autopilot revocation binding is invalid")
+ }
+ return nil
+}
+
+func IssuePatrolAutopilotAcknowledgement(existing []PatrolAutopilotAcknowledgement, acknowledgementID string, actor ActionActor, policy PatrolAutopilotServerPolicy) (PatrolAutopilotAcknowledgement, bool, error) {
+ acknowledgementID = strings.TrimSpace(acknowledgementID)
+ actor = NormalizeActionActor(actor)
+ policy, policyErr := normalizePatrolAutopilotServerPolicy(policy)
+ if policyErr != nil {
+ return PatrolAutopilotAcknowledgement{}, false, patrolAutopilotError(PatrolAutopilotStatusConflict, policyErr)
+ }
+ if !patrolAutopilotAcknowledgementIDPattern.MatchString(acknowledgementID) {
+ return PatrolAutopilotAcknowledgement{}, false, patrolAutopilotError(PatrolAutopilotStatusConflict, fmt.Errorf("invalid acknowledgement id"))
+ }
+ if err := ValidateActionActor(actor); err != nil || actor.Kind != ActionActorUser {
+ return PatrolAutopilotAcknowledgement{}, false, patrolAutopilotError(PatrolAutopilotStatusUserRequired, err)
+ }
+ contract, _ := PatrolAutopilotContractForVersion(policy.CurrentVersion)
+ expiresAt := time.Time{}
+ lifetime := contract.Lifetime
+ if policy.Lifetime > 0 {
+ lifetime = policy.Lifetime
+ }
+ if lifetime > 0 {
+ expiresAt = policy.Now.Add(lifetime)
+ }
+ for _, record := range existing {
+ if strings.TrimSpace(record.ID) != acknowledgementID {
+ continue
+ }
+ if record.Version == policy.CurrentVersion && record.OrgID == actor.OrgID && ActionActorsEqual(record.Actor, actor) && slices.Equal(record.AcceptedScope, contract.AcceptedScope) && record.AcceptedLimits == contract.AcceptedLimits && record.Digest == PatrolAutopilotAcknowledgementDigest(record) {
+ return record, false, nil
+ }
+ return PatrolAutopilotAcknowledgement{}, false, patrolAutopilotError(PatrolAutopilotStatusConflict, fmt.Errorf("acknowledgement id already bound"))
+ }
+ record := PatrolAutopilotAcknowledgement{
+ Version: policy.CurrentVersion,
+ ID: acknowledgementID,
+ OrgID: actor.OrgID,
+ Actor: actor,
+ AcceptedScope: append([]string(nil), contract.AcceptedScope...),
+ AcceptedLimits: contract.AcceptedLimits,
+ AcceptedAt: policy.Now,
+ ExpiresAt: expiresAt,
+ }
+ record.Digest = PatrolAutopilotAcknowledgementDigest(record)
+ return record, true, nil
+}
+
+func RevokePatrolAutopilotAcknowledgement(acknowledgements []PatrolAutopilotAcknowledgement, revocations []PatrolAutopilotRevocation, acknowledgementID string, actor ActionActor, reason string, policy PatrolAutopilotServerPolicy) (PatrolAutopilotRevocation, bool, error) {
+ acknowledgementID = strings.TrimSpace(acknowledgementID)
+ actor = NormalizeActionActor(actor)
+ reason = strings.TrimSpace(reason)
+ policy, policyErr := normalizePatrolAutopilotServerPolicy(policy)
+ if policyErr != nil {
+ return PatrolAutopilotRevocation{}, false, patrolAutopilotError(PatrolAutopilotStatusConflict, policyErr)
+ }
+ if err := ValidateActionActor(actor); err != nil || actor.Kind != ActionActorUser {
+ return PatrolAutopilotRevocation{}, false, patrolAutopilotError(PatrolAutopilotStatusUserRequired, err)
+ }
+ var acknowledgement *PatrolAutopilotAcknowledgement
+ for index := range acknowledgements {
+ if acknowledgements[index].ID == acknowledgementID {
+ acknowledgement = &acknowledgements[index]
+ break
+ }
+ }
+ if acknowledgement == nil || acknowledgement.OrgID != actor.OrgID {
+ return PatrolAutopilotRevocation{}, false, patrolAutopilotError(PatrolAutopilotStatusWrongOrg, fmt.Errorf("acknowledgement not found for organization"))
+ }
+ for _, revocation := range revocations {
+ if revocation.AcknowledgementID == acknowledgementID {
+ if revocation.Version == PatrolAutopilotRevocationVersion && revocation.OrgID == actor.OrgID && ActionActorsEqual(revocation.Actor, actor) && revocation.Reason == reason && revocation.Digest == PatrolAutopilotRevocationDigest(revocation) {
+ return revocation, false, nil
+ }
+ return PatrolAutopilotRevocation{}, false, patrolAutopilotError(PatrolAutopilotStatusConflict, fmt.Errorf("revocation already bound to different evidence"))
+ }
+ }
+ record := PatrolAutopilotRevocation{
+ Version: PatrolAutopilotRevocationVersion,
+ AcknowledgementID: acknowledgementID,
+ OrgID: actor.OrgID,
+ Actor: actor,
+ Reason: reason,
+ RevokedAt: policy.Now,
+ }
+ record.Digest = PatrolAutopilotRevocationDigest(record)
+ return record, true, nil
+}
+
+func BindPatrolAutopilotActivation(acknowledgements []PatrolAutopilotAcknowledgement, revocations []PatrolAutopilotRevocation, current *PatrolAutopilotActivation, acknowledgementID string, actor ActionActor, policy PatrolAutopilotServerPolicy) (PatrolAutopilotActivation, bool, error) {
+ actor = NormalizeActionActor(actor)
+ policy, policyErr := normalizePatrolAutopilotServerPolicy(policy)
+ if policyErr != nil {
+ return PatrolAutopilotActivation{}, false, patrolAutopilotError(PatrolAutopilotStatusConflict, policyErr)
+ }
+ if err := ValidateActionActor(actor); err != nil || actor.Kind != ActionActorUser {
+ return PatrolAutopilotActivation{}, false, patrolAutopilotError(PatrolAutopilotStatusUserRequired, err)
+ }
+ acknowledgement, status := ValidatePatrolAutopilotAcknowledgement(acknowledgements, revocations, acknowledgementID, actor.OrgID, &actor, policy)
+ if !status.Active {
+ return PatrolAutopilotActivation{}, false, patrolAutopilotError(status.Code, fmt.Errorf("acknowledgement is not eligible for activation"))
+ }
+ if current != nil && current.AcknowledgementID == acknowledgement.ID && current.AcknowledgementDigest == acknowledgement.Digest && current.OrgID == actor.OrgID && ActionActorsEqual(current.Actor, actor) && current.Digest == PatrolAutopilotActivationDigest(*current) {
+ return *current, false, nil
+ }
+ binding := PatrolAutopilotActivation{
+ Version: PatrolAutopilotActivationVersion,
+ AcknowledgementID: acknowledgement.ID,
+ AcknowledgementDigest: acknowledgement.Digest,
+ OrgID: actor.OrgID,
+ Actor: actor,
+ ActivatedAt: policy.Now,
+ }
+ binding.Digest = PatrolAutopilotActivationDigest(binding)
+ return binding, true, nil
+}
+
+func ValidatePatrolAutopilotAcknowledgement(acknowledgements []PatrolAutopilotAcknowledgement, revocations []PatrolAutopilotRevocation, acknowledgementID, orgID string, actor *ActionActor, policy PatrolAutopilotServerPolicy) (PatrolAutopilotAcknowledgement, PatrolAutopilotStatus) {
+ policy, policyErr := normalizePatrolAutopilotServerPolicy(policy)
+ if policyErr != nil {
+ return PatrolAutopilotAcknowledgement{}, newPatrolAutopilotStatus(PatrolAutopilotStatusConflict, PatrolAutopilotCurrentAcknowledgementVersion)
+ }
+ contract, _ := PatrolAutopilotContractForVersion(policy.CurrentVersion)
+ status := newPatrolAutopilotStatus(PatrolAutopilotStatusAcknowledgementRequired, policy.CurrentVersion)
+ acknowledgementID = strings.TrimSpace(acknowledgementID)
+ orgID = strings.TrimSpace(orgID)
+ var record *PatrolAutopilotAcknowledgement
+ for index := range acknowledgements {
+ if strings.TrimSpace(acknowledgements[index].ID) == acknowledgementID {
+ record = &acknowledgements[index]
+ break
+ }
+ }
+ if record == nil {
+ return PatrolAutopilotAcknowledgement{}, status
+ }
+ status.AcknowledgementID = record.ID
+ status.AcknowledgementVersion = record.Version
+ status.AcknowledgementDigest = record.Digest
+ status.AcknowledgedBy = record.Actor.SubjectID
+ status.AcceptedAt = record.AcceptedAt
+ status.ExpiresAt = record.ExpiresAt
+ if record.Version != policy.CurrentVersion || !slices.Equal(record.AcceptedScope, contract.AcceptedScope) || record.AcceptedLimits != contract.AcceptedLimits {
+ status.Code = PatrolAutopilotStatusStaleVersion
+ return *record, status
+ }
+ if record.OrgID != orgID || record.Actor.OrgID != orgID {
+ status.Code = PatrolAutopilotStatusWrongOrg
+ return *record, status
+ }
+ if err := ValidateActionActor(record.Actor); err != nil || record.Actor.Kind != ActionActorUser {
+ status.Code = PatrolAutopilotStatusUserRequired
+ return *record, status
+ }
+ if actor != nil && !ActionActorsEqual(record.Actor, NormalizeActionActor(*actor)) {
+ status.Code = PatrolAutopilotStatusWrongActor
+ return *record, status
+ }
+ if record.Digest == "" || record.Digest != PatrolAutopilotAcknowledgementDigest(*record) {
+ status.Code = PatrolAutopilotStatusDigestInvalid
+ return *record, status
+ }
+ if record.AcceptedAt.IsZero() || record.AcceptedAt.After(policy.Now) || (!record.ExpiresAt.IsZero() && (!record.ExpiresAt.After(record.AcceptedAt) || !policy.Now.Before(record.ExpiresAt))) {
+ status.Code = PatrolAutopilotStatusExpired
+ return *record, status
+ }
+ for _, revocation := range revocations {
+ if revocation.AcknowledgementID != record.ID {
+ continue
+ }
+ if revocation.OrgID != record.OrgID || NormalizeActionActor(revocation.Actor).OrgID != record.OrgID {
+ status.Code = PatrolAutopilotStatusWrongOrg
+ return *record, status
+ }
+ if err := validatePatrolAutopilotRevocationForAcknowledgement(revocation, *record); err != nil {
+ status.Code = PatrolAutopilotStatusDigestInvalid
+ return *record, status
+ }
+ status.Code = PatrolAutopilotStatusRevoked
+ return *record, status
+ }
+ status.Code = PatrolAutopilotStatusActive
+ status.Active = true
+ return *record, status
+}
+
+func EvaluatePatrolAutopilot(requestedMode, fallbackMode, orgID string, legacyUnlocked bool, acknowledgements []PatrolAutopilotAcknowledgement, revocations []PatrolAutopilotRevocation, activation *PatrolAutopilotActivation, policy PatrolAutopilotServerPolicy) (string, PatrolAutopilotStatus) {
+ policy, policyErr := normalizePatrolAutopilotServerPolicy(policy)
+ if policyErr != nil {
+ return fallbackMode, newPatrolAutopilotStatus(PatrolAutopilotStatusConflict, PatrolAutopilotCurrentAcknowledgementVersion)
+ }
+ if requestedMode != "full" {
+ return requestedMode, newPatrolAutopilotStatus(PatrolAutopilotStatusNotRequested, policy.CurrentVersion)
+ }
+ if activation == nil {
+ code := PatrolAutopilotStatusAcknowledgementRequired
+ if legacyUnlocked {
+ code = PatrolAutopilotStatusLegacyBooleanIgnored
+ }
+ return fallbackMode, newPatrolAutopilotStatus(code, policy.CurrentVersion)
+ }
+ if activation.Version != PatrolAutopilotActivationVersion || activation.Digest == "" || activation.Digest != PatrolAutopilotActivationDigest(*activation) {
+ return fallbackMode, newPatrolAutopilotStatus(PatrolAutopilotStatusActivationDigestInvalid, policy.CurrentVersion)
+ }
+ if activation.OrgID != strings.TrimSpace(orgID) || activation.Actor.OrgID != strings.TrimSpace(orgID) {
+ return fallbackMode, newPatrolAutopilotStatus(PatrolAutopilotStatusWrongOrg, policy.CurrentVersion)
+ }
+ if err := ValidateActionActor(activation.Actor); err != nil || activation.Actor.Kind != ActionActorUser {
+ return fallbackMode, newPatrolAutopilotStatus(PatrolAutopilotStatusUserRequired, policy.CurrentVersion)
+ }
+ acknowledgement, status := ValidatePatrolAutopilotAcknowledgement(acknowledgements, revocations, activation.AcknowledgementID, orgID, &activation.Actor, policy)
+ if !status.Active {
+ return fallbackMode, status
+ }
+ if activation.AcknowledgementDigest != acknowledgement.Digest {
+ status.Active = false
+ status.Code = PatrolAutopilotStatusDigestInvalid
+ return fallbackMode, status
+ }
+ status.Active = true
+ status.Code = PatrolAutopilotStatusActive
+ return requestedMode, status
+}
+
+func newPatrolAutopilotStatus(code string, currentVersion int) PatrolAutopilotStatus {
+ status := PatrolAutopilotStatus{
+ Code: code,
+ CurrentVersion: currentVersion,
+ }
+ if contract, supported := PatrolAutopilotContractForVersion(currentVersion); supported {
+ status.AcceptedScope = contract.AcceptedScope
+ status.AcceptedLimits = contract.AcceptedLimits
+ }
+ return status
+}
diff --git a/internal/unifiedresources/patrol_autopilot_test.go b/internal/unifiedresources/patrol_autopilot_test.go
new file mode 100644
index 0000000000..60caed173c
--- /dev/null
+++ b/internal/unifiedresources/patrol_autopilot_test.go
@@ -0,0 +1,206 @@
+package unifiedresources
+
+import (
+ "testing"
+ "time"
+)
+
+func patrolAutopilotTestActor(subject, credential, orgID string) ActionActor {
+ return ActionActor{SubjectID: subject, Kind: ActionActorUser, CredentialID: credential, OrgID: orgID}
+}
+
+func TestPatrolAutopilotContractRegistryOwnsSupportedVersionShapes(t *testing.T) {
+ v1, v1Supported := PatrolAutopilotContractForVersion(PatrolAutopilotAcknowledgementVersionV1)
+ v2, v2Supported := PatrolAutopilotContractForVersion(PatrolAutopilotAcknowledgementVersionV2)
+ if !v1Supported || !v2Supported {
+ t.Fatalf("supported contracts missing: v1=%v v2=%v", v1Supported, v2Supported)
+ }
+ if v1.Version != PatrolAutopilotAcknowledgementVersionV1 || v2.Version != PatrolAutopilotAcknowledgementVersionV2 || len(v1.AcceptedScope) == len(v2.AcceptedScope) || v1.AcceptedLimits == v2.AcceptedLimits {
+ t.Fatalf("versioned contracts are not distinct: v1=%#v v2=%#v", v1, v2)
+ }
+ if _, supported := PatrolAutopilotContractForVersion(99); supported {
+ t.Fatal("unsupported V99 contract was accepted")
+ }
+ if CurrentPatrolAutopilotServerPolicy(time.Now()).CurrentVersion != PatrolAutopilotCurrentAcknowledgementVersion {
+ t.Fatal("current version provider diverges from the server-owned current version")
+ }
+}
+
+func issuedPatrolAutopilotTestEvidence(t *testing.T, id string, actor ActionActor, policy PatrolAutopilotServerPolicy) (PatrolAutopilotAcknowledgement, PatrolAutopilotActivation) {
+ t.Helper()
+ acknowledgement, created, err := IssuePatrolAutopilotAcknowledgement(nil, id, actor, policy)
+ if err != nil || !created {
+ t.Fatalf("issue acknowledgement created=%v err=%v", created, err)
+ }
+ activation, created, err := BindPatrolAutopilotActivation([]PatrolAutopilotAcknowledgement{acknowledgement}, nil, nil, acknowledgement.ID, actor, policy)
+ if err != nil || !created {
+ t.Fatalf("bind activation created=%v err=%v", created, err)
+ }
+ return acknowledgement, activation
+}
+
+func TestPatrolAutopilotAcknowledgementExactRetryAndConflict(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ policy := CurrentPatrolAutopilotServerPolicy(now)
+ actor := patrolAutopilotTestActor("admin-one", "session:one", "org-a")
+ acknowledgement, created, err := IssuePatrolAutopilotAcknowledgement(nil, "ack-retry-0001", actor, policy)
+ if err != nil || !created {
+ t.Fatalf("first issue created=%v err=%v", created, err)
+ }
+ replayed, created, err := IssuePatrolAutopilotAcknowledgement([]PatrolAutopilotAcknowledgement{acknowledgement}, acknowledgement.ID, actor, PatrolAutopilotServerPolicy{CurrentVersion: policy.CurrentVersion, Now: now.Add(time.Minute)})
+ if err != nil || created || replayed.Digest != acknowledgement.Digest || !replayed.AcceptedAt.Equal(acknowledgement.AcceptedAt) {
+ t.Fatalf("exact replay created=%v err=%v record=%#v", created, err, replayed)
+ }
+ otherActor := patrolAutopilotTestActor("admin-two", "session:two", "org-a")
+ if _, _, err := IssuePatrolAutopilotAcknowledgement([]PatrolAutopilotAcknowledgement{acknowledgement}, acknowledgement.ID, otherActor, policy); PatrolAutopilotErrorCode(err) != PatrolAutopilotStatusConflict {
+ t.Fatalf("conflicting actor error=%v code=%q", err, PatrolAutopilotErrorCode(err))
+ }
+ otherOrg := patrolAutopilotTestActor("admin-one", "session:one", "org-b")
+ if _, _, err := IssuePatrolAutopilotAcknowledgement([]PatrolAutopilotAcknowledgement{acknowledgement}, acknowledgement.ID, otherOrg, policy); PatrolAutopilotErrorCode(err) != PatrolAutopilotStatusConflict {
+ t.Fatalf("cross-org reuse error=%v code=%q", err, PatrolAutopilotErrorCode(err))
+ }
+}
+
+func TestPatrolAutopilotRevocationRetryIsExact(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ policy := CurrentPatrolAutopilotServerPolicy(now)
+ actor := patrolAutopilotTestActor("admin-one", "session:one", "org-a")
+ acknowledgement, _ := issuedPatrolAutopilotTestEvidence(t, "ack-revoke-001", actor, policy)
+ revocation, created, err := RevokePatrolAutopilotAcknowledgement([]PatrolAutopilotAcknowledgement{acknowledgement}, nil, acknowledgement.ID, actor, "operator stop", policy)
+ if err != nil || !created {
+ t.Fatalf("first revocation created=%v err=%v", created, err)
+ }
+ replayed, created, err := RevokePatrolAutopilotAcknowledgement([]PatrolAutopilotAcknowledgement{acknowledgement}, []PatrolAutopilotRevocation{revocation}, acknowledgement.ID, actor, "operator stop", PatrolAutopilotServerPolicy{CurrentVersion: policy.CurrentVersion, Now: now.Add(time.Minute)})
+ if err != nil || created || replayed.Digest != revocation.Digest {
+ t.Fatalf("exact revocation replay created=%v err=%v", created, err)
+ }
+ for _, tc := range []struct {
+ name string
+ actor ActionActor
+ reason string
+ }{
+ {name: "different actor", actor: patrolAutopilotTestActor("admin-two", "session:two", "org-a"), reason: "operator stop"},
+ {name: "different credential", actor: patrolAutopilotTestActor("admin-one", "session:changed", "org-a"), reason: "operator stop"},
+ {name: "different reason", actor: actor, reason: "different request"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if _, _, err := RevokePatrolAutopilotAcknowledgement([]PatrolAutopilotAcknowledgement{acknowledgement}, []PatrolAutopilotRevocation{revocation}, acknowledgement.ID, tc.actor, tc.reason, policy); PatrolAutopilotErrorCode(err) != PatrolAutopilotStatusConflict {
+ t.Fatalf("error=%v code=%q", err, PatrolAutopilotErrorCode(err))
+ }
+ })
+ }
+}
+
+func TestEvaluatePatrolAutopilotFailsClosedForIneligibleEvidence(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ policy := CurrentPatrolAutopilotServerPolicy(now)
+ actor := patrolAutopilotTestActor("admin-one", "session:one", "org-a")
+ acknowledgement, activation := issuedPatrolAutopilotTestEvidence(t, "ack-negative-01", actor, policy)
+
+ tests := []struct {
+ name string
+ legacy bool
+ acknowledges []PatrolAutopilotAcknowledgement
+ revocations []PatrolAutopilotRevocation
+ activation *PatrolAutopilotActivation
+ orgID string
+ policy PatrolAutopilotServerPolicy
+ wantCode string
+ }{
+ {name: "no acknowledgement", activation: nil, orgID: "org-a", policy: policy, wantCode: PatrolAutopilotStatusAcknowledgementRequired},
+ {name: "legacy boolean", legacy: true, activation: nil, orgID: "org-a", policy: policy, wantCode: PatrolAutopilotStatusLegacyBooleanIgnored},
+ {name: "stale version", acknowledges: []PatrolAutopilotAcknowledgement{acknowledgement}, activation: &activation, orgID: "org-a", policy: PatrolAutopilotServerPolicy{CurrentVersion: 2, Now: now}, wantCode: PatrolAutopilotStatusStaleVersion},
+ {name: "wrong org", acknowledges: []PatrolAutopilotAcknowledgement{acknowledgement}, activation: &activation, orgID: "org-b", policy: policy, wantCode: PatrolAutopilotStatusWrongOrg},
+ {name: "wrong actor binding", acknowledges: []PatrolAutopilotAcknowledgement{acknowledgement}, activation: func() *PatrolAutopilotActivation {
+ record := activation
+ record.Actor.CredentialID = "session:other"
+ record.Digest = PatrolAutopilotActivationDigest(record)
+ return &record
+ }(), orgID: "org-a", policy: policy, wantCode: PatrolAutopilotStatusWrongActor},
+ {name: "tampered acknowledgement digest", acknowledges: []PatrolAutopilotAcknowledgement{func() PatrolAutopilotAcknowledgement {
+ record := acknowledgement
+ record.AcceptedScope = []string{"tampered"}
+ return record
+ }()}, activation: &activation, orgID: "org-a", policy: policy, wantCode: PatrolAutopilotStatusStaleVersion},
+ {name: "tampered activation digest", acknowledges: []PatrolAutopilotAcknowledgement{acknowledgement}, activation: func() *PatrolAutopilotActivation {
+ record := activation
+ record.AcknowledgementDigest = "sha256:tampered"
+ return &record
+ }(), orgID: "org-a", policy: policy, wantCode: PatrolAutopilotStatusActivationDigestInvalid},
+ }
+
+ expiringPolicy := PatrolAutopilotServerPolicy{CurrentVersion: 1, Now: now, Lifetime: time.Minute}
+ expiringAcknowledgement, expiringActivation := issuedPatrolAutopilotTestEvidence(t, "ack-expired-001", actor, expiringPolicy)
+ tests = append(tests, struct {
+ name string
+ legacy bool
+ acknowledges []PatrolAutopilotAcknowledgement
+ revocations []PatrolAutopilotRevocation
+ activation *PatrolAutopilotActivation
+ orgID string
+ policy PatrolAutopilotServerPolicy
+ wantCode string
+ }{name: "expired", acknowledges: []PatrolAutopilotAcknowledgement{expiringAcknowledgement}, activation: &expiringActivation, orgID: "org-a", policy: PatrolAutopilotServerPolicy{CurrentVersion: 1, Now: now.Add(2 * time.Minute)}, wantCode: PatrolAutopilotStatusExpired})
+
+ revocation, _, err := RevokePatrolAutopilotAcknowledgement([]PatrolAutopilotAcknowledgement{acknowledgement}, nil, acknowledgement.ID, actor, "stop", policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tests = append(tests, struct {
+ name string
+ legacy bool
+ acknowledges []PatrolAutopilotAcknowledgement
+ revocations []PatrolAutopilotRevocation
+ activation *PatrolAutopilotActivation
+ orgID string
+ policy PatrolAutopilotServerPolicy
+ wantCode string
+ }{name: "revoked", acknowledges: []PatrolAutopilotAcknowledgement{acknowledgement}, revocations: []PatrolAutopilotRevocation{revocation}, activation: &activation, orgID: "org-a", policy: policy, wantCode: PatrolAutopilotStatusRevoked})
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ effective, status := EvaluatePatrolAutopilot("full", "approval", tc.orgID, tc.legacy, tc.acknowledges, tc.revocations, tc.activation, tc.policy)
+ if effective != "approval" || status.Active || status.Code != tc.wantCode {
+ t.Fatalf("effective=%q status=%#v", effective, status)
+ }
+ })
+ }
+}
+
+func TestEvaluatePatrolAutopilotRejectsForeignMalformedRevocationWithoutVictimAttribution(t *testing.T) {
+ now := time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC)
+ policy := CurrentPatrolAutopilotServerPolicy(now)
+ actor := patrolAutopilotTestActor("admin-one", "session:one", "org-a")
+ acknowledgement, activation := issuedPatrolAutopilotTestEvidence(t, "ack-foreign-revoke", actor, policy)
+ foreign := PatrolAutopilotRevocation{
+ Version: PatrolAutopilotRevocationVersion,
+ AcknowledgementID: acknowledgement.ID,
+ OrgID: "org-b",
+ Actor: patrolAutopilotTestActor("admin-two", "session:two", "org-b"),
+ Reason: "foreign mutation",
+ RevokedAt: now.Add(time.Minute),
+ }
+ foreign.Digest = PatrolAutopilotRevocationDigest(foreign)
+
+ effective, status := EvaluatePatrolAutopilot("full", "approval", "org-a", false, []PatrolAutopilotAcknowledgement{acknowledgement}, []PatrolAutopilotRevocation{foreign}, &activation, PatrolAutopilotServerPolicy{CurrentVersion: 1, Now: now.Add(2 * time.Minute)})
+ if effective != "approval" || status.Active || status.Code != PatrolAutopilotStatusWrongOrg {
+ t.Fatalf("foreign revocation was accepted or attributed to victim: effective=%q status=%#v", effective, status)
+ }
+}
+
+func TestPatrolAutopilotRequiresHumanActorAndHonestOutcomeLimits(t *testing.T) {
+ policy := CurrentPatrolAutopilotServerPolicy(time.Date(2026, 7, 11, 20, 0, 0, 0, time.UTC))
+ tokenActor := ActionActor{SubjectID: "admin-one", Kind: ActionActorAPIToken, CredentialID: "api-token:one", OrgID: "org-a"}
+ if _, _, err := IssuePatrolAutopilotAcknowledgement(nil, "ack-token-0001", tokenActor, policy); PatrolAutopilotErrorCode(err) != PatrolAutopilotStatusUserRequired {
+ t.Fatalf("token acknowledgement error=%v code=%q", err, PatrolAutopilotErrorCode(err))
+ }
+ limits := CurrentPatrolAutopilotAcceptedLimits()
+ if !limits.VerificationReconciledWhenSupported || !limits.EvidenceClassDisclosed || !limits.InconclusiveOutcomeAllowed || !limits.ExecutionSuccessIsNotOutcomeTruth {
+ t.Fatalf("accepted limits overstate or omit outcome truth: %#v", limits)
+ }
+ for _, scope := range CurrentPatrolAutopilotAcceptedScope() {
+ if scope == "verified_outcomes" {
+ t.Fatal("accepted scope must not promise universal verified outcomes")
+ }
+ }
+}
diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.py
index a1f730786e..4cb8c2241a 100644
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@ -1022,6 +1022,7 @@ class CanonicalCompletionGuardTest(unittest.TestCase):
"exact_files": [
"frontend-modern/src/types/api.ts",
"internal/api/contract_test.go",
+ "internal/api/patrol_autopilot_test.go",
],
}
],
@@ -2182,6 +2183,62 @@ None yet.
)
self.assertEqual(matches, ["frontend-modern/src/api/__tests__/alerts.test.ts"])
+ def test_patrol_autopilot_runtime_accepts_only_dedicated_verification(self):
+ rules = {rule["id"]: rule for rule in load_subsystem_rules()}
+ cases = [
+ (
+ "ai-runtime",
+ "internal/api/ai_handlers.go",
+ "ai-api-surface",
+ "internal/api/patrol_autopilot_test.go",
+ ),
+ (
+ "api-contracts",
+ "internal/api/ai_handlers.go",
+ "backend-payload-contracts",
+ "internal/api/patrol_autopilot_test.go",
+ ),
+ (
+ "ai-runtime",
+ "internal/config/ai.go",
+ "ai-runtime-config",
+ "internal/config/patrol_autopilot_persistence_test.go",
+ ),
+ (
+ "ai-runtime",
+ "internal/config/patrol_autopilot_persistence.go",
+ "ai-runtime-config",
+ "internal/config/patrol_autopilot_persistence_test.go",
+ ),
+ (
+ "unified-resources",
+ "internal/unifiedresources/patrol_autopilot.go",
+ "patrol-autopilot-runtime",
+ "internal/unifiedresources/patrol_autopilot_test.go",
+ ),
+ ]
+
+ for subsystem_id, runtime_path, requirement_id, proof_path in cases:
+ with self.subTest(subsystem=subsystem_id, runtime=runtime_path):
+ rule = rules[subsystem_id]
+ requirement = next(
+ requirement
+ for requirement in build_verification_requirements(rule, [runtime_path])
+ if requirement["id"] == requirement_id
+ )
+ self.assertEqual(
+ staged_verification_files_for_requirement(
+ rule,
+ requirement,
+ [proof_path],
+ ),
+ [proof_path],
+ )
+ self.assertEqual(
+ staged_verification_files_for_requirement(rule, requirement, []),
+ [],
+ )
+
def test_explicit_coverage_gap_uses_registry_path_policy_requirement(self):
synthetic_rule = {
"id": "synthetic",
diff --git a/scripts/release_control/registry_audit_test.py b/scripts/release_control/registry_audit_test.py
index 8406cee10b..f72260d2b0 100644
--- a/scripts/release_control/registry_audit_test.py
+++ b/scripts/release_control/registry_audit_test.py
@@ -1,3 +1,4 @@
+import copy
import os
import subprocess
import tempfile
@@ -42,6 +43,99 @@ class RegistryAuditTest(unittest.TestCase):
self.assertTrue(args.check)
self.assertTrue(args.staged)
+ def test_patrol_autopilot_registry_uses_dedicated_proof_and_rejects_drift(self) -> None:
+ registry = registry_audit.load_registry_payload()
+ rules = {rule["id"]: rule for rule in registry["subsystems"]}
+
+ ai_policies = {
+ policy["id"]: policy for policy in rules["ai-runtime"]["verification"]["path_policies"]
+ }
+ self.assertIn(
+ "internal/api/patrol_autopilot_test.go",
+ ai_policies["ai-api-surface"]["exact_files"],
+ )
+ self.assertEqual(
+ ai_policies["ai-runtime-config"]["match_files"],
+ [
+ "internal/config/ai.go",
+ "internal/config/patrol_autopilot_persistence.go",
+ ],
+ )
+ self.assertIn(
+ "internal/config/patrol_autopilot_persistence_test.go",
+ ai_policies["ai-runtime-config"]["exact_files"],
+ )
+
+ api_policy = next(
+ policy
+ for policy in rules["api-contracts"]["verification"]["path_policies"]
+ if policy["id"] == "backend-payload-contracts"
+ )
+ self.assertIn("internal/api/patrol_autopilot_test.go", api_policy["exact_files"])
+
+ patrol_policy = next(
+ policy
+ for policy in rules["unified-resources"]["verification"]["path_policies"]
+ if policy["id"] == "patrol-autopilot-runtime"
+ )
+ self.assertEqual(
+ patrol_policy["match_files"],
+ ["internal/unifiedresources/patrol_autopilot.go"],
+ )
+ self.assertEqual(
+ patrol_policy["exact_files"],
+ ["internal/unifiedresources/patrol_autopilot_test.go"],
+ )
+
+ payload = {
+ "version": 13,
+ "shared_ownerships": [],
+ "subsystems": [
+ {
+ "id": "unified-resources",
+ "lane": "L13",
+ "contract": "docs/release-control/v6/internal/subsystems/unified-resources.md",
+ "owned_prefixes": ["internal/unifiedresources/"],
+ "owned_files": [],
+ "verification": {
+ "allow_same_subsystem_tests": False,
+ "test_prefixes": [],
+ "exact_files": [],
+ "require_explicit_path_policy_coverage": True,
+ "path_policies": [copy.deepcopy(patrol_policy)],
+ },
+ }
+ ],
+ }
+ tracked = {
+ "docs/release-control/v6/internal/subsystems/unified-resources.md",
+ "internal/unifiedresources/patrol_autopilot.go",
+ "internal/unifiedresources/patrol_autopilot_test.go",
+ }
+ report = audit_registry_payload(payload, tracked_files=tracked, status_lane_ids={"L13"})
+ self.assertEqual(report["errors"], [])
+
+ missing_proof = audit_registry_payload(
+ payload,
+ tracked_files=tracked - {"internal/unifiedresources/patrol_autopilot_test.go"},
+ status_lane_ids={"L13"},
+ )
+ self.assertIn(
+ "internal/unifiedresources/patrol_autopilot_test.go",
+ "\n".join(missing_proof["errors"]),
+ )
+
+ drifted = copy.deepcopy(payload)
+ drifted["subsystems"][0]["verification"]["path_policies"][0]["match_files"] = [
+ "internal/unifiedresources/other.go"
+ ]
+ drifted_report = audit_registry_payload(
+ drifted,
+ tracked_files=tracked | {"internal/unifiedresources/other.go"},
+ status_lane_ids={"L13"},
+ )
+ self.assertIn("patrol_autopilot.go", "\n".join(drifted_report["errors"]))
+
def test_tracked_workspace_files_uses_linked_worktree_as_canonical_local_repo(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
workspace = Path(tmpdir) / "workspace"
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 16763fa892..b568ab0129 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -1161,7 +1161,58 @@ class SubsystemLookupTest(unittest.TestCase):
self.assertEqual(match["contract"], "docs/release-control/v6/internal/subsystems/ai-runtime.md")
self.assertEqual(match["lane_context"]["lane_id"], "L6")
self.assertEqual(match["verification_requirement"]["id"], "ai-runtime-config")
- self.assertEqual(match["verification_requirement"]["exact_files"], ["internal/config/ai_config_test.go"])
+ self.assertEqual(
+ match["verification_requirement"]["exact_files"],
+ [
+ "internal/config/ai_config_test.go",
+ "internal/config/patrol_autopilot_persistence_test.go",
+ ],
+ )
+
+ def test_lookup_paths_selects_dedicated_patrol_autopilot_proof(self) -> None:
+ result = lookup_paths(
+ [
+ "internal/api/ai_handlers.go",
+ "internal/config/patrol_autopilot_persistence.go",
+ "internal/unifiedresources/patrol_autopilot.go",
+ ]
+ )
+ self.assertEqual(result["unowned_runtime_files"], [])
+
+ api_matches = {
+ match["subsystem"]: match["verification_requirement"]
+ for match in result["files"][0]["matches"]
+ }
+ self.assertEqual(set(api_matches), {"ai-runtime", "api-contracts"})
+ self.assertEqual(api_matches["ai-runtime"]["id"], "ai-api-surface")
+ self.assertEqual(api_matches["api-contracts"]["id"], "backend-payload-contracts")
+ self.assertIn(
+ "internal/api/patrol_autopilot_test.go",
+ api_matches["ai-runtime"]["exact_files"],
+ )
+ self.assertIn(
+ "internal/api/patrol_autopilot_test.go",
+ api_matches["api-contracts"]["exact_files"],
+ )
+
+ config_match = result["files"][1]["matches"][0]
+ self.assertEqual(config_match["subsystem"], "ai-runtime")
+ self.assertEqual(config_match["verification_requirement"]["id"], "ai-runtime-config")
+ self.assertIn(
+ "internal/config/patrol_autopilot_persistence_test.go",
+ config_match["verification_requirement"]["exact_files"],
+ )
+
+ unified_match = result["files"][2]["matches"][0]
+ self.assertEqual(unified_match["subsystem"], "unified-resources")
+ self.assertEqual(
+ unified_match["verification_requirement"]["id"],
+ "patrol-autopilot-runtime",
+ )
+ self.assertEqual(
+ unified_match["verification_requirement"]["exact_files"],
+ ["internal/unifiedresources/patrol_autopilot_test.go"],
+ )
def test_lookup_paths_reports_notification_client_as_shared_boundary(self) -> None:
result = lookup_paths(["frontend-modern/src/api/notifications.ts"])