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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Add durable Patrol objectives
rcourtman903b579f8aa2
diff --git a/docs/API.md b/docs/API.mdindex 0864f6b488..92c89dc3c1 100644--- a/docs/API.md+++ b/docs/API.md@@ -1131,6 +1131,22 @@ Runs a focused investigation for an alert payload (used by the UI).- `GET /api/ai/patrol/status`- `GET /api/ai/patrol/findings`- `DELETE /api/ai/patrol/findings` (clear all findings)+- `GET /api/ai/patrol/objectives`+- `POST /api/ai/patrol/objectives`+- `GET /api/ai/patrol/objectives/{id}`+- `PATCH /api/ai/patrol/objectives/{id}`+- `DELETE /api/ai/patrol/objectives/{id}?revision={revision}`+ - Objective writes accept an outcome-oriented `brief`, optional+ `optional_context`, and optional canonical `resource_ids`. `PATCH` also+ accepts `status` (`active`, `paused`, or `archived`) and requires the+ current `revision` in its JSON body.+ - Responses include server-derived `coverage` (`covered`, `degraded`, or+ `uncovered`) and observer lifecycle state. Clients cannot submit either+ field or mark an objective covered. A saved objective remains uncovered+ until core records a validated, installed read-only observer with a live+ health lease.+ - Reads and writes require `ai:execute`. Stale writes return+ `409 patrol_objective_revision_conflict`.- `GET /api/ai/patrol/history`- `GET /api/ai/patrol/runs`- `GET /api/ai/patrol/stream` (Pro)diff --git a/docs/PRIVACY.md b/docs/PRIVACY.mdindex 2509873659..30c84b2e27 100644--- a/docs/PRIVACY.md+++ b/docs/PRIVACY.md@@ -256,6 +256,6 @@ The telemetry implementation is in [`internal/telemetry/telemetry.go`](../internPulse can make outbound connections when you enable specific features:-- **AI providers**: when AI features are configured, Pulse sends only the context required for your request to the provider you chose. Local providers stay on your network; non-local hosted providers receive provider-bound context directly from your Pulse instance. AI prompts from self-managed installs do not transit Pulse infrastructure. Before non-local model requests leave the instance, governed resource details use the same resource-policy redaction shown in Data Handling: local-only resource details are omitted from detailed prompt sections or replaced with policy-safe summaries, and known restricted resource identifiers are redacted where they appear in provider-bound context. See `docs/AI.md`.+- **AI providers**: when AI features are configured, Pulse sends only the context required for your request to the provider you chose. This can include active Patrol objective briefs and their optional operator context when they apply to a Patrol run. Those retained objectives are encrypted at rest in the local organization data directory; saving one does not itself call a model, and objective text is not included in Pulse usage telemetry or audit messages. Local providers stay on your network; non-local hosted providers receive provider-bound context directly from your Pulse instance. AI prompts from self-managed installs do not transit Pulse infrastructure. Before non-local model requests leave the instance, governed resource details use the same resource-policy redaction shown in Data Handling: local-only resource details are omitted from detailed prompt sections or replaced with policy-safe summaries, and known restricted resource identifiers are redacted where they appear in provider-bound context. See `docs/AI.md`.- **Relay / Remote Access**: when relay is enabled, Pulse connects to the configured relay endpoint to enable secure remote web access, Pulse Mobile pairing for handoff, and push notifications. See Settings → Remote Access.- **Update checks**: Pulse can check for new releases/updates (for example via GitHub release metadata) depending on your deployment and configuration.diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 5c5b04634b..cd2422756f 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -1741,6 +1741,13 @@ the intentionally sparse public response.4. Keep shared agent-side TLS identity fail-closed across `cmd/pulse-agent/main.go`, `internal/hostagent/`, `internal/agentupdate/`, `internal/remoteconfig/client.go`, and `internal/agenttls/config.go`. Self-signed deployments may use a canonical pinned Pulse server certificate fingerprint, but lifecycle transport must route that pin through reporting, enrollment, command websocket, remote-config, and self-update clients instead of widening `PULSE_INSECURE_SKIP_VERIFY` into a blanket MITM carve-out. A configured custom CA bundle is part of that same trust boundary: if the bundle is unreadable or invalid, lifecycle transport must refuse the connection path rather than silently downgrading back to system roots.5. Keep release-grade updater trust fail-closed across `internal/agentupdate/`, `internal/dockeragent/`, and the shared `internal/api/unified_agent.go` download helpers. When release builds embed trusted update signing keys, published agent binaries and installer assets must carry detached `.sig` plus `.sshsig` sidecars; updater/runtime paths must require `X-Signature-Ed25519` in addition to `X-Checksum-Sha256`, and installer-owned download flows must require the matching base64-encoded `X-Signature-SSHSIG`, instead of silently downgrading to checksum-only trust.6. Keep shared `internal/api/` helper edits isolated from agent lifecycle semantics: Patrol-specific status transport or alert-trigger wiring changes in shared handlers must not bleed into auto-register, installer, or fleet-control behavior unless this contract moves in the same slice.+ The same isolation rule applies to retained Patrol objective routes under+ `internal/api/`: objective briefs, resource scope, optimistic revisions,+ derived observer coverage, and observer-health state are AI/runtime plus+ API-contract facts. Agent lifecycle surfaces must not reinterpret an+ objective or observer record as agent enrollment, install state, command+ connectivity, profile assignment, update readiness, setup-token scope, or+ infrastructure mutation authority.Commercial migration startup behavior in`internal/api/licensing_handlers.go` and `internal/api/licensing_bridge.go`remains a cloud-paid/API concern. Suppressing synthetic mock-licensediff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 5920e4f7b6..d8fbf0c89c 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -395,9 +395,32 @@ batch, and it retains parallel execution for independent reads and independentfinding writes. This makes the existing read-before-write guard deterministicwithout requiring the model to understand an internal goroutine schedule.+Patrol operational objectives are durable organization-scoped operator intent,+not prompts that exist only for one provider session. Core persists the brief,+optional context, canonical resource scope, lifecycle revision, and internal+observer record in `ai_patrol_objectives.enc` under the tenant data directory;+the file must decrypt successfully before any objective is loaded. Active+objectives are added to full and scoped Patrol seed context as desired outcomes,+not as trusted scripts or tool instructions. Scoped runs receive global+objectives plus only objectives whose canonical resource IDs intersect the+effective scope. Provider-bound resource-policy sanitization remains the final+transport boundary for the resulting context.++Objective coverage is core-derived. Saving intent starts `uncovered`; neither a+client nor a model may write `covered`. Coverage becomes `covered` only for an+internally recorded, read-only observer that traversed+`proposed -> validated -> installed` and holds an unexpired health lease. A+missing lease, expired lease, or observer failure is `degraded`; paused,+archived, missing, proposed, validated-but-uninstalled, and disabled observers+are `uncovered`. Observer artifact identity, SHA-256 digest, declared bounded+trigger kinds, version, state transitions, and machine failure code are+validated and persisted by core. Observer authority never includes an+infrastructure mutation capability.+## Canonical Files1. `internal/ai/`+ 1g. `internal/ai/patrol_objectives.go`1e. `internal/ai/attention.go`1f. `internal/ai/patrol_metrics.go`1a. `cmd/pulse-mcp/main.go`diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex d0453bb428..1154502634 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -53,6 +53,16 @@ reopen path for a dismissed Patrol finding. It removes the finding-backedsuppression row, preserves the operator note, clears dismissal state in boththe Patrol and unified stores, and returns not-found when the row is notcurrently dismissed or suppressed.+`GET` and `POST /api/ai/patrol/objectives` plus `GET`, `PATCH`, and `DELETE`+on `/api/ai/patrol/objectives/{id}` are the authenticated `ai:execute` contract+for retained Patrol intent. The write payload accepts a bounded outcome brief,+optional bounded context, and optional canonical resource IDs; updates and+deletes require the current non-zero revision and stale writes return the stable+`409 patrol_objective_revision_conflict` envelope. The response includes+server-derived `coverage` and the internal observer lifecycle for honest status,+but public request schemas do not accept either field. Unknown fields, trailing+JSON, over-limit bodies, unsupported statuses, and malformed scope entries fail+closed. Objective text is never copied into audit messages.Physical-disk payloads preserve optional SMART counter presence, includingexplicit zero values, and expose provider vendor metadata without convertingmissing data into health. Unified-resource clients may request bounded server@@ -202,6 +212,7 @@ continues to mint and quote the enrollment token.78. `frontend-modern/src/api/aiChat.ts`69a. `frontend-modern/src/api/aiChatDevStreamFixture.ts`79. `frontend-modern/src/api/patrol.ts`+ 79a. `internal/api/patrol_objectives.go`80. `frontend-modern/src/api/generated/aiChatEvents.ts`81. `internal/api/agent_exec_token_binding.go`72a. `cmd/pulse-mcp/main.go`diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.mdindex 883c42c9f2..88d005f15f 100644--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md@@ -128,6 +128,15 @@ with bounded provenance and rollback; app-named integration code is anoptimization only when repeated evidence justifies productizing it, never aprerequisite for a new objective.+The first canonical runtime slice is implemented by+`internal/ai/patrol_objectives.go` and `internal/api/patrol_objectives.go`.+It provides encrypted retained intent, optimistic revisions, resource scoping,+model seed projection, and the core-owned observer state machine. The public API+deliberately cannot attach an observer or author coverage. The monitor-building,+validation, sandbox installation, event delivery, and redesign executor remains+an extension of this lifecycle; until one records a healthy installed observer,+the saved objective truthfully remains uncovered.+Desktop Autopilot activation consumes the server-owned acknowledgementcontract through `frontend-modern/src/api/patrol.ts` and`PatrolAutopilotAcknowledgementDialog.tsx`. The UI displays requested versusdiff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex c0500c543d..8aec865044 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -48,6 +48,17 @@ configuration. It may override Pulse's automatic filesystem suppression only;it must not override a matching operator exclusion or introduce remoteauthority to expand the reported filesystem set silently.+Retained Patrol objective briefs and optional context are operator-authored AI+content. They are encrypted at rest in the organization-scoped Pulse data+directory and loading fails closed if decryption fails. Audit and telemetry+records must not contain the brief, optional context, observer artifact,+resource identifiers, or health evidence. Audit records may include the+objective ID; usage telemetry may include only content-free aggregate lifecycle+counts. When Patrol is enabled, applicable active objective text becomes part+of the context sent to the configured AI provider under the same local-provider+and non-local provider-bound resource-policy redaction rules as other Patrol+context. Merely saving an objective makes no outbound model request.+## Canonical Files1. `SECURITY.md`diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex aa29b14733..240afe69fc 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -1177,6 +1177,11 @@ recovery scope, or a storage/recovery-owned secret source.hosted diagnostics do not collapse into false free-tier behavior.19. Preserve shipped local security-doc guidance in shared `internal/api/` config/setup helpers so storage- and recovery-adjacent transport surfaces do not reintroduce GitHub `main` security links when the running build already serves its own local security documentation route.20. Keep shared `internal/api/` Patrol transport and alert-trigger edits feature-isolated: Patrol-specific recency fields, callback fan-out, or alert-bridge wiring changes must not leak into recovery queries, storage links, or recovery-adjacent install/setup flows unless this contract changes in the same slice.+ Retained Patrol objective routes follow the same adjacency rule. A brief,+ canonical resource scope, observer lifecycle, or derived coverage state is+ AI/runtime plus API-contract context; storage and recovery consumers must not+ treat it as backup evidence, restore coverage, storage health, recovery-point+ identity, restore authority, or proof that a protected-system observer exists.The same adjacency rule applies to AI settings transport in `internal/api/ai_handlers.go`: provider auth state, masked-secret payload fields, provider-test model selection, safe provider preflight diagnostics, and legacy Anthropic OAuth cleanup fields remain AI/runtime plus API-contract concerns and must not be absorbed into storage/recovery transport ownership just because those handlers live under the shared backend API tree. Storage/recovery-adjacent consumers may preserve or clear legacy OAuth tokens only through the shared AI settings owner; they must not treat stored OAuth tokens or `auth_method=oauth` as recovery capability, provider readiness, restore authority, or an AI-backed storage support signal.Patrol readiness labels on the same settings payload, including theuser-facing Patrol control label for the stable `configuration` check ID,diff --git a/frontend-modern/public/docs/API.md b/frontend-modern/public/docs/API.mdindex 0864f6b488..92c89dc3c1 100644--- a/frontend-modern/public/docs/API.md+++ b/frontend-modern/public/docs/API.md@@ -1131,6 +1131,22 @@ Runs a focused investigation for an alert payload (used by the UI).- `GET /api/ai/patrol/status`- `GET /api/ai/patrol/findings`- `DELETE /api/ai/patrol/findings` (clear all findings)+- `GET /api/ai/patrol/objectives`+- `POST /api/ai/patrol/objectives`+- `GET /api/ai/patrol/objectives/{id}`+- `PATCH /api/ai/patrol/objectives/{id}`+- `DELETE /api/ai/patrol/objectives/{id}?revision={revision}`+ - Objective writes accept an outcome-oriented `brief`, optional+ `optional_context`, and optional canonical `resource_ids`. `PATCH` also+ accepts `status` (`active`, `paused`, or `archived`) and requires the+ current `revision` in its JSON body.+ - Responses include server-derived `coverage` (`covered`, `degraded`, or+ `uncovered`) and observer lifecycle state. Clients cannot submit either+ field or mark an objective covered. A saved objective remains uncovered+ until core records a validated, installed read-only observer with a live+ health lease.+ - Reads and writes require `ai:execute`. Stale writes return+ `409 patrol_objective_revision_conflict`.- `GET /api/ai/patrol/history`- `GET /api/ai/patrol/runs`- `GET /api/ai/patrol/stream` (Pro)diff --git a/frontend-modern/public/docs/PRIVACY.md b/frontend-modern/public/docs/PRIVACY.mdindex 2509873659..30c84b2e27 100644--- a/frontend-modern/public/docs/PRIVACY.md+++ b/frontend-modern/public/docs/PRIVACY.md@@ -256,6 +256,6 @@ The telemetry implementation is in [`internal/telemetry/telemetry.go`](../internPulse can make outbound connections when you enable specific features:-- **AI providers**: when AI features are configured, Pulse sends only the context required for your request to the provider you chose. Local providers stay on your network; non-local hosted providers receive provider-bound context directly from your Pulse instance. AI prompts from self-managed installs do not transit Pulse infrastructure. Before non-local model requests leave the instance, governed resource details use the same resource-policy redaction shown in Data Handling: local-only resource details are omitted from detailed prompt sections or replaced with policy-safe summaries, and known restricted resource identifiers are redacted where they appear in provider-bound context. See `docs/AI.md`.+- **AI providers**: when AI features are configured, Pulse sends only the context required for your request to the provider you chose. This can include active Patrol objective briefs and their optional operator context when they apply to a Patrol run. Those retained objectives are encrypted at rest in the local organization data directory; saving one does not itself call a model, and objective text is not included in Pulse usage telemetry or audit messages. Local providers stay on your network; non-local hosted providers receive provider-bound context directly from your Pulse instance. AI prompts from self-managed installs do not transit Pulse infrastructure. Before non-local model requests leave the instance, governed resource details use the same resource-policy redaction shown in Data Handling: local-only resource details are omitted from detailed prompt sections or replaced with policy-safe summaries, and known restricted resource identifiers are redacted where they appear in provider-bound context. See `docs/AI.md`.- **Relay / Remote Access**: when relay is enabled, Pulse connects to the configured relay endpoint to enable secure remote web access, Pulse Mobile pairing for handoff, and push notifications. See Settings → Remote Access.- **Update checks**: Pulse can check for new releases/updates (for example via GitHub release metadata) depending on your deployment and configuration.diff --git a/frontend-modern/src/stores/__tests__/systemSettings.test.ts b/frontend-modern/src/stores/__tests__/systemSettings.test.tsindex 62423ac173..91ede1611f 100644--- a/frontend-modern/src/stores/__tests__/systemSettings.test.ts+++ b/frontend-modern/src/stores/__tests__/systemSettings.test.ts@@ -117,6 +117,9 @@ describe('systemSettings store', () => {expect(privacyDoc).toContain('rows older than **90 days** are purged automatically');expect(privacyDoc).toContain('uses request IP addresses transiently for abuse/rate limiting');expect(privacyDoc).toContain('Reset ID');+ expect(privacyDoc).toContain('active Patrol objective briefs');+ expect(privacyDoc).toContain('encrypted at rest in the local organization data directory');+ expect(privacyDoc).toContain('objective text is not included in Pulse usage telemetry');expect(privacyDoc).toContain('Pulse Intelligence Patrol control completed operations loop 30d');expect(privacyDoc).toContain('Pulse Intelligence Patrol control paid resolved operations loop 30d',diff --git a/frontend-modern/src/utils/__tests__/docsLinks.test.ts b/frontend-modern/src/utils/__tests__/docsLinks.test.tsindex 7bfdb15660..729d12854d 100644--- a/frontend-modern/src/utils/__tests__/docsLinks.test.ts+++ b/frontend-modern/src/utils/__tests__/docsLinks.test.ts@@ -153,6 +153,21 @@ describe('docsLinks', () => {expect(importContract).toContain('settings:write');});+ it('ships the truthful Patrol objective API contract', () => {+ const apiReference = readFileSync(path.join(repoRoot, 'docs', 'API.md'), 'utf8');+ const shippedAPIReference = readFileSync(+ path.join(frontendRoot, 'public', 'docs', 'API.md'),+ 'utf8',+ );++ expect(shippedAPIReference).toBe(apiReference);+ expect(apiReference).toContain('`POST /api/ai/patrol/objectives`');+ expect(apiReference).toContain('`PATCH /api/ai/patrol/objectives/{id}`');+ expect(apiReference).toContain('Clients cannot submit either');+ expect(apiReference).toContain('validated, installed read-only observer with a live');+ expect(apiReference).toContain('`409 patrol_objective_revision_conflict`');+ });+it('routes runtime docs links through shipped local docs instead of GitHub main', () => {expect(apiAccessPanelSource).toContain('API_TOKEN_SCOPES_DOC_URL');expect(apiAccessPanelSource).not.toContain(diff --git a/internal/ai/patrol.go b/internal/ai/patrol.goindex 8f937fcd9b..65f73def0e 100644--- a/internal/ai/patrol.go+++ b/internal/ai/patrol.go@@ -468,6 +468,7 @@ type PatrolService struct {thresholdProvider ThresholdProviderconfig PatrolConfigfindings *FindingsStore+ objectiveStore *PatrolObjectiveStoreknowledgeStore *knowledge.Store // For per-resource notes in patrol contextdiscoveryStore *servicediscovery.Store // For AI-discovered infrastructure contextguestProber GuestProber // For pre-patrol guest reachability checksdiff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.goindex 26f8f2c607..6fe6e7ca0e 100644--- a/internal/ai/patrol_ai.go+++ b/internal/ai/patrol_ai.go@@ -1492,6 +1492,7 @@ func (p *PatrolService) buildTriageSeedSectionsState(sections := []seedSection{// P0 — always include.{priority: 0, name: "triage_overview", content: formatTriageOverviewSection(triage)},+ {priority: 0, name: "operator_objectives", content: p.seedPatrolObjectives(sortedScopedIDs(seedSet), scope != nil, now)},{priority: 0, name: "findings", content: findingsCtx},{priority: 0, name: "health_alerts", content: p.seedHealthAndAlertsState(snap, seedSet, cfg, now)},{priority: 0, name: "scope", content: buildScopeSection(scope, sortedScopedIDs(seedSet))},@@ -1540,6 +1541,7 @@ func (p *PatrolService) buildSeedSectionsState(snap patrolRuntimeState, scope *Psections := []seedSection{// P0 — always include.+ {priority: 0, name: "operator_objectives", content: p.seedPatrolObjectives(effectiveScopeIDs, scope != nil, now)},{priority: 0, name: "findings", content: findingsCtx},{priority: 0, name: "health_alerts", content: p.seedHealthAndAlertsState(snap, scopedSet, cfg, now)},{priority: 0, name: "scope", content: buildScopeSection(scope, effectiveScopeIDs)},diff --git a/internal/ai/patrol_init.go b/internal/ai/patrol_init.goindex 569d3183f6..d4ca516a72 100644--- a/internal/ai/patrol_init.go+++ b/internal/ai/patrol_init.go@@ -382,6 +382,22 @@ func (p *PatrolService) GetThresholds() PatrolThresholds {return p.thresholds}+// SetObjectiveStore attaches the durable operator-intent store. Objective+// state is read-only from the Patrol loop; create/update/delete ownership stays+// on the authenticated API, and observer state stays on the constrained core+// monitor-builder/installer boundary.+func (p *PatrolService) SetObjectiveStore(store *PatrolObjectiveStore) {+ p.mu.Lock()+ defer p.mu.Unlock()+ p.objectiveStore = store+}++func (p *PatrolService) GetObjectiveStore() *PatrolObjectiveStore {+ p.mu.RLock()+ defer p.mu.RUnlock()+ return p.objectiveStore+}+// SetFindingsPersistence enables findings persistence (load from and save to disk)// This should be called before Start() to load any existing findingsfunc (p *PatrolService) SetFindingsPersistence(persistence FindingsPersistence) error {diff --git a/internal/ai/patrol_objectives.go b/internal/ai/patrol_objectives.gonew file mode 100644index 0000000000..ec06725c3f--- /dev/null+++ b/internal/ai/patrol_objectives.go@@ -0,0 +1,976 @@+package ai++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "sync"+ "time"+ "unicode"+ "unicode/utf8"++ "github.com/google/uuid"+ "github.com/rcourtman/pulse-go-rewrite/internal/crypto"+ "github.com/rcourtman/pulse-go-rewrite/internal/securityutil"+)++const (+ patrolObjectiveDocumentVersion = 1+ MaxPatrolObjectives = 256+ MaxActivePatrolObjectives = 64+ MaxPatrolObjectiveBriefBytes = 2 * 1024+ MaxPatrolObjectiveContextBytes = 4 * 1024+ MaxPatrolObjectiveResourceIDs = 64+ MaxPatrolObserverTriggerKinds = 8+)++var (+ ErrPatrolObjectiveNotFound = errors.New("patrol objective not found")+ ErrPatrolObjectiveConflict = errors.New("patrol objective revision conflict")+ ErrPatrolObjectiveLimit = errors.New("patrol objective limit reached")+ ErrPatrolObjectiveInvalid = errors.New("invalid patrol objective")+)++type PatrolObjectiveStatus string++const (+ PatrolObjectiveActive PatrolObjectiveStatus = "active"+ PatrolObjectivePaused PatrolObjectiveStatus = "paused"+ PatrolObjectiveArchived PatrolObjectiveStatus = "archived"+)++type PatrolObjectiveCoverageState string++const (+ PatrolObjectiveCovered PatrolObjectiveCoverageState = "covered"+ PatrolObjectiveDegraded PatrolObjectiveCoverageState = "degraded"+ PatrolObjectiveUncovered PatrolObjectiveCoverageState = "uncovered"+)++type PatrolObserverState string++const (+ PatrolObserverProposed PatrolObserverState = "proposed"+ PatrolObserverValidated PatrolObserverState = "validated"+ PatrolObserverInstalled PatrolObserverState = "installed"+ PatrolObserverDegraded PatrolObserverState = "degraded"+ PatrolObserverDisabled PatrolObserverState = "disabled"+)++type PatrolObserverTriggerKind string++const (+ PatrolObserverTriggerEvent PatrolObserverTriggerKind = "event"+ PatrolObserverTriggerWebhook PatrolObserverTriggerKind = "webhook"+ PatrolObserverTriggerLog PatrolObserverTriggerKind = "log"+ PatrolObserverTriggerFile PatrolObserverTriggerKind = "file"+ PatrolObserverTriggerSocket PatrolObserverTriggerKind = "socket"+ PatrolObserverTriggerAPI PatrolObserverTriggerKind = "api"+ PatrolObserverTriggerInterval PatrolObserverTriggerKind = "interval"+)++type PatrolObjectiveScope struct {+ ResourceIDs []string `json:"resource_ids"`+}++type PatrolObserverRecord struct {+ ID string `json:"id"`+ Version uint64 `json:"version"`+ State PatrolObserverState `json:"state"`+ ArtifactDigest string `json:"artifact_digest"`+ TriggerKinds []PatrolObserverTriggerKind `json:"trigger_kinds"`+ ReadOnly bool `json:"read_only"`+ ValidUntil *time.Time `json:"valid_until,omitempty"`+ LastEvidenceAt *time.Time `json:"last_evidence_at,omitempty"`+ FailureCode string `json:"failure_code,omitempty"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+}++type PatrolObjectiveCoverage struct {+ State PatrolObjectiveCoverageState `json:"state"`+ ReasonCode string `json:"reason_code"`+ Summary string `json:"summary"`+ ObserverID string `json:"observer_id,omitempty"`+ ObserverVersion uint64 `json:"observer_version,omitempty"`+ ValidUntil *time.Time `json:"valid_until,omitempty"`+ LastEvidenceAt *time.Time `json:"last_evidence_at,omitempty"`+}++type PatrolObjective struct {+ ID string `json:"id"`+ Brief string `json:"brief"`+ OptionalContext string `json:"optional_context,omitempty"`+ Scope PatrolObjectiveScope `json:"scope"`+ Status PatrolObjectiveStatus `json:"status"`+ Coverage PatrolObjectiveCoverage `json:"coverage"`+ Observer *PatrolObserverRecord `json:"observer,omitempty"`+ Revision uint64 `json:"revision"`+ CreatedBy string `json:"created_by,omitempty"`+ UpdatedBy string `json:"updated_by,omitempty"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+}++type CreatePatrolObjectiveInput struct {+ Brief string+ OptionalContext string+ ResourceIDs []string+ Actor string+}++type UpdatePatrolObjectiveInput struct {+ ExpectedRevision uint64+ Brief *string+ OptionalContext *string+ ResourceIDs *[]string+ Status *PatrolObjectiveStatus+ Actor string+}++type patrolObjectiveDocument struct {+ Version int `json:"version"`+ LastSaved time.Time `json:"last_saved"`+ Objectives []*PatrolObjective `json:"objectives"`+}++type PatrolObjectiveStore struct {+ mu sync.RWMutex+ objectives map[string]*PatrolObjective+ filePath string+ crypto *crypto.CryptoManager+}++func NewInMemoryPatrolObjectiveStore() *PatrolObjectiveStore {+ return &PatrolObjectiveStore{objectives: make(map[string]*PatrolObjective)}+}++func NewPatrolObjectiveStore(dataDir string) (*PatrolObjectiveStore, error) {+ normalizedDir, err := securityutil.NormalizeStorageDir(dataDir)+ if err != nil {+ return nil, fmt.Errorf("resolve patrol objective storage: %w", err)+ }+ if err := os.MkdirAll(normalizedDir, 0o700); err != nil {+ return nil, fmt.Errorf("prepare patrol objective storage: %w", err)+ }+ filePath, err := securityutil.JoinStorageLeaf(normalizedDir, "ai_patrol_objectives.enc")+ if err != nil {+ return nil, fmt.Errorf("resolve patrol objective file: %w", err)+ }+ cryptoManager, err := crypto.NewCryptoManagerAt(normalizedDir)+ if err != nil {+ return nil, fmt.Errorf("initialize patrol objective encryption: %w", err)+ }+ store := &PatrolObjectiveStore{+ objectives: make(map[string]*PatrolObjective),+ filePath: filePath,+ crypto: cryptoManager,+ }+ if err := store.load(); err != nil {+ return nil, err+ }+ return store, nil+}++func (s *PatrolObjectiveStore) load() error {+ if s == nil || s.filePath == "" {+ return nil+ }+ data, err := os.ReadFile(s.filePath)+ if err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ return fmt.Errorf("read patrol objectives: %w", err)+ }+ if s.crypto == nil {+ return errors.New("patrol objective encryption unavailable")+ }+ data, err = s.crypto.Decrypt(data)+ if err != nil {+ return fmt.Errorf("decrypt patrol objectives: %w", err)+ }+ var document patrolObjectiveDocument+ if err := json.Unmarshal(data, &document); err != nil {+ return fmt.Errorf("decode patrol objectives: %w", err)+ }+ if document.Version != patrolObjectiveDocumentVersion {+ return fmt.Errorf("unsupported patrol objective document version %d", document.Version)+ }+ if len(document.Objectives) > MaxPatrolObjectives {+ return fmt.Errorf("patrol objective document exceeds limit")+ }+ loaded := make(map[string]*PatrolObjective, len(document.Objectives))+ for _, raw := range document.Objectives {+ objective, normalizeErr := normalizeStoredPatrolObjective(raw)+ if normalizeErr != nil {+ return normalizeErr+ }+ if _, exists := loaded[objective.ID]; exists {+ return fmt.Errorf("duplicate patrol objective id %q", objective.ID)+ }+ loaded[objective.ID] = objective+ }+ s.objectives = loaded+ return nil+}++func (s *PatrolObjectiveStore) List(includeArchived bool, now time.Time) []PatrolObjective {+ if s == nil {+ return []PatrolObjective{}+ }+ now = normalizePatrolObjectiveTime(now)+ s.mu.RLock()+ defer s.mu.RUnlock()+ result := make([]PatrolObjective, 0, len(s.objectives))+ for _, objective := range s.objectives {+ if !includeArchived && objective.Status == PatrolObjectiveArchived {+ continue+ }+ result = append(result, objectiveForRead(objective, now))+ }+ sort.Slice(result, func(i, j int) bool {+ if result[i].Status != result[j].Status {+ return patrolObjectiveStatusRank(result[i].Status) < patrolObjectiveStatusRank(result[j].Status)+ }+ if !result[i].UpdatedAt.Equal(result[j].UpdatedAt) {+ return result[i].UpdatedAt.After(result[j].UpdatedAt)+ }+ return result[i].ID < result[j].ID+ })+ return result+}++func (s *PatrolObjectiveStore) Get(id string, now time.Time) (PatrolObjective, bool) {+ if s == nil {+ return PatrolObjective{}, false+ }+ id = strings.TrimSpace(id)+ now = normalizePatrolObjectiveTime(now)+ s.mu.RLock()+ defer s.mu.RUnlock()+ objective, ok := s.objectives[id]+ if !ok {+ return PatrolObjective{}, false+ }+ return objectiveForRead(objective, now), true+}++func (s *PatrolObjectiveStore) Create(input CreatePatrolObjectiveInput, now time.Time) (PatrolObjective, error) {+ if s == nil {+ return PatrolObjective{}, fmt.Errorf("%w: store unavailable", ErrPatrolObjectiveInvalid)+ }+ now = normalizePatrolObjectiveTime(now)+ brief, optionalContext, resourceIDs, err := normalizePatrolObjectiveInput(input.Brief, input.OptionalContext, input.ResourceIDs)+ if err != nil {+ return PatrolObjective{}, err+ }+ actor := normalizePatrolObjectiveActor(input.Actor)++ s.mu.Lock()+ defer s.mu.Unlock()+ if len(s.objectives) >= MaxPatrolObjectives || countNonArchivedPatrolObjectives(s.objectives) >= MaxActivePatrolObjectives {+ return PatrolObjective{}, ErrPatrolObjectiveLimit+ }+ objective := &PatrolObjective{+ ID: "objective-" + uuid.NewString(),+ Brief: brief,+ OptionalContext: optionalContext,+ Scope: PatrolObjectiveScope{ResourceIDs: resourceIDs},+ Status: PatrolObjectiveActive,+ Revision: 1,+ CreatedBy: actor,+ UpdatedBy: actor,+ CreatedAt: now,+ UpdatedAt: now,+ }+ next := clonePatrolObjectiveMap(s.objectives)+ next[objective.ID] = clonePatrolObjective(objective)+ if err := s.persistLocked(next); err != nil {+ return PatrolObjective{}, err+ }+ s.objectives = next+ return objectiveForRead(objective, now), nil+}++func (s *PatrolObjectiveStore) Update(id string, input UpdatePatrolObjectiveInput, now time.Time) (PatrolObjective, error) {+ if s == nil {+ return PatrolObjective{}, fmt.Errorf("%w: store unavailable", ErrPatrolObjectiveInvalid)+ }+ id = strings.TrimSpace(id)+ now = normalizePatrolObjectiveTime(now)+ if input.ExpectedRevision == 0 {+ return PatrolObjective{}, fmt.Errorf("%w: expected revision is required", ErrPatrolObjectiveInvalid)+ }+ if input.Brief == nil && input.OptionalContext == nil && input.ResourceIDs == nil && input.Status == nil {+ return PatrolObjective{}, fmt.Errorf("%w: no changes supplied", ErrPatrolObjectiveInvalid)+ }++ s.mu.Lock()+ defer s.mu.Unlock()+ current, ok := s.objectives[id]+ if !ok {+ return PatrolObjective{}, ErrPatrolObjectiveNotFound+ }+ if current.Revision != input.ExpectedRevision {+ return PatrolObjective{}, ErrPatrolObjectiveConflict+ }+ updated := clonePatrolObjective(current)+ if input.Brief != nil {+ brief, err := normalizePatrolObjectiveText(*input.Brief, MaxPatrolObjectiveBriefBytes, false)+ if err != nil {+ return PatrolObjective{}, fmt.Errorf("%w: brief %v", ErrPatrolObjectiveInvalid, err)+ }+ updated.Brief = brief+ }+ if input.OptionalContext != nil {+ contextText, err := normalizePatrolObjectiveText(*input.OptionalContext, MaxPatrolObjectiveContextBytes, true)+ if err != nil {+ return PatrolObjective{}, fmt.Errorf("%w: optional context %v", ErrPatrolObjectiveInvalid, err)+ }+ updated.OptionalContext = contextText+ }+ if input.ResourceIDs != nil {+ resourceIDs, err := normalizePatrolObjectiveResourceIDs(*input.ResourceIDs)+ if err != nil {+ return PatrolObjective{}, err+ }+ updated.Scope.ResourceIDs = resourceIDs+ }+ if input.Status != nil {+ if !isPatrolObjectiveStatus(*input.Status) {+ return PatrolObjective{}, fmt.Errorf("%w: unsupported status", ErrPatrolObjectiveInvalid)+ }+ if current.Status == PatrolObjectiveArchived && *input.Status != PatrolObjectiveArchived && countNonArchivedPatrolObjectives(s.objectives) >= MaxActivePatrolObjectives {+ return PatrolObjective{}, ErrPatrolObjectiveLimit+ }+ updated.Status = *input.Status+ }+ updated.UpdatedBy = normalizePatrolObjectiveActor(input.Actor)+ updated.UpdatedAt = now+ updated.Revision+++ next := clonePatrolObjectiveMap(s.objectives)+ next[id] = updated+ if err := s.persistLocked(next); err != nil {+ return PatrolObjective{}, err+ }+ s.objectives = next+ return objectiveForRead(updated, now), nil+}++func (s *PatrolObjectiveStore) Delete(id string, expectedRevision uint64) error {+ if s == nil {+ return fmt.Errorf("%w: store unavailable", ErrPatrolObjectiveInvalid)+ }+ id = strings.TrimSpace(id)+ if expectedRevision == 0 {+ return fmt.Errorf("%w: expected revision is required", ErrPatrolObjectiveInvalid)+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ current, ok := s.objectives[id]+ if !ok {+ return ErrPatrolObjectiveNotFound+ }+ if current.Revision != expectedRevision {+ return ErrPatrolObjectiveConflict+ }+ next := clonePatrolObjectiveMap(s.objectives)+ delete(next, id)+ if err := s.persistLocked(next); err != nil {+ return err+ }+ s.objectives = next+ return nil+}++// RecordObserver persists a core-owned observer lifecycle transition. Public+// objective clients cannot call this method through HTTP. A future constrained+// monitor builder and installer must use it only after validating the observer+// artifact, declared read-only posture, triggers, and health lease.+func (s *PatrolObjectiveStore) RecordObserver(id string, expectedRevision uint64, observer PatrolObserverRecord, actor string, now time.Time) (PatrolObjective, error) {+ if s == nil {+ return PatrolObjective{}, fmt.Errorf("%w: store unavailable", ErrPatrolObjectiveInvalid)+ }+ id = strings.TrimSpace(id)+ now = normalizePatrolObjectiveTime(now)+ if expectedRevision == 0 {+ return PatrolObjective{}, fmt.Errorf("%w: expected revision is required", ErrPatrolObjectiveInvalid)+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ current, ok := s.objectives[id]+ if !ok {+ return PatrolObjective{}, ErrPatrolObjectiveNotFound+ }+ if current.Revision != expectedRevision {+ return PatrolObjective{}, ErrPatrolObjectiveConflict+ }+ observer, err := normalizePatrolObserver(observer, now)+ if err != nil {+ return PatrolObjective{}, err+ }+ if current.Observer != nil && observer.ID == current.Observer.ID && observer.Version == current.Observer.Version {+ observer.CreatedAt = current.Observer.CreatedAt+ } else {+ observer.CreatedAt = now+ }+ if err := validatePatrolObserverTransition(current.Observer, observer); err != nil {+ return PatrolObjective{}, err+ }+ updated := clonePatrolObjective(current)+ updated.Observer = clonePatrolObserver(&observer)+ updated.UpdatedBy = normalizePatrolObjectiveActor(actor)+ updated.UpdatedAt = now+ updated.Revision+++ next := clonePatrolObjectiveMap(s.objectives)+ next[id] = updated+ if err := s.persistLocked(next); err != nil {+ return PatrolObjective{}, err+ }+ s.objectives = next+ return objectiveForRead(updated, now), nil+}++func (s *PatrolObjectiveStore) persistLocked(objectives map[string]*PatrolObjective) error {+ if s.filePath == "" {+ return nil+ }+ ordered := make([]*PatrolObjective, 0, len(objectives))+ for _, objective := range objectives {+ copy := clonePatrolObjective(objective)+ copy.Coverage = PatrolObjectiveCoverage{}+ ordered = append(ordered, copy)+ }+ sort.Slice(ordered, func(i, j int) bool { return ordered[i].ID < ordered[j].ID })+ document := patrolObjectiveDocument{+ Version: patrolObjectiveDocumentVersion,+ LastSaved: time.Now().UTC(),+ Objectives: ordered,+ }+ data, err := json.MarshalIndent(document, "", " ")+ if err != nil {+ return fmt.Errorf("encode patrol objectives: %w", err)+ }+ if s.crypto != nil {+ data, err = s.crypto.Encrypt(data)+ if err != nil {+ return fmt.Errorf("encrypt patrol objectives: %w", err)+ }+ }+ if err := os.MkdirAll(filepath.Dir(s.filePath), 0o700); err != nil {+ return fmt.Errorf("prepare patrol objective directory: %w", err)+ }+ tempFile, err := os.CreateTemp(filepath.Dir(s.filePath), ".ai_patrol_objectives-*.tmp")+ if err != nil {+ return fmt.Errorf("create patrol objective transaction: %w", err)+ }+ tempPath := tempFile.Name()+ removeTemp := true+ defer func() {+ _ = tempFile.Close()+ if removeTemp {+ _ = os.Remove(tempPath)+ }+ }()+ if err := tempFile.Chmod(0o600); err != nil {+ return fmt.Errorf("secure patrol objective transaction: %w", err)+ }+ if _, err := tempFile.Write(data); err != nil {+ return fmt.Errorf("write patrol objectives: %w", err)+ }+ if err := tempFile.Sync(); err != nil {+ return fmt.Errorf("sync patrol objectives: %w", err)+ }+ if err := tempFile.Close(); err != nil {+ return fmt.Errorf("close patrol objective transaction: %w", err)+ }+ if err := os.Rename(tempPath, s.filePath); err != nil {+ return fmt.Errorf("commit patrol objectives: %w", err)+ }+ removeTemp = false+ if directory, openErr := os.Open(filepath.Dir(s.filePath)); openErr == nil {+ _ = directory.Sync()+ _ = directory.Close()+ }+ return nil+}++func objectiveForRead(objective *PatrolObjective, now time.Time) PatrolObjective {+ copy := clonePatrolObjective(objective)+ copy.Coverage = derivePatrolObjectiveCoverage(copy, now)+ return *copy+}++func derivePatrolObjectiveCoverage(objective *PatrolObjective, now time.Time) PatrolObjectiveCoverage {+ if objective == nil {+ return PatrolObjectiveCoverage{State: PatrolObjectiveUncovered, ReasonCode: "objective_missing", Summary: "Objective is unavailable."}+ }+ switch objective.Status {+ case PatrolObjectivePaused:+ return PatrolObjectiveCoverage{State: PatrolObjectiveUncovered, ReasonCode: "objective_paused", Summary: "Objective is paused."}+ case PatrolObjectiveArchived:+ return PatrolObjectiveCoverage{State: PatrolObjectiveUncovered, ReasonCode: "objective_archived", Summary: "Objective is archived."}+ }+ observer := objective.Observer+ if observer == nil {+ return PatrolObjectiveCoverage{State: PatrolObjectiveUncovered, ReasonCode: "observer_missing", Summary: "No durable observer has been installed."}+ }+ coverage := PatrolObjectiveCoverage{+ ObserverID: observer.ID,+ ObserverVersion: observer.Version,+ ValidUntil: clonePatrolTime(observer.ValidUntil),+ LastEvidenceAt: clonePatrolTime(observer.LastEvidenceAt),+ }+ switch observer.State {+ case PatrolObserverProposed:+ coverage.State = PatrolObjectiveUncovered+ coverage.ReasonCode = "observer_proposed"+ coverage.Summary = "An observer has been proposed but not validated or installed."+ case PatrolObserverValidated:+ coverage.State = PatrolObjectiveUncovered+ coverage.ReasonCode = "observer_not_installed"+ coverage.Summary = "The observer is validated but not installed."+ case PatrolObserverInstalled:+ switch {+ case observer.ValidUntil == nil:+ coverage.State = PatrolObjectiveDegraded+ coverage.ReasonCode = "observer_health_unknown"+ coverage.Summary = "The observer is installed but has no current health lease."+ case !observer.ValidUntil.After(now):+ coverage.State = PatrolObjectiveDegraded+ coverage.ReasonCode = "observer_stale"+ coverage.Summary = "The observer health lease has expired."+ default:+ coverage.State = PatrolObjectiveCovered+ coverage.ReasonCode = "observer_healthy"+ coverage.Summary = "A healthy read-only observer is installed."+ }+ case PatrolObserverDegraded:+ coverage.State = PatrolObjectiveDegraded+ coverage.ReasonCode = observer.FailureCode+ if coverage.ReasonCode == "" {+ coverage.ReasonCode = "observer_degraded"+ }+ coverage.Summary = "The installed observer needs attention."+ case PatrolObserverDisabled:+ coverage.State = PatrolObjectiveUncovered+ coverage.ReasonCode = "observer_disabled"+ coverage.Summary = "The observer is disabled."+ default:+ coverage.State = PatrolObjectiveUncovered+ coverage.ReasonCode = "observer_state_unknown"+ coverage.Summary = "Observer coverage cannot be established."+ }+ return coverage+}++func normalizeStoredPatrolObjective(raw *PatrolObjective) (*PatrolObjective, error) {+ if raw == nil {+ return nil, fmt.Errorf("%w: nil persisted objective", ErrPatrolObjectiveInvalid)+ }+ copy := clonePatrolObjective(raw)+ copy.ID = strings.TrimSpace(copy.ID)+ if copy.ID == "" || len(copy.ID) > 128 || containsUnsafePatrolText(copy.ID) {+ return nil, fmt.Errorf("%w: invalid persisted objective id", ErrPatrolObjectiveInvalid)+ }+ brief, optionalContext, resourceIDs, err := normalizePatrolObjectiveInput(copy.Brief, copy.OptionalContext, copy.Scope.ResourceIDs)+ if err != nil {+ return nil, err+ }+ if !isPatrolObjectiveStatus(copy.Status) || copy.Revision == 0 || copy.CreatedAt.IsZero() || copy.UpdatedAt.IsZero() || copy.UpdatedAt.Before(copy.CreatedAt) {+ return nil, fmt.Errorf("%w: invalid persisted objective lifecycle", ErrPatrolObjectiveInvalid)+ }+ copy.Brief = brief+ copy.OptionalContext = optionalContext+ copy.Scope.ResourceIDs = resourceIDs+ copy.CreatedAt = copy.CreatedAt.UTC()+ copy.UpdatedAt = copy.UpdatedAt.UTC()+ copy.CreatedBy = normalizePatrolObjectiveActor(copy.CreatedBy)+ copy.UpdatedBy = normalizePatrolObjectiveActor(copy.UpdatedBy)+ copy.Coverage = PatrolObjectiveCoverage{}+ if copy.Observer != nil {+ observer, err := normalizePatrolObserver(*copy.Observer, copy.Observer.UpdatedAt)+ if err != nil {+ return nil, err+ }+ if observer.UpdatedAt.Before(observer.CreatedAt) {+ return nil, fmt.Errorf("%w: invalid persisted observer lifecycle", ErrPatrolObjectiveInvalid)+ }+ copy.Observer = &observer+ }+ return copy, nil+}++func normalizePatrolObjectiveInput(brief, optionalContext string, resourceIDs []string) (string, string, []string, error) {+ normalizedBrief, err := normalizePatrolObjectiveText(brief, MaxPatrolObjectiveBriefBytes, false)+ if err != nil {+ return "", "", nil, fmt.Errorf("%w: brief %v", ErrPatrolObjectiveInvalid, err)+ }+ normalizedContext, err := normalizePatrolObjectiveText(optionalContext, MaxPatrolObjectiveContextBytes, true)+ if err != nil {+ return "", "", nil, fmt.Errorf("%w: optional context %v", ErrPatrolObjectiveInvalid, err)+ }+ normalizedResourceIDs, err := normalizePatrolObjectiveResourceIDs(resourceIDs)+ if err != nil {+ return "", "", nil, err+ }+ return normalizedBrief, normalizedContext, normalizedResourceIDs, nil+}++func normalizePatrolObjectiveText(value string, maxBytes int, allowEmpty bool) (string, error) {+ value = strings.Join(strings.Fields(strings.TrimSpace(value)), " ")+ if value == "" && !allowEmpty {+ return "", errors.New("is required")+ }+ if len(value) > maxBytes {+ return "", fmt.Errorf("exceeds %d bytes", maxBytes)+ }+ if containsUnsafePatrolText(value) {+ return "", errors.New("contains unsupported control characters")+ }+ return value, nil+}++func normalizePatrolObjectiveResourceIDs(resourceIDs []string) ([]string, error) {+ if len(resourceIDs) > MaxPatrolObjectiveResourceIDs {+ return nil, fmt.Errorf("%w: too many resource ids", ErrPatrolObjectiveInvalid)+ }+ seen := make(map[string]struct{}, len(resourceIDs))+ result := make([]string, 0, len(resourceIDs))+ for _, raw := range resourceIDs {+ id := strings.TrimSpace(raw)+ if id == "" || len(id) > 256 || containsUnsafePatrolText(id) {+ return nil, fmt.Errorf("%w: invalid resource id", ErrPatrolObjectiveInvalid)+ }+ if _, exists := seen[id]; exists {+ continue+ }+ seen[id] = struct{}{}+ result = append(result, id)+ }+ sort.Strings(result)+ if result == nil {+ result = []string{}+ }+ return result, nil+}++func normalizePatrolObserver(observer PatrolObserverRecord, now time.Time) (PatrolObserverRecord, error) {+ observer.ID = strings.TrimSpace(observer.ID)+ observer.ArtifactDigest = strings.ToLower(strings.TrimSpace(observer.ArtifactDigest))+ observer.FailureCode = strings.ToLower(strings.TrimSpace(observer.FailureCode))+ if observer.ID == "" || len(observer.ID) > 128 || containsUnsafePatrolText(observer.ID) || observer.Version == 0 {+ return PatrolObserverRecord{}, fmt.Errorf("%w: invalid observer identity", ErrPatrolObjectiveInvalid)+ }+ if !isPatrolObserverState(observer.State) {+ return PatrolObserverRecord{}, fmt.Errorf("%w: invalid observer state", ErrPatrolObjectiveInvalid)+ }+ if !observer.ReadOnly {+ return PatrolObserverRecord{}, fmt.Errorf("%w: observers must be read-only", ErrPatrolObjectiveInvalid)+ }+ if !isPatrolArtifactDigest(observer.ArtifactDigest) {+ return PatrolObserverRecord{}, fmt.Errorf("%w: observer artifact digest must be sha256", ErrPatrolObjectiveInvalid)+ }+ triggerKinds, err := normalizePatrolObserverTriggerKinds(observer.TriggerKinds)+ if err != nil {+ return PatrolObserverRecord{}, err+ }+ observer.TriggerKinds = triggerKinds+ if observer.FailureCode != "" && !isPatrolMachineCode(observer.FailureCode) {+ return PatrolObserverRecord{}, fmt.Errorf("%w: invalid observer failure code", ErrPatrolObjectiveInvalid)+ }+ if observer.State == PatrolObserverDegraded && observer.FailureCode == "" {+ return PatrolObserverRecord{}, fmt.Errorf("%w: degraded observer requires a failure code", ErrPatrolObjectiveInvalid)+ }+ if observer.State != PatrolObserverDegraded {+ observer.FailureCode = ""+ }+ observer.ValidUntil = clonePatrolTime(observer.ValidUntil)+ observer.LastEvidenceAt = clonePatrolTime(observer.LastEvidenceAt)+ if observer.ValidUntil != nil {+ value := observer.ValidUntil.UTC()+ observer.ValidUntil = &value+ }+ if observer.LastEvidenceAt != nil {+ value := observer.LastEvidenceAt.UTC()+ if value.After(now.Add(time.Minute)) {+ return PatrolObserverRecord{}, fmt.Errorf("%w: observer evidence time is in the future", ErrPatrolObjectiveInvalid)+ }+ observer.LastEvidenceAt = &value+ }+ if observer.CreatedAt.IsZero() {+ observer.CreatedAt = now+ }+ observer.CreatedAt = observer.CreatedAt.UTC()+ observer.UpdatedAt = now+ return observer, nil+}++func validatePatrolObserverTransition(current *PatrolObserverRecord, next PatrolObserverRecord) error {+ if current == nil {+ if next.State != PatrolObserverProposed {+ return fmt.Errorf("%w: first observer state must be proposed", ErrPatrolObjectiveInvalid)+ }+ return nil+ }+ if next.ID != current.ID || next.Version > current.Version {+ if next.Version <= current.Version || next.State != PatrolObserverProposed {+ return fmt.Errorf("%w: new observer revision must advance the version and start proposed", ErrPatrolObjectiveInvalid)+ }+ return nil+ }+ if next.Version != current.Version || next.ArtifactDigest != current.ArtifactDigest || !equalPatrolTriggerKinds(next.TriggerKinds, current.TriggerKinds) {+ return fmt.Errorf("%w: observer identity and artifact are immutable within a version", ErrPatrolObjectiveInvalid)+ }+ allowed := map[PatrolObserverState]map[PatrolObserverState]bool{+ PatrolObserverProposed: {PatrolObserverProposed: true, PatrolObserverValidated: true, PatrolObserverDisabled: true},+ PatrolObserverValidated: {PatrolObserverValidated: true, PatrolObserverInstalled: true, PatrolObserverDegraded: true, PatrolObserverDisabled: true},+ PatrolObserverInstalled: {PatrolObserverInstalled: true, PatrolObserverDegraded: true, PatrolObserverDisabled: true},+ PatrolObserverDegraded: {PatrolObserverDegraded: true, PatrolObserverInstalled: true, PatrolObserverDisabled: true},+ PatrolObserverDisabled: {PatrolObserverDisabled: true},+ }+ if !allowed[current.State][next.State] {+ return fmt.Errorf("%w: invalid observer state transition", ErrPatrolObjectiveInvalid)+ }+ return nil+}++func normalizePatrolObserverTriggerKinds(values []PatrolObserverTriggerKind) ([]PatrolObserverTriggerKind, error) {+ if len(values) == 0 || len(values) > MaxPatrolObserverTriggerKinds {+ return nil, fmt.Errorf("%w: observer must declare bounded trigger kinds", ErrPatrolObjectiveInvalid)+ }+ seen := make(map[PatrolObserverTriggerKind]struct{}, len(values))+ result := make([]PatrolObserverTriggerKind, 0, len(values))+ for _, value := range values {+ if !isPatrolObserverTriggerKind(value) {+ return nil, fmt.Errorf("%w: invalid observer trigger kind", ErrPatrolObjectiveInvalid)+ }+ if _, exists := seen[value]; exists {+ continue+ }+ seen[value] = struct{}{}+ result = append(result, value)+ }+ sort.Slice(result, func(i, j int) bool { return result[i] < result[j] })+ return result, nil+}++func isPatrolObjectiveStatus(status PatrolObjectiveStatus) bool {+ switch status {+ case PatrolObjectiveActive, PatrolObjectivePaused, PatrolObjectiveArchived:+ return true+ default:+ return false+ }+}++func isPatrolObserverState(state PatrolObserverState) bool {+ switch state {+ case PatrolObserverProposed, PatrolObserverValidated, PatrolObserverInstalled, PatrolObserverDegraded, PatrolObserverDisabled:+ return true+ default:+ return false+ }+}++func isPatrolObserverTriggerKind(kind PatrolObserverTriggerKind) bool {+ switch kind {+ case PatrolObserverTriggerEvent, PatrolObserverTriggerWebhook, PatrolObserverTriggerLog, PatrolObserverTriggerFile, PatrolObserverTriggerSocket, PatrolObserverTriggerAPI, PatrolObserverTriggerInterval:+ return true+ default:+ return false+ }+}++func isPatrolArtifactDigest(value string) bool {+ if len(value) != 71 || !strings.HasPrefix(value, "sha256:") {+ return false+ }+ for _, r := range value[len("sha256:"):] {+ if (r < '0' || r > '9') && (r < 'a' || r > 'f') {+ return false+ }+ }+ return true+}++func isPatrolMachineCode(value string) bool {+ if value == "" || len(value) > 64 {+ return false+ }+ for _, r := range value {+ if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' {+ continue+ }+ return false+ }+ return true+}++func containsUnsafePatrolText(value string) bool {+ for _, r := range value {+ if unicode.IsControl(r) {+ return true+ }+ }+ return false+}++func normalizePatrolObjectiveActor(actor string) string {+ actor = strings.TrimSpace(actor)+ for len(actor) > 128 {+ _, size := utf8.DecodeLastRuneInString(actor)+ if size == 0 {+ return ""+ }+ actor = actor[:len(actor)-size]+ }+ if containsUnsafePatrolText(actor) {+ return ""+ }+ return actor+}++func normalizePatrolObjectiveTime(value time.Time) time.Time {+ if value.IsZero() {+ return time.Now().UTC()+ }+ return value.UTC()+}++func patrolObjectiveStatusRank(status PatrolObjectiveStatus) int {+ switch status {+ case PatrolObjectiveActive:+ return 0+ case PatrolObjectivePaused:+ return 1+ default:+ return 2+ }+}++func countNonArchivedPatrolObjectives(objectives map[string]*PatrolObjective) int {+ count := 0+ for _, objective := range objectives {+ if objective != nil && objective.Status != PatrolObjectiveArchived {+ count+++ }+ }+ return count+}++func clonePatrolObjectiveMap(source map[string]*PatrolObjective) map[string]*PatrolObjective {+ clone := make(map[string]*PatrolObjective, len(source))+ for id, objective := range source {+ clone[id] = clonePatrolObjective(objective)+ }+ return clone+}++func clonePatrolObjective(objective *PatrolObjective) *PatrolObjective {+ if objective == nil {+ return nil+ }+ copy := *objective+ copy.Scope.ResourceIDs = append([]string{}, objective.Scope.ResourceIDs...)+ copy.Observer = clonePatrolObserver(objective.Observer)+ copy.Coverage.ValidUntil = clonePatrolTime(objective.Coverage.ValidUntil)+ copy.Coverage.LastEvidenceAt = clonePatrolTime(objective.Coverage.LastEvidenceAt)+ return ©+}++func clonePatrolObserver(observer *PatrolObserverRecord) *PatrolObserverRecord {+ if observer == nil {+ return nil+ }+ copy := *observer+ copy.TriggerKinds = append([]PatrolObserverTriggerKind{}, observer.TriggerKinds...)+ copy.ValidUntil = clonePatrolTime(observer.ValidUntil)+ copy.LastEvidenceAt = clonePatrolTime(observer.LastEvidenceAt)+ return ©+}++func clonePatrolTime(value *time.Time) *time.Time {+ if value == nil {+ return nil+ }+ copy := value.UTC()+ return ©+}++func equalPatrolTriggerKinds(left, right []PatrolObserverTriggerKind) bool {+ if len(left) != len(right) {+ return false+ }+ for i := range left {+ if left[i] != right[i] {+ return false+ }+ }+ return true+}++func (p *PatrolService) seedPatrolObjectives(effectiveScopeIDs []string, scoped bool, now time.Time) string {+ if p == nil {+ return ""+ }+ p.mu.RLock()+ store := p.objectiveStore+ p.mu.RUnlock()+ if store == nil {+ return ""+ }+ objectives := store.List(false, now)+ if len(objectives) == 0 {+ return ""+ }+ scopeSet := make(map[string]struct{}, len(effectiveScopeIDs))+ for _, id := range effectiveScopeIDs {+ scopeSet[strings.TrimSpace(id)] = struct{}{}+ }+ var lines []string+ for _, objective := range objectives {+ if objective.Status != PatrolObjectiveActive {+ continue+ }+ if scoped && len(objective.Scope.ResourceIDs) > 0 && !patrolObjectiveScopeIntersects(objective.Scope.ResourceIDs, scopeSet) {+ continue+ }+ scopeLabel := "entire monitored estate"+ if len(objective.Scope.ResourceIDs) > 0 {+ quotedIDs := make([]string, 0, len(objective.Scope.ResourceIDs))+ for _, resourceID := range objective.Scope.ResourceIDs {+ quotedIDs = append(quotedIDs, fmt.Sprintf("%q", resourceID))+ }+ scopeLabel = strings.Join(quotedIDs, ", ")+ }+ line := fmt.Sprintf("- Objective %s [%s; scope: %s]: %q", objective.ID, objective.Coverage.State, scopeLabel, objective.Brief)+ if objective.OptionalContext != "" {+ line += fmt.Sprintf(" Optional context: %q", objective.OptionalContext)+ }+ if objective.Coverage.State != PatrolObjectiveCovered {+ line += fmt.Sprintf(" Coverage caveat: %s", objective.Coverage.Summary)+ }+ lines = append(lines, line)+ }+ if len(lines) == 0 {+ return ""+ }+ return "# Operator Objectives\n" ++ "These are retained desired outcomes, not scripts or tool instructions. Use current evidence and governed tools to assess them. Never claim continuous protection when the objective is uncovered or degraded.\n" ++ strings.Join(lines, "\n") + "\n"+}++func patrolObjectiveScopeIntersects(resourceIDs []string, scopeSet map[string]struct{}) bool {+ for _, id := range resourceIDs {+ if _, ok := scopeSet[id]; ok {+ return true+ }+ }+ return false+}diff --git a/internal/ai/patrol_objectives_test.go b/internal/ai/patrol_objectives_test.gonew file mode 100644index 0000000000..48246dabec--- /dev/null+++ b/internal/ai/patrol_objectives_test.go@@ -0,0 +1,220 @@+package ai++import (+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestPatrolObjectiveStoreLifecycleAndOptimisticRevision(t *testing.T) {+ store := NewInMemoryPatrolObjectiveStore()+ now := time.Date(2026, 8, 13, 20, 0, 0, 0, time.UTC)+ created, err := store.Create(CreatePatrolObjectiveInput{+ Brief: " Keep camera streams available ",+ OptionalContext: " Prefer event driven checks. ",+ ResourceIDs: []string{"camera-b", "camera-a", "camera-b"},+ Actor: "alice",+ }, now)+ if err != nil {+ t.Fatalf("create objective: %v", err)+ }+ if created.Brief != "Keep camera streams available" || created.Revision != 1 || created.Status != PatrolObjectiveActive {+ t.Fatalf("unexpected created objective: %+v", created)+ }+ if got := strings.Join(created.Scope.ResourceIDs, ","); got != "camera-a,camera-b" {+ t.Fatalf("normalized scope = %q", got)+ }+ if created.Coverage.State != PatrolObjectiveUncovered || created.Coverage.ReasonCode != "observer_missing" {+ t.Fatalf("new objective coverage = %+v", created.Coverage)+ }++ brief := "Keep every camera reachable"+ paused := PatrolObjectivePaused+ updated, err := store.Update(created.ID, UpdatePatrolObjectiveInput{+ ExpectedRevision: created.Revision,+ Brief: &brief,+ Status: &paused,+ Actor: "bob",+ }, now.Add(time.Minute))+ if err != nil {+ t.Fatalf("update objective: %v", err)+ }+ if updated.Revision != 2 || updated.Status != PatrolObjectivePaused || updated.UpdatedBy != "bob" {+ t.Fatalf("unexpected updated objective: %+v", updated)+ }+ if updated.Coverage.ReasonCode != "objective_paused" {+ t.Fatalf("paused coverage = %+v", updated.Coverage)+ }+ if _, err := store.Update(created.ID, UpdatePatrolObjectiveInput{ExpectedRevision: 1, Brief: &brief}, now); err != ErrPatrolObjectiveConflict {+ t.Fatalf("stale update error = %v, want conflict", err)+ }+ if err := store.Delete(created.ID, 1); err != ErrPatrolObjectiveConflict {+ t.Fatalf("stale delete error = %v, want conflict", err)+ }+ if err := store.Delete(created.ID, updated.Revision); err != nil {+ t.Fatalf("delete objective: %v", err)+ }+ if _, found := store.Get(created.ID, now); found {+ t.Fatal("deleted objective remained in store")+ }+}++func TestPatrolObjectiveStorePersistsEncrypted(t *testing.T) {+ dataDir := t.TempDir()+ store, err := NewPatrolObjectiveStore(dataDir)+ if err != nil {+ t.Fatalf("new persistent store: %v", err)+ }+ const brief = "Keep Jellyfin playback free of buffering"+ created, err := store.Create(CreatePatrolObjectiveInput{Brief: brief, Actor: "alice"}, time.Now().UTC())+ if err != nil {+ t.Fatalf("create objective: %v", err)+ }++ data, err := os.ReadFile(filepath.Join(dataDir, "ai_patrol_objectives.enc"))+ if err != nil {+ t.Fatalf("read objective file: %v", err)+ }+ if strings.Contains(string(data), brief) {+ t.Fatal("objective brief was persisted in plaintext")+ }++ reloaded, err := NewPatrolObjectiveStore(dataDir)+ if err != nil {+ t.Fatalf("reload persistent store: %v", err)+ }+ got, found := reloaded.Get(created.ID, time.Now().UTC())+ if !found || got.Brief != brief || got.Revision != created.Revision {+ t.Fatalf("reloaded objective = %+v, found=%v", got, found)+ }+}++func TestPatrolObjectiveStoreRejectsPlaintextPersistence(t *testing.T) {+ dataDir := t.TempDir()+ if _, err := NewPatrolObjectiveStore(dataDir); err != nil {+ t.Fatalf("initialize encryption key: %v", err)+ }+ plaintext := []byte(`{"version":1,"objectives":[]}`)+ if err := os.WriteFile(filepath.Join(dataDir, "ai_patrol_objectives.enc"), plaintext, 0o600); err != nil {+ t.Fatalf("write plaintext fixture: %v", err)+ }+ if _, err := NewPatrolObjectiveStore(dataDir); err == nil || !strings.Contains(err.Error(), "decrypt patrol objectives") {+ t.Fatalf("plaintext load error = %v, want fail-closed decryption error", err)+ }+}++func TestPatrolObserverLifecycleDerivesCoverageFromHealthLease(t *testing.T) {+ store := NewInMemoryPatrolObjectiveStore()+ now := time.Date(2026, 8, 13, 20, 0, 0, 0, time.UTC)+ objective, err := store.Create(CreatePatrolObjectiveInput{Brief: "Keep cameras online"}, now)+ if err != nil {+ t.Fatalf("create objective: %v", err)+ }+ digest := "sha256:" + strings.Repeat("a", 64)+ observer := PatrolObserverRecord{+ ID: "observer-camera-health",+ Version: 1,+ State: PatrolObserverProposed,+ ArtifactDigest: digest,+ TriggerKinds: []PatrolObserverTriggerKind{PatrolObserverTriggerInterval, PatrolObserverTriggerEvent},+ ReadOnly: true,+ }+ objective, err = store.RecordObserver(objective.ID, objective.Revision, observer, "builder", now.Add(time.Minute))+ if err != nil {+ t.Fatalf("record proposed observer: %v", err)+ }+ if objective.Coverage.ReasonCode != "observer_proposed" {+ t.Fatalf("proposed coverage = %+v", objective.Coverage)+ }++ observer = *objective.Observer+ observer.State = PatrolObserverValidated+ objective, err = store.RecordObserver(objective.ID, objective.Revision, observer, "validator", now.Add(2*time.Minute))+ if err != nil {+ t.Fatalf("validate observer: %v", err)+ }+ if objective.Coverage.ReasonCode != "observer_not_installed" {+ t.Fatalf("validated coverage = %+v", objective.Coverage)+ }++ observer = *objective.Observer+ observer.State = PatrolObserverInstalled+ validUntil := now.Add(30 * time.Minute)+ lastEvidence := now.Add(2 * time.Minute)+ observer.ValidUntil = &validUntil+ observer.LastEvidenceAt = &lastEvidence+ objective, err = store.RecordObserver(objective.ID, objective.Revision, observer, "installer", now.Add(3*time.Minute))+ if err != nil {+ t.Fatalf("install observer: %v", err)+ }+ if objective.Coverage.State != PatrolObjectiveCovered || objective.Coverage.ReasonCode != "observer_healthy" {+ t.Fatalf("installed coverage = %+v", objective.Coverage)+ }++ stale, found := store.Get(objective.ID, validUntil.Add(time.Second))+ if !found || stale.Coverage.State != PatrolObjectiveDegraded || stale.Coverage.ReasonCode != "observer_stale" {+ t.Fatalf("stale coverage = %+v, found=%v", stale.Coverage, found)+ }+}++func TestPatrolObserverRejectsUnvalidatedInstallAndWritableArtifact(t *testing.T) {+ store := NewInMemoryPatrolObjectiveStore()+ now := time.Now().UTC()+ objective, err := store.Create(CreatePatrolObjectiveInput{Brief: "Keep playback smooth"}, now)+ if err != nil {+ t.Fatalf("create objective: %v", err)+ }+ observer := PatrolObserverRecord{+ ID: "observer-playback",+ Version: 1,+ State: PatrolObserverInstalled,+ ArtifactDigest: "sha256:" + strings.Repeat("b", 64),+ TriggerKinds: []PatrolObserverTriggerKind{PatrolObserverTriggerEvent},+ ReadOnly: true,+ }+ if _, err := store.RecordObserver(objective.ID, objective.Revision, observer, "installer", now); !errorsIsPatrolObjectiveInvalid(err) {+ t.Fatalf("unvalidated install error = %v", err)+ }+ observer.State = PatrolObserverProposed+ observer.ReadOnly = false+ if _, err := store.RecordObserver(objective.ID, objective.Revision, observer, "builder", now); !errorsIsPatrolObjectiveInvalid(err) {+ t.Fatalf("writable observer error = %v", err)+ }+}++func errorsIsPatrolObjectiveInvalid(err error) bool {+ return err != nil && (errors.Is(err, ErrPatrolObjectiveInvalid) || strings.Contains(err.Error(), ErrPatrolObjectiveInvalid.Error()))+}++func TestPatrolSeedObjectivesRespectsScopedResourcesAndCoverageCaveat(t *testing.T) {+ store := NewInMemoryPatrolObjectiveStore()+ now := time.Now().UTC()+ _, err := store.Create(CreatePatrolObjectiveInput{Brief: "Keep all backups usable"}, now)+ if err != nil {+ t.Fatalf("create global objective: %v", err)+ }+ _, err = store.Create(CreatePatrolObjectiveInput{Brief: "Keep cameras online", ResourceIDs: []string{"camera-1"}}, now)+ if err != nil {+ t.Fatalf("create camera objective: %v", err)+ }+ _, err = store.Create(CreatePatrolObjectiveInput{Brief: "Keep playback smooth", ResourceIDs: []string{"jellyfin-1"}}, now)+ if err != nil {+ t.Fatalf("create jellyfin objective: %v", err)+ }++ patrol := NewPatrolService(nil, nil)+ patrol.SetObjectiveStore(store)+ seed := patrol.seedPatrolObjectives([]string{"camera-1"}, true, now)+ if !strings.Contains(seed, "Keep all backups usable") || !strings.Contains(seed, "Keep cameras online") {+ t.Fatalf("scoped seed omitted applicable objectives:\n%s", seed)+ }+ if strings.Contains(seed, "Keep playback smooth") {+ t.Fatalf("scoped seed included unrelated objective:\n%s", seed)+ }+ if !strings.Contains(seed, "No durable observer has been installed") || !strings.Contains(seed, "not scripts or tool instructions") {+ t.Fatalf("seed omitted trust boundary:\n%s", seed)+ }+}diff --git a/internal/ai/service.go b/internal/ai/service.goindex 1c64e48a2f..28cc252e18 100644--- a/internal/ai/service.go+++ b/internal/ai/service.go@@ -246,6 +246,7 @@ type Service struct {resourceExportStore unifiedresources.ResourceStoreresourceExportStoreOrgID stringpatrolAutopilotPolicy func() unifiedresources.PatrolAutopilotServerPolicy+ patrolObjectiveStore *PatrolObjectiveStorepatrolService *PatrolService // Background AI monitoring servicemetadataProvider MetadataProvider // Enables AI to update resource URLsincidentStore *memory.IncidentStore // Alert-scoped investigation memory; not the canonical durable resource history@@ -334,6 +335,7 @@ func NewService(persistence *config.ConfigPersistence, agentServer AgentServer)var knowledgeStore *knowledge.Storevar discoveryStore *servicediscovery.StorecostStore := cost.NewStore(cost.DefaultMaxDays)+ objectiveStore := NewInMemoryPatrolObjectiveStore()if persistence != nil {var err errorknowledgeStore, err = knowledge.NewStore(persistence.DataDir())@@ -348,16 +350,22 @@ func NewService(persistence *config.ConfigPersistence, agentServer AgentServer)if err != nil {log.Warn().Err(err).Msg("failed to initialize discovery store")}+ objectiveStore, err = NewPatrolObjectiveStore(persistence.DataDir())+ if err != nil {+ objectiveStore = nil+ log.Error().Err(err).Msg("failed to initialize encrypted Patrol objective store")+ }}svc := &Service{- orgID: "default",- persistence: persistence,- agentServer: agentServer,- policy: agentexec.DefaultPolicy(),- knowledgeStore: knowledgeStore,- discoveryStore: discoveryStore,- costStore: costStore,+ orgID: "default",+ persistence: persistence,+ agentServer: agentServer,+ policy: agentexec.DefaultPolicy(),+ knowledgeStore: knowledgeStore,+ discoveryStore: discoveryStore,+ costStore: costStore,+ patrolObjectiveStore: objectiveStore,limits: executionLimits{chatSlots: make(chan struct{}, 4),patrolSlots: make(chan struct{}, 1),@@ -559,6 +567,7 @@ func (s *Service) initPatrolServiceLocked() {}s.patrolService = NewPatrolService(s, s.stateProvider)+ s.patrolService.SetObjectiveStore(s.patrolObjectiveStore)if s.knowledgeStore != nil {s.patrolService.SetKnowledgeStore(s.knowledgeStore)}@@ -701,6 +710,15 @@ func (s *Service) GetPatrolService() *PatrolService {return s.patrolService}+// GetPatrolObjectiveStore returns the organization-scoped durable operator+// objective store. It exists independently from a running Patrol service so an+// operator can retain intent while provider or infrastructure setup is offline.+func (s *Service) GetPatrolObjectiveStore() *PatrolObjectiveStore {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.patrolObjectiveStore+}+// SetChatService sets the chat service for investigation orchestratorfunc (s *Service) SetChatService(cs ChatServiceProvider) {s.mu.Lock()diff --git a/internal/api/ai_handlers_patrol_actions_additional_test.go b/internal/api/ai_handlers_patrol_actions_additional_test.goindex eb62d1a508..46ed7dc565 100644--- a/internal/api/ai_handlers_patrol_actions_additional_test.go+++ b/internal/api/ai_handlers_patrol_actions_additional_test.go@@ -1244,3 +1244,28 @@ func TestHandleForcePatrol_ScopedRequestBypassesFullRunCadenceGate(t *testing.T)t.Fatalf("full response = %s, want patrol_rate_limited", fullRec.Body.String())}}++func TestPatrolObjectiveAPIContractKeepsCoverageServerOwned(t *testing.T) {+ handler, _, _, _ := setupAIHandlerWithPatrol(t)++ createReq := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/objectives", strings.NewReader(`{"brief":"Keep cameras online","resource_ids":["camera-1"]}`))+ createRec := httptest.NewRecorder()+ handler.HandlePatrolObjectives(createRec, createReq)+ if createRec.Code != http.StatusCreated {+ t.Fatalf("create status = %d, body=%s", createRec.Code, createRec.Body.String())+ }+ var objective ai.PatrolObjective+ if err := json.Unmarshal(createRec.Body.Bytes(), &objective); err != nil {+ t.Fatalf("decode objective: %v", err)+ }+ if objective.Coverage.State != ai.PatrolObjectiveUncovered || objective.Coverage.ReasonCode != "observer_missing" {+ t.Fatalf("new objective coverage = %+v", objective.Coverage)+ }++ forgedReq := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/objectives", strings.NewReader(`{"brief":"Keep cameras online","coverage":{"state":"covered"}}`))+ forgedRec := httptest.NewRecorder()+ handler.HandlePatrolObjectives(forgedRec, forgedReq)+ if forgedRec.Code != http.StatusBadRequest {+ t.Fatalf("forged coverage status = %d, body=%s", forgedRec.Code, forgedRec.Body.String())+ }+}diff --git a/internal/api/patrol_objectives.go b/internal/api/patrol_objectives.gonew file mode 100644index 0000000000..8d4bd9bdce--- /dev/null+++ b/internal/api/patrol_objectives.go@@ -0,0 +1,206 @@+package api++import (+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "strconv"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai"+ "github.com/rcourtman/pulse-go-rewrite/internal/utils"+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+ "github.com/rs/zerolog/log"+)++const maxPatrolObjectiveRequestBytes = 16 * 1024++type patrolObjectiveCreateRequest struct {+ Brief string `json:"brief"`+ OptionalContext string `json:"optional_context,omitempty"`+ ResourceIDs []string `json:"resource_ids,omitempty"`+}++type patrolObjectiveUpdateRequest struct {+ Revision uint64 `json:"revision"`+ Brief *string `json:"brief,omitempty"`+ OptionalContext *string `json:"optional_context,omitempty"`+ ResourceIDs *[]string `json:"resource_ids,omitempty"`+ Status *ai.PatrolObjectiveStatus `json:"status,omitempty"`+}++func (h *AISettingsHandler) HandlePatrolObjectives(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Cache-Control", "no-store")+ if strings.TrimSuffix(r.URL.Path, "/") != "/api/ai/patrol/objectives" {+ writePatrolObjectiveError(w, ai.ErrPatrolObjectiveNotFound)+ return+ }+ store := h.patrolObjectiveStore(r)+ if store == nil {+ writeJSONError(w, http.StatusServiceUnavailable, "patrol_objectives_unavailable", "Patrol objectives are unavailable")+ return+ }+ switch r.Method {+ case http.MethodGet:+ includeArchived, err := parsePatrolObjectiveIncludeArchived(r)+ if err != nil {+ writeJSONError(w, http.StatusBadRequest, "patrol_objective_invalid_request", err.Error())+ return+ }+ writePatrolObjectiveJSON(w, http.StatusOK, map[string]any{+ "objectives": store.List(includeArchived, time.Now().UTC()),+ })+ case http.MethodPost:+ var request patrolObjectiveCreateRequest+ if err := decodePatrolObjectiveRequest(w, r, &request); err != nil {+ writeJSONError(w, http.StatusBadRequest, "patrol_objective_invalid_request", "Invalid Patrol objective request")+ return+ }+ objective, err := store.Create(ai.CreatePatrolObjectiveInput{+ Brief: request.Brief,+ OptionalContext: request.OptionalContext,+ ResourceIDs: request.ResourceIDs,+ Actor: strings.TrimSpace(auth.GetUser(r.Context())),+ }, time.Now().UTC())+ if err != nil {+ writePatrolObjectiveError(w, err)+ return+ }+ LogAuditEventForTenant(GetOrgID(r.Context()), "patrol_objective_created", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, true, "Created Patrol objective "+objective.ID)+ writePatrolObjectiveJSON(w, http.StatusCreated, objective)+ default:+ w.Header().Set("Allow", "GET, POST")+ writeJSONError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed")+ }+}++func (h *AISettingsHandler) HandlePatrolObjective(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Cache-Control", "no-store")+ id, ok := patrolObjectiveIDFromPath(r.URL.Path)+ if !ok {+ writePatrolObjectiveError(w, ai.ErrPatrolObjectiveNotFound)+ return+ }+ store := h.patrolObjectiveStore(r)+ if store == nil {+ writeJSONError(w, http.StatusServiceUnavailable, "patrol_objectives_unavailable", "Patrol objectives are unavailable")+ return+ }+ switch r.Method {+ case http.MethodGet:+ objective, found := store.Get(id, time.Now().UTC())+ if !found {+ writePatrolObjectiveError(w, ai.ErrPatrolObjectiveNotFound)+ return+ }+ writePatrolObjectiveJSON(w, http.StatusOK, objective)+ case http.MethodPatch:+ var request patrolObjectiveUpdateRequest+ if err := decodePatrolObjectiveRequest(w, r, &request); err != nil {+ writeJSONError(w, http.StatusBadRequest, "patrol_objective_invalid_request", "Invalid Patrol objective request")+ return+ }+ objective, err := store.Update(id, ai.UpdatePatrolObjectiveInput{+ ExpectedRevision: request.Revision,+ Brief: request.Brief,+ OptionalContext: request.OptionalContext,+ ResourceIDs: request.ResourceIDs,+ Status: request.Status,+ Actor: strings.TrimSpace(auth.GetUser(r.Context())),+ }, time.Now().UTC())+ if err != nil {+ writePatrolObjectiveError(w, err)+ return+ }+ LogAuditEventForTenant(GetOrgID(r.Context()), "patrol_objective_updated", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, true, "Updated Patrol objective "+objective.ID)+ writePatrolObjectiveJSON(w, http.StatusOK, objective)+ case http.MethodDelete:+ revision, err := strconv.ParseUint(strings.TrimSpace(r.URL.Query().Get("revision")), 10, 64)+ if err != nil || revision == 0 {+ writeJSONError(w, http.StatusBadRequest, "patrol_objective_invalid_request", "A valid revision is required")+ return+ }+ if err := store.Delete(id, revision); err != nil {+ writePatrolObjectiveError(w, err)+ return+ }+ LogAuditEventForTenant(GetOrgID(r.Context()), "patrol_objective_deleted", auth.GetUser(r.Context()), GetClientIP(r), r.URL.Path, true, "Deleted Patrol objective "+id)+ w.WriteHeader(http.StatusNoContent)+ default:+ w.Header().Set("Allow", "GET, PATCH, DELETE")+ writeJSONError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Method not allowed")+ }+}++func (h *AISettingsHandler) patrolObjectiveStore(r *http.Request) *ai.PatrolObjectiveStore {+ if h == nil || r == nil {+ return nil+ }+ service := h.GetAIService(r.Context())+ if service == nil {+ return nil+ }+ return service.GetPatrolObjectiveStore()+}++func decodePatrolObjectiveRequest(w http.ResponseWriter, r *http.Request, destination any) error {+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxPatrolObjectiveRequestBytes))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(destination); err != nil {+ return err+ }+ if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {+ return errors.New("request body must contain one JSON object")+ }+ return nil+}++func parsePatrolObjectiveIncludeArchived(r *http.Request) (bool, error) {+ raw := strings.TrimSpace(r.URL.Query().Get("include_archived"))+ if raw == "" {+ return false, nil+ }+ value, err := strconv.ParseBool(raw)+ if err != nil {+ return false, errors.New("include_archived must be true or false")+ }+ return value, nil+}++func patrolObjectiveIDFromPath(path string) (string, bool) {+ const prefix = "/api/ai/patrol/objectives/"+ if !strings.HasPrefix(path, prefix) {+ return "", false+ }+ id := strings.TrimSpace(strings.TrimPrefix(path, prefix))+ if id == "" || strings.Contains(id, "/") || len(id) > 128 {+ return "", false+ }+ return id, true+}++func writePatrolObjectiveError(w http.ResponseWriter, err error) {+ switch {+ case errors.Is(err, ai.ErrPatrolObjectiveNotFound):+ writeJSONError(w, http.StatusNotFound, "patrol_objective_not_found", "Patrol objective not found")+ case errors.Is(err, ai.ErrPatrolObjectiveConflict):+ writeJSONError(w, http.StatusConflict, "patrol_objective_revision_conflict", "Patrol objective changed; reload it before saving")+ case errors.Is(err, ai.ErrPatrolObjectiveLimit):+ writeJSONError(w, http.StatusConflict, "patrol_objective_limit_reached", "Patrol objective limit reached")+ case errors.Is(err, ai.ErrPatrolObjectiveInvalid):+ writeJSONError(w, http.StatusBadRequest, "patrol_objective_invalid_request", err.Error())+ default:+ log.Error().Err(err).Msg("Patrol objective operation failed")+ writeJSONError(w, http.StatusInternalServerError, "patrol_objective_persistence_failed", "Failed to persist Patrol objective")+ }+}++func writePatrolObjectiveJSON(w http.ResponseWriter, status int, payload any) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ if err := utils.WriteJSONResponse(w, payload); err != nil {+ log.Error().Err(err).Msg("Failed to write Patrol objective response")+ }+}diff --git a/internal/api/patrol_objectives_test.go b/internal/api/patrol_objectives_test.gonew file mode 100644index 0000000000..d98ca44f0a--- /dev/null+++ b/internal/api/patrol_objectives_test.go@@ -0,0 +1,117 @@+package api++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai"+)++func TestPatrolObjectivesHTTPContractAndOptimisticRevision(t *testing.T) {+ handler := NewAISettingsHandler(nil, nil, nil)++ createRequest := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/objectives", strings.NewReader(`{+ "brief":"Keep Jellyfin playback smooth",+ "optional_context":"Avoid polling the model continuously",+ "resource_ids":["jellyfin-1"]+ }`))+ createResponse := httptest.NewRecorder()+ handler.HandlePatrolObjectives(createResponse, createRequest)+ if createResponse.Code != http.StatusCreated {+ t.Fatalf("create status = %d, body=%s", createResponse.Code, createResponse.Body.String())+ }+ if createResponse.Header().Get("Cache-Control") != "no-store" {+ t.Fatalf("create cache control = %q", createResponse.Header().Get("Cache-Control"))+ }+ var created ai.PatrolObjective+ if err := json.Unmarshal(createResponse.Body.Bytes(), &created); err != nil {+ t.Fatalf("decode created objective: %v", err)+ }+ if created.ID == "" || created.Revision != 1 || created.Coverage.State != ai.PatrolObjectiveUncovered || created.Coverage.ReasonCode != "observer_missing" {+ t.Fatalf("created objective = %+v", created)+ }+ if created.Observer != nil {+ t.Fatalf("public create unexpectedly accepted an observer: %+v", created.Observer)+ }++ listRequest := httptest.NewRequest(http.MethodGet, "/api/ai/patrol/objectives", nil)+ listResponse := httptest.NewRecorder()+ handler.HandlePatrolObjectives(listResponse, listRequest)+ if listResponse.Code != http.StatusOK {+ t.Fatalf("list status = %d, body=%s", listResponse.Code, listResponse.Body.String())+ }+ var listed struct {+ Objectives []ai.PatrolObjective `json:"objectives"`+ }+ if err := json.Unmarshal(listResponse.Body.Bytes(), &listed); err != nil {+ t.Fatalf("decode objective list: %v", err)+ }+ if len(listed.Objectives) != 1 || listed.Objectives[0].ID != created.ID {+ t.Fatalf("listed objectives = %+v", listed.Objectives)+ }++ patchBody := fmt.Sprintf(`{"revision":%d,"status":"paused"}`, created.Revision)+ patchRequest := httptest.NewRequest(http.MethodPatch, "/api/ai/patrol/objectives/"+created.ID, strings.NewReader(patchBody))+ patchResponse := httptest.NewRecorder()+ handler.HandlePatrolObjective(patchResponse, patchRequest)+ if patchResponse.Code != http.StatusOK {+ t.Fatalf("patch status = %d, body=%s", patchResponse.Code, patchResponse.Body.String())+ }+ var updated ai.PatrolObjective+ if err := json.Unmarshal(patchResponse.Body.Bytes(), &updated); err != nil {+ t.Fatalf("decode updated objective: %v", err)+ }+ if updated.Revision != 2 || updated.Status != ai.PatrolObjectivePaused || updated.Coverage.ReasonCode != "objective_paused" {+ t.Fatalf("updated objective = %+v", updated)+ }++ staleRequest := httptest.NewRequest(http.MethodPatch, "/api/ai/patrol/objectives/"+created.ID, strings.NewReader(patchBody))+ staleResponse := httptest.NewRecorder()+ handler.HandlePatrolObjective(staleResponse, staleRequest)+ if staleResponse.Code != http.StatusConflict || !strings.Contains(staleResponse.Body.String(), "patrol_objective_revision_conflict") {+ t.Fatalf("stale patch status = %d, body=%s", staleResponse.Code, staleResponse.Body.String())+ }++ deleteRequest := httptest.NewRequest(http.MethodDelete, fmt.Sprintf("/api/ai/patrol/objectives/%s?revision=%d", created.ID, updated.Revision), nil)+ deleteResponse := httptest.NewRecorder()+ handler.HandlePatrolObjective(deleteResponse, deleteRequest)+ if deleteResponse.Code != http.StatusNoContent {+ t.Fatalf("delete status = %d, body=%s", deleteResponse.Code, deleteResponse.Body.String())+ }+}++func TestPatrolObjectivesHTTPRejectsClientAuthoredCoverageAndObservers(t *testing.T) {+ handler := NewAISettingsHandler(nil, nil, nil)+ requests := []string{+ `{"brief":"Keep cameras online","coverage":{"state":"covered"}}`,+ `{"brief":"Keep cameras online","observer":{"state":"installed"}}`,+ }+ for _, body := range requests {+ request := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/objectives", strings.NewReader(body))+ response := httptest.NewRecorder()+ handler.HandlePatrolObjectives(response, request)+ if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "patrol_objective_invalid_request") {+ t.Fatalf("body %s: status = %d, response=%s", body, response.Code, response.Body.String())+ }+ }+}++func TestPatrolObjectivesHTTPRejectsOversizedAndAmbiguousBodies(t *testing.T) {+ handler := NewAISettingsHandler(nil, nil, nil)+ bodies := []string{+ `{"brief":"one"}{"brief":"two"}`,+ `{"brief":"` + strings.Repeat("x", maxPatrolObjectiveRequestBytes) + `"}`,+ }+ for _, body := range bodies {+ request := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/objectives", strings.NewReader(body))+ response := httptest.NewRecorder()+ handler.HandlePatrolObjectives(response, request)+ if response.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, body=%s", response.Code, response.Body.String())+ }+ }+}diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex cc5f6cbeaf..6db491fb48 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -626,6 +626,8 @@ var allRouteAllowlist = []string{"/api/ai/patrol/status","/api/ai/patrol/stream","/api/ai/patrol/findings",+ "/api/ai/patrol/objectives",+ "/api/ai/patrol/objectives/","/api/ai/patrol/attention","/api/ai/patrol/attention/","/api/ai/patrol/history",diff --git a/internal/api/router_routes_ai_relay.go b/internal/api/router_routes_ai_relay.goindex dc3d4ee386..184270e5f4 100644--- a/internal/api/router_routes_ai_relay.go+++ b/internal/api/router_routes_ai_relay.go@@ -112,6 +112,8 @@ func (r *Router) registerAIRelayRoutesGroup() {r.mux.HandleFunc("/api/ai/patrol/status", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleGetPatrolStatus)))r.mux.HandleFunc("/api/ai/patrol/stream", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandlePatrolStream)))r.mux.HandleFunc("/api/ai/patrol/findings", RequireAuth(r.config, r.routeAIPatrolFindings))+ r.mux.HandleFunc("/api/ai/patrol/objectives", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandlePatrolObjectives)))+ r.mux.HandleFunc("/api/ai/patrol/objectives/", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandlePatrolObjective)))r.mux.HandleFunc("/api/ai/patrol/attention", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRouteAttentionList, r.attentionHandlers.HandleAttention)))r.mux.HandleFunc("/api/ai/patrol/attention/", RequireAuth(r.config, requireRelayMobileRuntimeRoute(relayMobileRouteAttentionDetail, r.attentionHandlers.HandleAttention)))// SECURITY: AI Patrol read endpoints - require ai:execute scopediff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex 38cca380cf..0ba0139040 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -1609,6 +1609,8 @@ func TestAIExecuteReadEndpointsRequireAIExecuteScope(t *testing.T) {"/api/ai/patrol/status","/api/ai/patrol/stream","/api/ai/patrol/findings",+ "/api/ai/patrol/objectives",+ "/api/ai/patrol/objectives/objective-1","/api/ai/patrol/history","/api/ai/patrol/runs","/api/ai/patrol/runs/run-1",@@ -1752,6 +1754,7 @@ func TestRelayMobileAccessScopeDeniesAdjacentAIRoutes(t *testing.T) {{method: http.MethodPost, path: "/api/ai/workflow-prompts/activity", body: `{}`, want: config.ScopeAIChat},{method: http.MethodGet, path: "/api/ai/agents", body: "", want: config.ScopeAIExecute},{method: http.MethodGet, path: "/api/ai/approvals/approval-1", body: "", want: config.ScopeAIExecute},+ {method: http.MethodGet, path: "/api/ai/patrol/objectives", body: "", want: config.ScopeAIExecute},{method: http.MethodDelete, path: "/api/ai/patrol/findings", body: "", want: config.ScopeAIExecute},{method: http.MethodPost, path: "/api/ai/findings/finding-1/reinvestigate", body: `{}`, want: config.ScopeAIExecute},{method: http.MethodPost, path: "/api/ai/findings/finding-1/reapprove", body: `{}`, want: config.ScopeAIExecute},@@ -1794,6 +1797,9 @@ func TestAIExecuteMutationEndpointsRequireAIExecuteScope(t *testing.T) {{method: http.MethodPost, path: "/api/ai/patrol/resolve", body: `{}`},{method: http.MethodPost, path: "/api/ai/patrol/suppressions", body: `{}`},{method: http.MethodDelete, path: "/api/ai/patrol/suppressions/rule-1", body: ""},+ {method: http.MethodPost, path: "/api/ai/patrol/objectives", body: `{}`},+ {method: http.MethodPatch, path: "/api/ai/patrol/objectives/objective-1", body: `{}`},+ {method: http.MethodDelete, path: "/api/ai/patrol/objectives/objective-1", body: ""},{method: http.MethodPost, path: "/api/ai/remediation/approve", body: `{}`},{method: http.MethodPost, path: "/api/ai/findings/f-1/reapprove", body: `{}`},{method: http.MethodPost, path: "/api/ai/approvals/approval-1/approve", body: `{}`},