Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Add the typed Patrol action-proposal seam over the shared lifecycle

rcourtman26718e70b6f5
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 3b087d99b1..a09089dac1 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -347,7 +347,11 @@ lifecycle evidence, and retry/idempotency handling must not create duplicate
lifecycle events. Approval or rejection decisions for those plans must flow
through `POST /api/actions/{id}/decision`, which records API-owned audit and
lifecycle evidence only; lifecycle surfaces must not treat approval as
-implicit command execution or define a parallel execution handoff. Assistant
+implicit command execution or define a parallel execution handoff. The
+Patrol proposal broker (`internal/api/patrol_action_broker.go`) rides that
+same API-owned lifecycle; agent lifecycle surfaces must not consume
+Patrol-origin action audits as an agent command grant or lifecycle
+execution shortcut. Assistant
handoffs that recover a live Patrol approval by finding ID are still AI/runtime
review context only; agent lifecycle surfaces must not treat that recovered
approval reference as an agent command grant or host-execution shortcut.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 749a67ba5a..4c6b1b55bf 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -4540,6 +4540,30 @@ investigation-fix approvals must also enter that shared decision lifecycle:
when the approval has a governed action plan and moves the owning Patrol
finding to `fix_rejected`, so a declined fix remains a visible governed loop
outcome rather than disappearing when the pending approval leaves the queue.
+The typed action-proposal seam in `pkg/aicontracts/action_broker.go` is the
+successor to that command-shaped approval flow and the ONLY sanctioned route
+from an enterprise Patrol investigation to a Pulse infrastructure mutation:
+`OrchestratorActionBroker` exposes exactly `Capabilities` (read-only catalog
+of a resource's advertised capabilities and parameter schemas, including
+sensitivity) and `Submit` (plan-only typed proposal). The contract
+deliberately omits org ID, requestedBy, autonomy, risk, approval-policy,
+destructive, command, and target-host fields, and has no decide or execute
+methods, so enterprise code can neither claim authorization nor dispatch;
+authorization always derives from the capability's declared policy on the
+core lifecycle. `OrchestratorDeps.ActionBroker` carries the seam;
+`CmdExecutor` and `ApprovalStore` on the same struct are migration-only
+legacy side doors that must not gain new callers and are scheduled for
+removal with the orchestrator migration. Investigations reference their
+canonical action through the additive `Action *ActionReference` fields on
+`InvestigationSession` and `InvestigationRecord`; the command-shaped
+`ProposedFix`/`ApprovalID` fields are migration-only narrative and must
+never be populated by new investigations nor re-armed into executable
+approvals. Proposal parameters live in the canonical action audit, not
+duplicated into investigation stores. Proofs:
+`TestOrchestratorActionBrokerIsProposeOnly`,
+`TestActionProposalWireShapeIsTypedAndCommandFree`, and
+`TestActionReferenceIsAdditiveOnInvestigationShapes` in
+`pkg/aicontracts/contracts_test.go`.
The same ownership includes the Pulse query tool schema under
`internal/ai/tools/`: topology-query input names must stay canonical inside
the AI runtime itself, so new tool arguments such as `max_proxmox_nodes`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index c7b8150fc6..6632368162 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1830,6 +1830,26 @@ a new API state machine, queue contract, or verification-accounting field.
remediation locks, plan-drift revalidation, execution, and terminal
publication. No caller, HTTP or in-process, may implement a parallel
lifecycle or dispatch a resource mutation around this service.
+ The Patrol proposal seam rides that same service:
+ `internal/api/patrol_action_broker.go` implements the public
+ `aicontracts.OrchestratorActionBroker` contract as a tenant-bound,
+ plan-only adapter. It stamps the fixed `pulse_patrol` requestedBy actor
+ and a broker-owned `ActionOrigin` (surface/finding/investigation/proposal
+ IDs) through the service's internal `PlanWithOptions`; the public plan
+ endpoint keeps calling plain `Plan`, so an HTTP request body can never
+ claim a first-party origin. Submit never decides or executes (even an
+ `ApprovalNone` capability returns a planned disposition), and proposals
+ that populate a capability parameter declared `IsSensitive` are refused
+ with `ErrSensitiveParamsRequireOperator` before any audit persistence,
+ so secret material never enters model output, investigation stores, or
+ action audit records. Capability inspection for proposals goes through
+ `Service.Capabilities`, which shares planning's registry resolution and
+ typed errors. The service also exposes an additive `OnActionTransition`
+ persisted-state callback (plan, decision, and terminal execution
+ transitions, published only after the corresponding store write
+ succeeds) so proposing surfaces can reconcile decisions and outcomes.
+ Plan-only proof: `TestContract_PatrolActionBrokerIsPlanOnly` in
+ `internal/api/contract_test.go`.
Executor-owned live readiness is part of planning, not a UI precheck:
after planner validation and before audit persistence, the lifecycle
service must ask
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 0393c9967f..94051df422 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -312,7 +312,11 @@ Storage/recovery remediation or restore-adjacent workflows may consume
contract. This subsystem must not create a storage-local approval policy,
stale-plan hash, blast-radius model, or execution protocol outside
`internal/api/actions.go`, `internal/actionlifecycle/service.go`, and
-`internal/actionplanner/planner.go`.
+`internal/actionplanner/planner.go`. The Patrol proposal broker
+(`internal/api/patrol_action_broker.go`) is part of that same API-owned
+boundary: storage/recovery surfaces must not treat Patrol-proposed action
+audits (origin surface `patrol`) as a storage-local execution channel or
+mint their own proposal origins.
Storage/recovery surfaces may consume unified-resource `platformScopes` as
read-only platform membership context, but they must not reinterpret runtime
scope overlap as storage or recovery ownership. A Docker workload that also
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index a005a51c3c..7cd8debf54 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1318,6 +1318,22 @@ AI-only summary payloads, or page-local heuristics.
the durable store-backed registry (ephemeral per-request registries
consult, never write). Regression coverage:
`internal/unifiedresources/canonical_id_pins_test.go`.
+26. Keep action-audit origin metadata broker-owned. `ActionAuditRecord`
+ carries an optional `Origin *ActionOrigin`
+ (`surface`/`findingId`/`investigationId`/`proposalId`), persisted in
+ the `action_audits.origin_json` column (added by
+ `migrateActionAuditsSchema`) and round-tripped through
+ `scanActionAuditRecord`. Origin identifies which internal surface
+ proposed the action (e.g. Patrol) so decisions and terminal outcomes
+ can be reconciled back onto that surface's records. It is set only by
+ in-process planning callers through the action lifecycle service's
+ plan options; the public `POST /api/actions/plan` body must never be
+ able to claim a first-party origin. `NormalizeActionOrigin` trims
+ fields and collapses an all-empty origin to nil so absent metadata
+ never persists as an empty object. Origin fields are Pulse-produced
+ identifiers, not operator text, and stay outside the redaction set.
+ Regression coverage: `TestSQLiteStoreActionAuditOriginRoundTrip` in
+ `internal/unifiedresources/store_test.go`.
## Current State
diff --git a/internal/actionlifecycle/service.go b/internal/actionlifecycle/service.go
index 61916a3cc5..d2e7c2a1fc 100644
--- a/internal/actionlifecycle/service.go
+++ b/internal/actionlifecycle/service.go
@@ -56,7 +56,23 @@ type Service struct {
// record, including refused-before-dispatch failures, so SSE bridges
// and reconcilers observe the full lifecycle regardless of transport.
OnActionCompleted func(unified.ActionAuditRecord)
- Now func() time.Time
+ // OnActionTransition receives the audit record after every successfully
+ // persisted state transition: plan creation, approval decisions, and
+ // terminal execution outcomes (including refusals). Persistence always
+ // happens before publication, so a subscriber that reconciles origin
+ // surfaces (e.g. Patrol finding outcomes) never observes a state the
+ // store could still lose. Terminal records additionally flow through
+ // OnActionCompleted after this hook.
+ OnActionTransition func(unified.ActionAuditRecord)
+ Now func() time.Time
+}
+
+// PlanOptions carries broker-owned planning metadata that must never be
+// accepted from a public transport request body.
+type PlanOptions struct {
+ // Origin identifies the internal proposing surface and its
+ // correlation IDs. Nil for operator/API-initiated plans.
+ Origin *unified.ActionOrigin
}
// Sentinel errors for dependency failures. Callers map these to their
@@ -199,6 +215,13 @@ func NormalizeRequest(req unified.ActionRequest) unified.ActionRequest {
// requirements come from the capability's declared policy, never from the
// caller.
func (s *Service) Plan(ctx context.Context, orgID string, req unified.ActionRequest) (unified.ActionPlan, error) {
+ return s.PlanWithOptions(ctx, orgID, req, PlanOptions{})
+}
+
+// PlanWithOptions is Plan plus broker-owned metadata. In-process proposing
+// surfaces use it to stamp the action's origin; the HTTP adapter always
+// calls plain Plan so a public request can never claim a first-party origin.
+func (s *Service) PlanWithOptions(ctx context.Context, orgID string, req unified.ActionRequest, opts PlanOptions) (unified.ActionPlan, error) {
req.ResourceID = unified.CanonicalResourceID(req.ResourceID)
if req.ResourceID == "" {
return unified.ActionPlan{}, &actionplanner.ValidationError{Field: "resourceId", Message: "resource id is required"}
@@ -239,16 +262,46 @@ func (s *Service) Plan(ctx context.Context, orgID string, req unified.ActionRequ
if err != nil {
return unified.ActionPlan{}, err
}
- if err := PersistPlanAudit(store, req, plan); err != nil {
+ record, err := persistPlanAudit(store, req, plan, opts.Origin)
+ if err != nil {
return unified.ActionPlan{}, &PersistError{Op: "action plan audit", Err: err}
}
+ s.publishTransition(record)
return plan, nil
}
+// Capabilities returns the resource's advertised capability declarations
+// through the same registry resolution and typed errors as planning, so a
+// proposing surface can inspect capability names and parameter schemas
+// without guessing planner input or duplicating registry lookup.
+func (s *Service) Capabilities(ctx context.Context, orgID, resourceID string) ([]unified.ResourceCapability, error) {
+ _ = ctx
+ resourceID = unified.CanonicalResourceID(resourceID)
+ if resourceID == "" {
+ return nil, &actionplanner.ValidationError{Field: "resourceId", Message: "resource id is required"}
+ }
+ registry, err := s.registry(orgID)
+ if err != nil {
+ return nil, err
+ }
+ resource, ok := registry.Get(resourceID)
+ if !ok || resource == nil {
+ return nil, &ResourceNotFoundError{ResourceID: resourceID}
+ }
+ capabilities := make([]unified.ResourceCapability, len(resource.Capabilities))
+ copy(capabilities, resource.Capabilities)
+ return capabilities, nil
+}
+
// PersistPlanAudit records the planned action's audit record and its
// initial lifecycle events, deduplicating states that were already
// recorded for the same action ID (idempotent replans).
func PersistPlanAudit(store Store, req unified.ActionRequest, plan unified.ActionPlan) error {
+ _, err := persistPlanAudit(store, req, plan, nil)
+ return err
+}
+
+func persistPlanAudit(store Store, req unified.ActionRequest, plan unified.ActionPlan, origin *unified.ActionOrigin) (unified.ActionAuditRecord, error) {
state := PlannedActionState(plan)
record := unified.ActionAuditRecord{
ID: plan.ActionID,
@@ -257,14 +310,15 @@ func PersistPlanAudit(store Store, req unified.ActionRequest, plan unified.Actio
State: state,
Request: req,
Plan: plan,
+ Origin: unified.NormalizeActionOrigin(origin),
}
if err := store.RecordActionAudit(record); err != nil {
- return err
+ return unified.ActionAuditRecord{}, err
}
existingEvents, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 100)
if err != nil {
- return err
+ return unified.ActionAuditRecord{}, err
}
seenStates := map[unified.ActionState]bool{}
for _, event := range existingEvents {
@@ -279,7 +333,7 @@ func PersistPlanAudit(store Store, req unified.ActionRequest, plan unified.Actio
Actor: req.RequestedBy,
Message: "Action plan created.",
}); err != nil {
- return err
+ return unified.ActionAuditRecord{}, err
}
}
if state != unified.ActionStatePlanned && !seenStates[state] {
@@ -290,10 +344,10 @@ func PersistPlanAudit(store Store, req unified.ActionRequest, plan unified.Actio
Actor: req.RequestedBy,
Message: "Action is waiting for approval before execution.",
}); err != nil {
- return err
+ return unified.ActionAuditRecord{}, err
}
}
- return nil
+ return record, nil
}
// PlannedActionState is the initial audit state for a fresh plan: pending
@@ -341,6 +395,7 @@ func (s *Service) Decide(ctx context.Context, orgID, actionID string, approval u
}
return unified.ActionAuditRecord{}, &PersistError{Op: "action decision", Err: err}
}
+ s.publishTransition(updated)
return updated, nil
}
@@ -374,6 +429,7 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID, actor, reason st
if persistErr != nil {
return unified.ActionAuditRecord{}, &PersistError{Op: "refused action execution", Err: persistErr}
}
+ s.publishTransition(failed)
s.publishCompleted(failed)
return failed, err
}
@@ -388,6 +444,7 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID, actor, reason st
if persistErr != nil {
return unified.ActionAuditRecord{}, &PersistError{Op: "refused action execution", Err: persistErr}
}
+ s.publishTransition(failed)
s.publishCompleted(failed)
return failed, err
}
@@ -399,6 +456,7 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID, actor, reason st
if persistErr != nil {
return unified.ActionAuditRecord{}, &PersistError{Op: "refused action execution", Err: persistErr}
}
+ s.publishTransition(failed)
s.publishCompleted(failed)
return failed, err
}
@@ -427,6 +485,7 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID, actor, reason st
if err := store.RecordActionExecutionResult(completed, doneEvent); err != nil {
return unified.ActionAuditRecord{}, &PersistError{Op: "action execution result", Err: err}
}
+ s.publishTransition(completed)
s.publishCompleted(completed)
return completed, nil
}
@@ -519,3 +578,12 @@ func (s *Service) publishCompleted(record unified.ActionAuditRecord) {
}
s.OnActionCompleted(record)
}
+
+// publishTransition notifies the persisted-state subscriber. Callers invoke
+// it only after the corresponding store write succeeded.
+func (s *Service) publishTransition(record unified.ActionAuditRecord) {
+ if s == nil || s.OnActionTransition == nil {
+ return
+ }
+ s.OnActionTransition(record)
+}
diff --git a/internal/actionlifecycle/service_test.go b/internal/actionlifecycle/service_test.go
index 66d6eae4a3..5154c99452 100644
--- a/internal/actionlifecycle/service_test.go
+++ b/internal/actionlifecycle/service_test.go
@@ -380,3 +380,133 @@ func TestLifecycleFailsClosedWithoutStore(t *testing.T) {
t.Fatalf("Execute error = %v, want ErrStoreUnavailable", err)
}
}
+
+func TestCapabilitiesUsesSameRegistryResolutionAsPlanning(t *testing.T) {
+ now := time.Now().UTC()
+ env := newServiceEnv(t, testResource(now, unified.ApprovalAdmin))
+
+ capabilities, err := env.service.Capabilities(context.Background(), "default", "vm:42")
+ if err != nil {
+ t.Fatalf("Capabilities: %v", err)
+ }
+ if len(capabilities) != 1 || capabilities[0].Name != "restart" {
+ t.Fatalf("capabilities = %#v", capabilities)
+ }
+
+ var notFound *ResourceNotFoundError
+ if _, err := env.service.Capabilities(context.Background(), "default", "vm:404"); !errors.As(err, &notFound) {
+ t.Fatalf("unknown resource error = %v, want ResourceNotFoundError", err)
+ }
+}
+
+func TestPlanWithOptionsPersistsOriginAcrossLifecycle(t *testing.T) {
+ now := time.Now().UTC()
+ env := newServiceEnv(t, testResource(now, unified.ApprovalAdmin))
+
+ origin := &unified.ActionOrigin{
+ Surface: "patrol",
+ FindingID: "finding-9",
+ InvestigationID: "inv-9",
+ ProposalID: "prop-9",
+ }
+ plan, err := env.service.PlanWithOptions(context.Background(), "default", restartRequest(), PlanOptions{Origin: origin})
+ if err != nil {
+ t.Fatalf("PlanWithOptions: %v", err)
+ }
+
+ record, ok, err := env.store.GetActionAudit(plan.ActionID)
+ if err != nil || !ok {
+ t.Fatalf("GetActionAudit: ok=%v err=%v", ok, err)
+ }
+ if record.Origin == nil || record.Origin.FindingID != "finding-9" {
+ t.Fatalf("plan audit origin = %#v", record.Origin)
+ }
+
+ // Origin must survive the decision transition: the decision persists
+ // the record loaded from the store, so the broker-owned metadata
+ // stays reconcilable at approval time.
+ updated, err := env.service.Decide(context.Background(), "default", plan.ActionID, unified.ActionApprovalRecord{
+ Actor: "[email protected]", Method: unified.MethodAPI, Outcome: unified.OutcomeApproved,
+ })
+ if err != nil {
+ t.Fatalf("Decide: %v", err)
+ }
+ if updated.Origin == nil || updated.Origin.ProposalID != "prop-9" {
+ t.Fatalf("decision record origin = %#v", updated.Origin)
+ }
+
+ // Plain Plan must never stamp an origin.
+ plain := restartRequest()
+ plain.RequestID = "req-plain"
+ plainPlan, err := env.service.Plan(context.Background(), "default", plain)
+ if err != nil {
+ t.Fatalf("Plan: %v", err)
+ }
+ plainRecord, ok, err := env.store.GetActionAudit(plainPlan.ActionID)
+ if err != nil || !ok {
+ t.Fatalf("GetActionAudit(plain): ok=%v err=%v", ok, err)
+ }
+ if plainRecord.Origin != nil {
+ t.Fatalf("plain plan must not carry an origin, got %#v", plainRecord.Origin)
+ }
+}
+
+func TestOnActionTransitionFiresAfterEachPersistedState(t *testing.T) {
+ now := time.Now().UTC()
+ env := newServiceEnv(t, testResource(now, unified.ApprovalAdmin))
+ var transitions []unified.ActionState
+ env.service.OnActionTransition = func(record unified.ActionAuditRecord) {
+ transitions = append(transitions, record.State)
+ }
+
+ plan, err := env.service.Plan(context.Background(), "default", restartRequest())
+ if err != nil {
+ t.Fatalf("Plan: %v", err)
+ }
+ if _, err := env.service.Decide(context.Background(), "default", plan.ActionID, unified.ActionApprovalRecord{
+ Actor: "[email protected]", Method: unified.MethodAPI, Outcome: unified.OutcomeApproved,
+ }); err != nil {
+ t.Fatalf("Decide: %v", err)
+ }
+ if _, err := env.service.Execute(context.Background(), "default", plan.ActionID, "[email protected]", ""); err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+
+ want := []unified.ActionState{unified.ActionStatePending, unified.ActionStateApproved, unified.ActionStateCompleted}
+ if len(transitions) != len(want) {
+ t.Fatalf("transitions = %v, want %v", transitions, want)
+ }
+ for i := range want {
+ if transitions[i] != want[i] {
+ t.Fatalf("transitions = %v, want %v", transitions, want)
+ }
+ }
+}
+
+func TestOnActionTransitionFiresForPersistedRefusals(t *testing.T) {
+ now := time.Now().UTC()
+ env := newServiceEnv(t, testResource(now, unified.ApprovalNone))
+ var transitions []unified.ActionState
+ env.service.OnActionTransition = func(record unified.ActionAuditRecord) {
+ transitions = append(transitions, record.State)
+ }
+
+ plan, err := env.service.Plan(context.Background(), "default", restartRequest())
+ if err != nil {
+ t.Fatalf("Plan: %v", err)
+ }
+ if err := env.store.SetResourceOperatorState(unified.ResourceOperatorState{
+ CanonicalID: "vm:42",
+ NeverAutoRemediate: true,
+ }); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+ if _, err := env.service.Execute(context.Background(), "default", plan.ActionID, "agent:test", ""); !errors.Is(err, unified.ErrResourceRemediationLocked) {
+ t.Fatalf("error = %v, want ErrResourceRemediationLocked", err)
+ }
+
+ want := []unified.ActionState{unified.ActionStatePlanned, unified.ActionStateFailed}
+ if len(transitions) != len(want) || transitions[0] != want[0] || transitions[1] != want[1] {
+ t.Fatalf("transitions = %v, want %v", transitions, want)
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index fcb970eda2..ddc27d5b4c 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -20422,3 +20422,30 @@ func TestProUpdateBrokerWiringContract(t *testing.T) {
}
}
}
+
+func TestContract_PatrolActionBrokerIsPlanOnly(t *testing.T) {
+ source, err := os.ReadFile("patrol_action_broker.go")
+ if err != nil {
+ t.Fatalf("read patrol_action_broker.go: %v", err)
+ }
+ src := string(source)
+ for _, snippet := range []string{
+ // Proposals ride the shared lifecycle service with broker-owned
+ // origin metadata and the fixed Patrol actor.
+ "PlanWithOptions(ctx, b.orgID",
+ `patrolActionBrokerActor = "pulse_patrol"`,
+ `patrolActionOriginSurface = "patrol"`,
+ "rejectSensitiveParams",
+ } {
+ if !strings.Contains(src, snippet) {
+ t.Fatalf("patrol_action_broker.go must pin plan-only broker snippet %q", snippet)
+ }
+ }
+ // The broker must stay a proposer: no decision or execution calls on
+ // the lifecycle service, ever.
+ for _, forbidden := range []string{".Decide(", ".Execute(", "ExecuteAction(", "ExecuteCommand("} {
+ if strings.Contains(src, forbidden) {
+ t.Fatalf("patrol_action_broker.go must not dispatch via %q", forbidden)
+ }
+ }
+}
diff --git a/internal/api/patrol_action_broker.go b/internal/api/patrol_action_broker.go
new file mode 100644
index 0000000000..abc7a16213
--- /dev/null
+++ b/internal/api/patrol_action_broker.go
@@ -0,0 +1,155 @@
+package api
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
+)
+
+// patrolActionBrokerActor is the fixed requestedBy identity for every
+// Patrol-proposed action. Enterprise code cannot influence it.
+const patrolActionBrokerActor = "pulse_patrol"
+
+// patrolActionOriginSurface tags Patrol-proposed action audits so later
+// decisions and terminal outcomes can be reconciled onto the finding.
+const patrolActionOriginSurface = "patrol"
+
+// patrolActionBroker is the org-bound core adapter behind
+// aicontracts.OrchestratorActionBroker. It routes every Patrol proposal
+// through the shared action lifecycle service: identical registry lookup,
+// capability validation, availability checks, plan hashing, and audit
+// persistence as the REST plan endpoint. Submit is plan-only; approval and
+// execution remain on the canonical decision/execute lifecycle, so the
+// enterprise investigation side stays a proposer, never a dispatcher.
+type patrolActionBroker struct {
+ orgID string
+ // lifecycle resolves the shared service per call so late-bound
+ // executor and publisher wiring on ResourceHandlers stays current.
+ lifecycle func() *actionlifecycle.Service
+}
+
+// NewPatrolActionBroker builds the tenant-bound Patrol proposal broker over
+// the shared action lifecycle service.
+func NewPatrolActionBroker(orgID string, resources *ResourceHandlers) aicontracts.OrchestratorActionBroker {
+ return &patrolActionBroker{
+ orgID: strings.TrimSpace(orgID),
+ lifecycle: resources.ActionLifecycle,
+ }
+}
+
+func (b *patrolActionBroker) Capabilities(ctx context.Context, resourceID string) (aicontracts.ActionCapabilityCatalog, error) {
+ resourceID = unified.CanonicalResourceID(resourceID)
+ capabilities, err := b.lifecycle().Capabilities(ctx, b.orgID, resourceID)
+ if err != nil {
+ return aicontracts.ActionCapabilityCatalog{}, err
+ }
+ catalog := aicontracts.ActionCapabilityCatalog{
+ ResourceID: resourceID,
+ Capabilities: make([]aicontracts.ActionCapabilityInfo, 0, len(capabilities)),
+ }
+ for _, capability := range capabilities {
+ info := aicontracts.ActionCapabilityInfo{
+ Name: capability.Name,
+ Description: capability.Description,
+ MinimumApprovalLevel: string(capability.MinimumApprovalLevel),
+ Platform: capability.Platform,
+ Params: make([]aicontracts.ActionCapabilityParamInfo, 0, len(capability.Params)),
+ }
+ for _, param := range capability.Params {
+ info.Params = append(info.Params, aicontracts.ActionCapabilityParamInfo{
+ Name: param.Name,
+ Type: param.Type,
+ Required: param.Required,
+ Enum: append([]string(nil), param.Enum...),
+ Description: param.Description,
+ Sensitive: param.IsSensitive,
+ })
+ }
+ catalog.Capabilities = append(catalog.Capabilities, info)
+ }
+ return catalog, nil
+}
+
+func (b *patrolActionBroker) Submit(ctx context.Context, proposal aicontracts.ActionProposal) (aicontracts.ActionDisposition, error) {
+ proposal.ProposalID = strings.TrimSpace(proposal.ProposalID)
+ proposal.FindingID = strings.TrimSpace(proposal.FindingID)
+ proposal.InvestigationID = strings.TrimSpace(proposal.InvestigationID)
+ proposal.ResourceID = unified.CanonicalResourceID(proposal.ResourceID)
+ proposal.CapabilityName = strings.TrimSpace(proposal.CapabilityName)
+ proposal.Reason = strings.TrimSpace(proposal.Reason)
+ if proposal.ResourceID == "" {
+ return aicontracts.ActionDisposition{}, fmt.Errorf("action proposal requires a resource id")
+ }
+ if proposal.CapabilityName == "" {
+ return aicontracts.ActionDisposition{}, fmt.Errorf("action proposal requires a capability name")
+ }
+ if proposal.Reason == "" {
+ return aicontracts.ActionDisposition{}, fmt.Errorf("action proposal requires a reason")
+ }
+
+ if err := b.rejectSensitiveParams(ctx, proposal); err != nil {
+ return aicontracts.ActionDisposition{}, err
+ }
+
+ plan, err := b.lifecycle().PlanWithOptions(ctx, b.orgID, unified.ActionRequest{
+ RequestID: proposal.ProposalID,
+ ResourceID: proposal.ResourceID,
+ CapabilityName: proposal.CapabilityName,
+ Params: proposal.Params,
+ Reason: proposal.Reason,
+ RequestedBy: patrolActionBrokerActor,
+ }, actionlifecycle.PlanOptions{
+ Origin: &unified.ActionOrigin{
+ Surface: patrolActionOriginSurface,
+ FindingID: proposal.FindingID,
+ InvestigationID: proposal.InvestigationID,
+ ProposalID: proposal.ProposalID,
+ },
+ })
+ if err != nil {
+ return aicontracts.ActionDisposition{}, err
+ }
+
+ // Plan-only by contract: even an ApprovalNone capability is returned
+ // as a planned disposition and never auto-executed on submission.
+ return aicontracts.ActionDisposition{
+ ActionID: plan.ActionID,
+ State: string(actionlifecycle.PlannedActionState(plan)),
+ Plan: *approvalPlanRequestToInfo(&plan),
+ }, nil
+}
+
+// rejectSensitiveParams fails a proposal that populates any parameter the
+// capability declares sensitive. Secrets must come from an operator on the
+// canonical surfaces, never from model output that would persist in
+// investigation stores and action audit records.
+func (b *patrolActionBroker) rejectSensitiveParams(ctx context.Context, proposal aicontracts.ActionProposal) error {
+ if len(proposal.Params) == 0 {
+ return nil
+ }
+ capabilities, err := b.lifecycle().Capabilities(ctx, b.orgID, proposal.ResourceID)
+ if err != nil {
+ return err
+ }
+ for _, capability := range capabilities {
+ if !strings.EqualFold(strings.TrimSpace(capability.Name), proposal.CapabilityName) {
+ continue
+ }
+ for _, param := range capability.Params {
+ if !param.IsSensitive {
+ continue
+ }
+ if value, ok := proposal.Params[param.Name]; ok && value != nil {
+ return fmt.Errorf("%w: parameter %q on capability %q", aicontracts.ErrSensitiveParamsRequireOperator, param.Name, proposal.CapabilityName)
+ }
+ }
+ return nil
+ }
+ // Unknown capability names fall through to the planner, which owns
+ // the canonical capability-not-found refusal.
+ return nil
+}
diff --git a/internal/api/patrol_action_broker_test.go b/internal/api/patrol_action_broker_test.go
new file mode 100644
index 0000000000..9d8802490b
--- /dev/null
+++ b/internal/api/patrol_action_broker_test.go
@@ -0,0 +1,187 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
+)
+
+func newPatrolBrokerTestHandlers(t *testing.T, minimumApproval unified.ActionApprovalLevel) (*ResourceHandlers, *stubActionExecutor) {
+ t.Helper()
+ now := time.Now().UTC()
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{
+ {
+ ID: "vm:42",
+ Type: unified.ResourceTypeVM,
+ Name: "web-42",
+ Status: unified.StatusWarning,
+ LastSeen: now,
+ UpdatedAt: now,
+ Sources: []unified.DataSource{unified.SourceProxmox},
+ Capabilities: []unified.ResourceCapability{
+ {
+ Name: "restart",
+ Type: unified.CapabilityTypeCommon,
+ Description: "Restart the VM",
+ MinimumApprovalLevel: minimumApproval,
+ InternalHandler: "proxmox.vm.restart",
+ Params: []unified.CapabilityParam{
+ {Name: "mode", Type: "string", Required: true, Enum: []string{"graceful", "force"}},
+ },
+ },
+ {
+ Name: "join_cluster",
+ Type: unified.CapabilityTypeCommon,
+ Description: "Join an authenticated cluster",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ InternalHandler: "proxmox.vm.join",
+ Params: []unified.CapabilityParam{
+ {Name: "join_token", Type: "string", Required: true, IsSensitive: true},
+ },
+ },
+ },
+ },
+ },
+ })
+ executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true}}
+ h.SetActionExecutor(executor)
+ return h, executor
+}
+
+func patrolTestProposal() aicontracts.ActionProposal {
+ return aicontracts.ActionProposal{
+ ProposalID: "prop-1",
+ FindingID: "finding-1",
+ InvestigationID: "inv-1",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Params: map[string]any{"mode": "graceful"},
+ Reason: "Recover after confirmed outage",
+ }
+}
+
+func TestPatrolActionBrokerSubmitPlansThroughCanonicalLifecycle(t *testing.T) {
+ h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
+ broker := NewPatrolActionBroker("default", h)
+
+ disposition, err := broker.Submit(context.Background(), patrolTestProposal())
+ if err != nil {
+ t.Fatalf("Submit: %v", err)
+ }
+ if disposition.ActionID == "" {
+ t.Fatal("disposition has no action id")
+ }
+ if disposition.State != string(unified.ActionStatePending) {
+ t.Fatalf("state = %q, want pending_approval", disposition.State)
+ }
+ if !disposition.Plan.RequiresApproval || disposition.Plan.ApprovalPolicy != string(unified.ApprovalAdmin) {
+ t.Fatalf("plan projection = %#v", disposition.Plan)
+ }
+ if executor.calls != 0 {
+ t.Fatalf("submit must never execute, executor calls = %d", executor.calls)
+ }
+
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("getStore: %v", err)
+ }
+ record, ok, err := store.GetActionAudit(disposition.ActionID)
+ if err != nil || !ok {
+ t.Fatalf("GetActionAudit: ok=%v err=%v", ok, err)
+ }
+ if record.Request.RequestedBy != patrolActionBrokerActor {
+ t.Fatalf("requestedBy = %q, want %q", record.Request.RequestedBy, patrolActionBrokerActor)
+ }
+ if record.Origin == nil ||
+ record.Origin.Surface != patrolActionOriginSurface ||
+ record.Origin.FindingID != "finding-1" ||
+ record.Origin.InvestigationID != "inv-1" ||
+ record.Origin.ProposalID != "prop-1" {
+ t.Fatalf("audit origin = %#v", record.Origin)
+ }
+}
+
+func TestPatrolActionBrokerSubmitIsPlanOnlyForApprovalNone(t *testing.T) {
+ h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalNone)
+ broker := NewPatrolActionBroker("default", h)
+
+ disposition, err := broker.Submit(context.Background(), patrolTestProposal())
+ if err != nil {
+ t.Fatalf("Submit: %v", err)
+ }
+ if disposition.State != string(unified.ActionStatePlanned) {
+ t.Fatalf("state = %q, want planned", disposition.State)
+ }
+ if disposition.Plan.RequiresApproval {
+ t.Fatal("ApprovalNone capability should not require approval")
+ }
+ if executor.calls != 0 {
+ t.Fatalf("submit must never auto-execute, executor calls = %d", executor.calls)
+ }
+}
+
+func TestPatrolActionBrokerRejectsSensitiveParams(t *testing.T) {
+ h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
+ broker := NewPatrolActionBroker("default", h)
+
+ proposal := patrolTestProposal()
+ proposal.CapabilityName = "join_cluster"
+ proposal.Params = map[string]any{"join_token": "sekret-token-value"}
+ _, err := broker.Submit(context.Background(), proposal)
+ if !errors.Is(err, aicontracts.ErrSensitiveParamsRequireOperator) {
+ t.Fatalf("error = %v, want ErrSensitiveParamsRequireOperator", err)
+ }
+ if executor.calls != 0 {
+ t.Fatalf("executor calls = %d, want 0", executor.calls)
+ }
+
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("getStore: %v", err)
+ }
+ audits, err := store.GetActionAudits("vm:42", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits: %v", err)
+ }
+ if len(audits) != 0 {
+ t.Fatalf("sensitive-param proposals must not persist audits, got %d", len(audits))
+ }
+}
+
+func TestPatrolActionBrokerCapabilitiesCatalog(t *testing.T) {
+ h, _ := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
+ broker := NewPatrolActionBroker("default", h)
+
+ catalog, err := broker.Capabilities(context.Background(), "vm:42")
+ if err != nil {
+ t.Fatalf("Capabilities: %v", err)
+ }
+ if catalog.ResourceID != "vm:42" || len(catalog.Capabilities) != 2 {
+ t.Fatalf("catalog = %#v", catalog)
+ }
+ byName := map[string]aicontracts.ActionCapabilityInfo{}
+ for _, capability := range catalog.Capabilities {
+ byName[capability.Name] = capability
+ }
+ restart := byName["restart"]
+ if restart.MinimumApprovalLevel != string(unified.ApprovalAdmin) || len(restart.Params) != 1 || restart.Params[0].Sensitive {
+ t.Fatalf("restart capability = %#v", restart)
+ }
+ join := byName["join_cluster"]
+ if len(join.Params) != 1 || !join.Params[0].Sensitive {
+ t.Fatalf("join_cluster capability must mark its token sensitive: %#v", join)
+ }
+
+ if _, err := broker.Capabilities(context.Background(), "vm:404"); err == nil {
+ t.Fatal("unknown resource must error")
+ }
+}
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index ce7d1cd71f..c648bef747 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -225,12 +225,43 @@ type ActionAuditRecord struct {
State ActionState `json:"state"`
Request ActionRequest `json:"request"`
Plan ActionPlan `json:"plan"`
+ Origin *ActionOrigin `json:"origin,omitempty"`
Approvals []ActionApprovalRecord `json:"approvals,omitempty"`
Result *ExecutionResult `json:"result,omitempty"`
Verification *ActionVerificationResult `json:"verification,omitempty"`
VerificationOutcome VerificationOutcome `json:"verificationOutcome"`
}
+// ActionOrigin records which internal surface proposed the action and the
+// correlation identifiers that surface needs to reconcile decisions and
+// terminal outcomes back onto its own records (e.g. a Patrol finding).
+// Origin is broker-owned metadata: it is set by in-process planning callers
+// only and is never accepted from the public plan request body.
+type ActionOrigin struct {
+ Surface string `json:"surface"`
+ FindingID string `json:"findingId,omitempty"`
+ InvestigationID string `json:"investigationId,omitempty"`
+ ProposalID string `json:"proposalId,omitempty"`
+}
+
+// NormalizeActionOrigin trims origin fields and collapses an all-empty
+// origin to nil so absent metadata never persists as an empty object.
+func NormalizeActionOrigin(origin *ActionOrigin) *ActionOrigin {
+ if origin == nil {
+ return nil
+ }
+ normalized := ActionOrigin{
+ Surface: strings.TrimSpace(origin.Surface),
+ FindingID: strings.TrimSpace(origin.FindingID),
+ InvestigationID: strings.TrimSpace(origin.InvestigationID),
+ ProposalID: strings.TrimSpace(origin.ProposalID),
+ }
+ if normalized == (ActionOrigin{}) {
+ return nil
+ }
+ return &normalized
+}
+
// ActionLifecycleEvent represents an append-only state transition in an action's life.
type ActionLifecycleEvent struct {
ActionID string `json:"actionId"`
@@ -563,6 +594,7 @@ func NormalizeActionAuditRecord(record ActionAuditRecord) (ActionAuditRecord, er
record.Request.CapabilityName = strings.TrimSpace(record.Request.CapabilityName)
record.Request.Reason = strings.TrimSpace(record.Request.Reason)
record.Request.RequestedBy = strings.TrimSpace(record.Request.RequestedBy)
+ record.Origin = NormalizeActionOrigin(record.Origin)
if record.Request.ResourceID == "" {
return ActionAuditRecord{}, fmt.Errorf("action request resource id required")
}
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index 61b69eaae2..aed6cc01a8 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -428,7 +428,8 @@ func (s *SQLiteResourceStore) initSchema() error {
plan_json TEXT NOT NULL,
approvals_json TEXT,
result_json TEXT,
- verification_outcome_json TEXT NOT NULL DEFAULT ''
+ verification_outcome_json TEXT NOT NULL DEFAULT '',
+ origin_json TEXT
);
CREATE INDEX IF NOT EXISTS idx_action_audits_canonical_created ON action_audits(canonical_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_action_audits_action_id ON action_audits(action_id);
@@ -550,20 +551,25 @@ func (s *SQLiteResourceStore) migrateResourceIdentitiesSchema() error {
return nil
}
-// migrateActionAuditsSchema adds the verification_outcome_json column to
-// older action_audits tables so the VerificationOutcome field on
-// ActionAuditRecord persists across restarts. Records written before the
-// migration read back with the default unknown status via the normalizer.
+// migrateActionAuditsSchema adds the verification_outcome_json and
+// origin_json columns to older action_audits tables so the
+// VerificationOutcome and broker-owned Origin fields on ActionAuditRecord
+// persist across restarts. Records written before the migration read back
+// with the default unknown status / nil origin via the normalizer.
func (s *SQLiteResourceStore) migrateActionAuditsSchema() error {
columns, err := s.tableColumns("action_audits")
if err != nil {
return err
}
- if _, ok := columns["verification_outcome_json"]; ok {
- return nil
+ if _, ok := columns["verification_outcome_json"]; !ok {
+ if _, err := s.db.Exec("ALTER TABLE action_audits ADD COLUMN verification_outcome_json TEXT NOT NULL DEFAULT ''"); err != nil {
+ return fmt.Errorf("add action_audits.verification_outcome_json column: %w", err)
+ }
}
- if _, err := s.db.Exec("ALTER TABLE action_audits ADD COLUMN verification_outcome_json TEXT NOT NULL DEFAULT ''"); err != nil {
- return fmt.Errorf("add action_audits.verification_outcome_json column: %w", err)
+ if _, ok := columns["origin_json"]; !ok {
+ if _, err := s.db.Exec("ALTER TABLE action_audits ADD COLUMN origin_json TEXT"); err != nil {
+ return fmt.Errorf("add action_audits.origin_json column: %w", err)
+ }
}
return nil
}
@@ -1675,10 +1681,18 @@ func recordActionAuditSQL(exec sqlExecutor, record ActionAuditRecord) error {
if err != nil {
return fmt.Errorf("marshal verification outcome: %w", err)
}
+ originJSON := ""
+ if origin := NormalizeActionOrigin(record.Origin); origin != nil {
+ encoded, err := json.Marshal(origin)
+ if err != nil {
+ return fmt.Errorf("marshal action origin: %w", err)
+ }
+ originJSON = string(encoded)
+ }
_, err = exec.Exec(`
- INSERT INTO action_audits (id, action_id, canonical_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json, verification_outcome_json)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO action_audits (id, action_id, canonical_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json, verification_outcome_json, origin_json)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
action_id=excluded.action_id,
canonical_id=excluded.canonical_id,
@@ -1690,8 +1704,9 @@ func recordActionAuditSQL(exec sqlExecutor, record ActionAuditRecord) error {
plan_json=excluded.plan_json,
approvals_json=excluded.approvals_json,
result_json=excluded.result_json,
- verification_outcome_json=excluded.verification_outcome_json
- `, record.ID, record.ID, CanonicalResourceID(record.Request.ResourceID), record.Request.RequestID, record.CreatedAt, record.UpdatedAt, string(record.State), string(requestJSON), string(planJSON), string(approvalsJSON), string(resultJSON), string(verificationOutcomeJSON))
+ verification_outcome_json=excluded.verification_outcome_json,
+ origin_json=excluded.origin_json
+ `, record.ID, record.ID, CanonicalResourceID(record.Request.ResourceID), record.Request.RequestID, record.CreatedAt, record.UpdatedAt, string(record.State), string(requestJSON), string(planJSON), string(approvalsJSON), string(resultJSON), string(verificationOutcomeJSON), originJSON)
if err != nil {
return fmt.Errorf("insert action audit: %w", err)
}
@@ -1723,8 +1738,8 @@ func scanActionAuditRecord(scanner actionAuditScanner) (ActionAuditRecord, error
var record ActionAuditRecord
var stateStr string
var actionID, requestID string
- var requestJSON, planJSON, approvalsJSON, resultJSON, verificationOutcomeJSON sql.NullString
- if err := scanner.Scan(&record.ID, &actionID, &requestID, &record.CreatedAt, &record.UpdatedAt, &stateStr, &requestJSON, &planJSON, &approvalsJSON, &resultJSON, &verificationOutcomeJSON); err != nil {
+ var requestJSON, planJSON, approvalsJSON, resultJSON, verificationOutcomeJSON, originJSON sql.NullString
+ if err := scanner.Scan(&record.ID, &actionID, &requestID, &record.CreatedAt, &record.UpdatedAt, &stateStr, &requestJSON, &planJSON, &approvalsJSON, &resultJSON, &verificationOutcomeJSON, &originJSON); err != nil {
return ActionAuditRecord{}, err
}
@@ -1759,6 +1774,13 @@ func scanActionAuditRecord(scanner actionAuditScanner) (ActionAuditRecord, error
record.VerificationOutcome = outcome
}
record.VerificationOutcome = NormalizeVerificationOutcome(record.VerificationOutcome)
+ if originJSON.Valid && originJSON.String != "" && originJSON.String != "null" {
+ var origin ActionOrigin
+ if err := json.Unmarshal([]byte(originJSON.String), &origin); err != nil {
+ return ActionAuditRecord{}, fmt.Errorf("unmarshal action origin: %w", err)
+ }
+ record.Origin = NormalizeActionOrigin(&origin)
+ }
record.Request.RequestID = requestID
record.Request.ResourceID = CanonicalResourceID(record.Request.ResourceID)
_ = actionID
@@ -1801,7 +1823,7 @@ func (s *SQLiteResourceStore) GetActionAudit(actionID string) (ActionAuditRecord
func (s *SQLiteResourceStore) GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error) {
query := `
- SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json, verification_outcome_json
+ SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json, verification_outcome_json, origin_json
FROM action_audits`
args := []any{}
@@ -2024,7 +2046,7 @@ func (s *SQLiteResourceStore) getActionAudit(actionID string) (ActionAuditRecord
return ActionAuditRecord{}, false, nil
}
row := s.db.QueryRow(`
- SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json, verification_outcome_json
+ SELECT id, action_id, request_id, created_at, updated_at, state, request_json, plan_json, approvals_json, result_json, verification_outcome_json, origin_json
FROM action_audits
WHERE id = ?
`, actionID)
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index 6e411d7f6f..f7460a4c34 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -2540,3 +2540,64 @@ func TestCapResourceChanges_KeepsNewestRows(t *testing.T) {
}
}
}
+
+func TestSQLiteStoreActionAuditOriginRoundTrip(t *testing.T) {
+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatalf("NewSQLiteResourceStore returned error: %v", err)
+ }
+ defer store.Close()
+
+ record := ActionAuditRecord{
+ ID: "act_origin_roundtrip",
+ State: ActionStatePending,
+ Request: ActionRequest{
+ RequestID: "prop-1",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ RequestedBy: "pulse_patrol",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_origin_roundtrip",
+ RequestID: "prop-1",
+ Allowed: true,
+ RequiresApproval: true,
+ },
+ Origin: &ActionOrigin{
+ Surface: " patrol ",
+ FindingID: "finding-1",
+ InvestigationID: "inv-1",
+ ProposalID: "prop-1",
+ },
+ }
+ if err := store.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit: %v", err)
+ }
+
+ got, ok, err := store.GetActionAudit("act_origin_roundtrip")
+ if err != nil || !ok {
+ t.Fatalf("GetActionAudit: ok=%v err=%v", ok, err)
+ }
+ if got.Origin == nil {
+ t.Fatal("origin was not persisted")
+ }
+ if got.Origin.Surface != "patrol" || got.Origin.FindingID != "finding-1" || got.Origin.InvestigationID != "inv-1" || got.Origin.ProposalID != "prop-1" {
+ t.Fatalf("origin round-trip = %#v", got.Origin)
+ }
+
+ // An all-empty origin must normalize to nil, never persist as an
+ // empty object.
+ record.ID = "act_origin_empty"
+ record.Plan.ActionID = record.ID
+ record.Origin = &ActionOrigin{Surface: " "}
+ if err := store.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit(empty origin): %v", err)
+ }
+ got, ok, err = store.GetActionAudit("act_origin_empty")
+ if err != nil || !ok {
+ t.Fatalf("GetActionAudit(empty origin): ok=%v err=%v", ok, err)
+ }
+ if got.Origin != nil {
+ t.Fatalf("empty origin should read back nil, got %#v", got.Origin)
+ }
+}
diff --git a/pkg/aicontracts/action_broker.go b/pkg/aicontracts/action_broker.go
new file mode 100644
index 0000000000..85a608985b
--- /dev/null
+++ b/pkg/aicontracts/action_broker.go
@@ -0,0 +1,105 @@
+package aicontracts
+
+import (
+ "context"
+ "errors"
+)
+
+// ---------------------------------------------------------------------------
+// Typed action proposals
+//
+// OrchestratorActionBroker is the ONLY sanctioned route from an enterprise
+// Patrol investigation to a Pulse infrastructure mutation. The enterprise
+// side is a proposer, never a dispatcher: the contract deliberately has no
+// org ID (the core adapter is tenant-bound at construction), no requestedBy
+// (the adapter always stamps the fixed Patrol actor), no autonomy, risk,
+// approval-policy, or destructive fields (authorization derives from the
+// capability's declared policy, never from model or enterprise input), no
+// Decide/Execute methods, and no command or target-host fields. Submit is
+// plan-only; approval and execution stay on the canonical core lifecycle.
+// ---------------------------------------------------------------------------
+
+// ActionProposal is a typed, no-authority remediation proposal produced by
+// an investigation. Params must reference the capability's declared
+// parameter schema; free-form command text is not representable.
+type ActionProposal struct {
+ ProposalID string `json:"proposal_id"`
+ FindingID string `json:"finding_id"`
+ InvestigationID string `json:"investigation_id"`
+ ResourceID string `json:"resource_id"`
+ CapabilityName string `json:"capability_name"`
+ Params map[string]any `json:"params,omitempty"`
+ Reason string `json:"reason"`
+ EvidenceIDs []string `json:"evidence_ids,omitempty"`
+}
+
+// ActionCapabilityCatalog is the read-only projection of a resource's
+// advertised capabilities, so an investigation can select a capability and
+// fill its declared parameters instead of guessing planner input.
+type ActionCapabilityCatalog struct {
+ ResourceID string `json:"resource_id"`
+ Capabilities []ActionCapabilityInfo `json:"capabilities"`
+}
+
+// ActionCapabilityInfo describes one advertised capability.
+type ActionCapabilityInfo struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ MinimumApprovalLevel string `json:"minimum_approval_level"`
+ Platform string `json:"platform,omitempty"`
+ Params []ActionCapabilityParamInfo `json:"params,omitempty"`
+}
+
+// ActionCapabilityParamInfo describes one declared capability parameter.
+// Sensitive parameters must never be populated by a model-driven proposal;
+// the broker rejects such proposals so secrets stay out of model output,
+// investigation persistence, and action audit records.
+type ActionCapabilityParamInfo struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Required bool `json:"required"`
+ Enum []string `json:"enum,omitempty"`
+ Description string `json:"description,omitempty"`
+ Sensitive bool `json:"sensitive,omitempty"`
+}
+
+// ActionDisposition reports what the canonical planner did with a proposal.
+// State reflects the persisted audit state (pending_approval or planned);
+// the proposal never executes as a side effect of submission. Plan reuses
+// the existing safe ActionPlanInfo projection shared with approval
+// surfaces (see fix_execution.go).
+type ActionDisposition struct {
+ ActionID string `json:"action_id"`
+ State string `json:"state"`
+ Plan ActionPlanInfo `json:"plan"`
+}
+
+// ActionReference links an investigation to its canonical action lifecycle
+// record. It replaces the command-shaped Fix as the executable artifact:
+// the investigation stores only this reference, while proposal parameters
+// and lifecycle state live in the canonical action audit.
+type ActionReference struct {
+ ActionID string `json:"action_id"`
+ ProposalID string `json:"proposal_id,omitempty"`
+ ResourceID string `json:"resource_id"`
+ CapabilityName string `json:"capability_name"`
+ State string `json:"state"`
+ Plan ActionPlanInfo `json:"plan"`
+}
+
+// ErrSensitiveParamsRequireOperator reports that a proposal populated a
+// parameter the capability declares sensitive. Such proposals stop for
+// operator input instead of persisting secret material.
+var ErrSensitiveParamsRequireOperator = errors.New("proposal populates a sensitive capability parameter; operator input required")
+
+// OrchestratorActionBroker is the proposal seam between the enterprise
+// investigation orchestrator and the core action lifecycle.
+type OrchestratorActionBroker interface {
+ // Capabilities returns the resource's advertised capability catalog.
+ Capabilities(ctx context.Context, resourceID string) (ActionCapabilityCatalog, error)
+ // Submit plans the proposal through the canonical action lifecycle
+ // and returns its persisted disposition. Plan-only: even a capability
+ // that requires no approval is returned as a planned disposition,
+ // never auto-executed by submission.
+ Submit(ctx context.Context, proposal ActionProposal) (ActionDisposition, error)
+}
diff --git a/pkg/aicontracts/contracts_test.go b/pkg/aicontracts/contracts_test.go
index a3c7d5145e..57be750c3c 100644
--- a/pkg/aicontracts/contracts_test.go
+++ b/pkg/aicontracts/contracts_test.go
@@ -2,6 +2,7 @@ package aicontracts
import (
"encoding/json"
+ "reflect"
"strings"
"testing"
@@ -151,3 +152,100 @@ func TestEmptyFix_UsesCanonicalEmptyCollections(t *testing.T) {
t.Fatalf("expected empty fix to retain commands array, got %s", payload)
}
}
+
+func TestActionProposalWireShapeIsTypedAndCommandFree(t *testing.T) {
+ payload, err := json.Marshal(ActionProposal{
+ ProposalID: "prop-1",
+ FindingID: "finding-1",
+ InvestigationID: "inv-1",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Params: map[string]any{"mode": "graceful"},
+ Reason: "recover",
+ })
+ if err != nil {
+ t.Fatalf("marshal action proposal: %v", err)
+ }
+ for _, want := range []string{`"proposal_id":"prop-1"`, `"resource_id":"vm:42"`, `"capability_name":"restart"`} {
+ if !strings.Contains(string(payload), want) {
+ t.Fatalf("proposal wire shape missing %s: %s", want, payload)
+ }
+ }
+ // The proposal contract must stay command-free: no command, target
+ // host, risk, destructive, or approval fields exist for enterprise
+ // code to smuggle authority through.
+ for _, forbidden := range []string{"command", "target_host", "risk", "destructive", "approval", "autonomy"} {
+ if strings.Contains(string(payload), forbidden) {
+ t.Fatalf("proposal wire shape must not carry %q: %s", forbidden, payload)
+ }
+ }
+}
+
+func TestActionReferenceIsAdditiveOnInvestigationShapes(t *testing.T) {
+ session := EmptyInvestigationSession()
+ session.Action = &ActionReference{
+ ActionID: "act-1",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ State: "pending_approval",
+ }
+ payload, err := json.Marshal(session)
+ if err != nil {
+ t.Fatalf("marshal investigation session with action reference: %v", err)
+ }
+ if !strings.Contains(string(payload), `"action":{`) || !strings.Contains(string(payload), `"action_id":"act-1"`) {
+ t.Fatalf("investigation session must carry the action reference, got %s", payload)
+ }
+
+ record := EmptyInvestigationRecord()
+ record.Action = &ActionReference{ActionID: "act-1", ResourceID: "vm:42", CapabilityName: "restart", State: "planned"}
+ recordPayload, err := json.Marshal(record)
+ if err != nil {
+ t.Fatalf("marshal investigation record with action reference: %v", err)
+ }
+ if !strings.Contains(string(recordPayload), `"action_id":"act-1"`) {
+ t.Fatalf("investigation record must carry the action reference, got %s", recordPayload)
+ }
+
+ // Absent references stay absent: legacy readers must not see a new
+ // non-optional field.
+ emptyPayload, err := json.Marshal(EmptyInvestigationSession())
+ if err != nil {
+ t.Fatalf("marshal empty investigation session: %v", err)
+ }
+ if strings.Contains(string(emptyPayload), `"action"`) {
+ t.Fatalf("empty investigation session must omit the action reference, got %s", emptyPayload)
+ }
+}
+
+func TestOrchestratorActionBrokerIsProposeOnly(t *testing.T) {
+ // The broker seam must never grow decision or execution authority:
+ // enterprise investigation code proposes, the canonical core
+ // lifecycle decides and executes. Guard the method set so a Decide
+ // or Execute method cannot be added without failing this proof.
+ brokerType := reflect.TypeOf((*OrchestratorActionBroker)(nil)).Elem()
+ if brokerType.NumMethod() != 2 {
+ t.Fatalf("OrchestratorActionBroker must stay propose-only (Capabilities, Submit), got %d methods", brokerType.NumMethod())
+ }
+ for _, name := range []string{"Capabilities", "Submit"} {
+ if _, ok := brokerType.MethodByName(name); !ok {
+ t.Fatalf("OrchestratorActionBroker missing method %s", name)
+ }
+ }
+ for _, forbidden := range []string{"Decide", "Execute", "Approve", "ExecuteCommand"} {
+ if _, ok := brokerType.MethodByName(forbidden); ok {
+ t.Fatalf("OrchestratorActionBroker must not expose %s", forbidden)
+ }
+ }
+}
+
+func TestOrchestratorDepsExposesTypedActionBroker(t *testing.T) {
+ depsType := reflect.TypeOf(OrchestratorDeps{})
+ field, ok := depsType.FieldByName("ActionBroker")
+ if !ok {
+ t.Fatal("OrchestratorDeps must expose the typed ActionBroker seam")
+ }
+ if field.Type != reflect.TypeOf((*OrchestratorActionBroker)(nil)).Elem() {
+ t.Fatalf("ActionBroker field type = %v, want OrchestratorActionBroker", field.Type)
+ }
+}
diff --git a/pkg/aicontracts/investigation.go b/pkg/aicontracts/investigation.go
index a369374fcf..10bb19385a 100644
--- a/pkg/aicontracts/investigation.go
+++ b/pkg/aicontracts/investigation.go
@@ -140,21 +140,26 @@ type FindingOperationalMemory struct {
// InvestigationSession represents an AI investigation of a finding.
type InvestigationSession struct {
- ID string `json:"id"`
- FindingID string `json:"finding_id"`
- SessionID string `json:"session_id"` // Chat session ID
- Status InvestigationStatus `json:"status"`
- StartedAt time.Time `json:"started_at"`
- CompletedAt *time.Time `json:"completed_at,omitempty"`
- TurnCount int `json:"turn_count"`
- Outcome InvestigationOutcome `json:"outcome,omitempty"`
- ProposedFix *Fix `json:"proposed_fix,omitempty"`
- ApprovalID string `json:"approval_id,omitempty"`
- ToolsAvailable []string `json:"tools_available"`
- ToolsUsed []string `json:"tools_used"`
- EvidenceIDs []string `json:"evidence_ids"`
- Summary string `json:"summary,omitempty"`
- Error string `json:"error,omitempty"`
+ ID string `json:"id"`
+ FindingID string `json:"finding_id"`
+ SessionID string `json:"session_id"` // Chat session ID
+ Status InvestigationStatus `json:"status"`
+ StartedAt time.Time `json:"started_at"`
+ CompletedAt *time.Time `json:"completed_at,omitempty"`
+ TurnCount int `json:"turn_count"`
+ Outcome InvestigationOutcome `json:"outcome,omitempty"`
+ // ProposedFix and ApprovalID are migration-only: persisted legacy
+ // command-shaped fixes stay readable as non-executable narrative, but
+ // new investigations never populate them. Typed remediation lives in
+ // Action, which references the canonical action lifecycle record.
+ ProposedFix *Fix `json:"proposed_fix,omitempty"`
+ ApprovalID string `json:"approval_id,omitempty"`
+ Action *ActionReference `json:"action,omitempty"`
+ ToolsAvailable []string `json:"tools_available"`
+ ToolsUsed []string `json:"tools_used"`
+ EvidenceIDs []string `json:"evidence_ids"`
+ Summary string `json:"summary,omitempty"`
+ Error string `json:"error,omitempty"`
}
func EmptyInvestigationSession() InvestigationSession {
@@ -215,8 +220,11 @@ type InvestigationRecord struct {
ToolsUsed []string `json:"tools_used"`
StartedAt time.Time `json:"started_at"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
- ApprovalID string `json:"approval_id,omitempty"`
- Error string `json:"error,omitempty"`
+ // ApprovalID and ProposedFix are migration-only legacy fields; new
+ // records reference the canonical action lifecycle through Action.
+ ApprovalID string `json:"approval_id,omitempty"`
+ Action *ActionReference `json:"action,omitempty"`
+ Error string `json:"error,omitempty"`
}
// InvestigationRecordSubject identifies the infrastructure object under
diff --git a/pkg/aicontracts/orchestrator_deps.go b/pkg/aicontracts/orchestrator_deps.go
index a7ae297a93..32eb3bee61 100644
--- a/pkg/aicontracts/orchestrator_deps.go
+++ b/pkg/aicontracts/orchestrator_deps.go
@@ -240,15 +240,23 @@ type OrchestratorAIFindingsStore interface {
// OrchestratorDeps contains all dependencies for constructing an investigation orchestrator.
type OrchestratorDeps struct {
- ChatService OrchestratorChatService
+ ChatService OrchestratorChatService
+ // CmdExecutor and ApprovalStore are the legacy command-execution side
+ // doors, retained only until the typed ActionBroker migration lands.
+ // New orchestrator code must propose through ActionBroker and never
+ // dispatch command text or create command-shaped approvals.
CmdExecutor OrchestratorCommandExecutor
Store InvestigationStore
FindingsStore OrchestratorFindingsStore
ApprovalStore OrchestratorApprovalStore // may be nil
- Config InvestigationConfig
- InfraContext OrchestratorInfraContextProvider // may be nil
- Autonomy OrchestratorAutonomyProvider
- FixVerifier OrchestratorFixVerifier
- License OrchestratorLicenseChecker
- Metrics OrchestratorMetricsCallback
+ // ActionBroker is the typed, plan-only proposal seam into the core
+ // action lifecycle. Tenant-bound and actor-stamped by the core
+ // adapter; may be nil until wiring lands.
+ ActionBroker OrchestratorActionBroker
+ Config InvestigationConfig
+ InfraContext OrchestratorInfraContextProvider // may be nil
+ Autonomy OrchestratorAutonomyProvider
+ FixVerifier OrchestratorFixVerifier
+ License OrchestratorLicenseChecker
+ Metrics OrchestratorMetricsCallback
}