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.

Bundle pending approvals into the agent resource-context endpoint

rcourtmand8f6b1e508a5
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 3e956dce18..8d7d1396a6 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -952,13 +952,16 @@ stays curated, not auto-derived from every internal endpoint.
`/api/agent/resource-context/{id}` is the agent-paradigm substrate
endpoint: any agent (in-process Patrol/Assistant or external) reads
the full situated picture of a resource — identity, operator state,
-active findings, recent actions including refused dispatches with
-their stable token prefixes preserved — in one call. The endpoint is
-read-only under `monitoring:read`. The active-findings section
-flows through an `AgentFindingsProvider` adapter wired in
-`router.go` from the patrol service so the api package stays free
-of an `internal/ai` import; the agent runtime keeps this provider
-wired across restarts.
+active findings, pending approvals scoped to the resource, recent
+actions including refused dispatches with their stable token
+prefixes preserved — in one call. The endpoint is read-only under
+`monitoring:read`. The active-findings section flows through an
+`AgentFindingsProvider` adapter wired in `router.go` from the
+patrol service so the api package stays free of an `internal/ai`
+import; the parallel `AgentApprovalsProvider` adapter resolves the
+canonical approval store at request time and filters by
+canonical resource id and org. The agent runtime keeps both
+providers wired across restarts.
The findings runtime now consumes operator-set per-resource state
through a provider adapter wired in `internal/api/router.go` at
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index f1c31bf0f6..f8527788e6 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1437,20 +1437,32 @@ context endpoint. One read returns the full situated picture of a
resource — identity, operator-set state (with server-computed
`maintenanceWindowActive` flag), active findings as the
`AgentResourceFindingSnapshot` projection (lightweight subset of
-the seven-question schema fields agents need), and recent action
-audits including refused dispatches with their stable token
-prefixes (`resource_remediation_locked:`, `plan_drift:`) preserved
-verbatim. The shape is intentionally narrower than the full
-internal types so agents see a stable agent-paradigm contract,
-decoupled from internal type evolution. Active findings come
-through the `AgentFindingsProvider` adapter wired at startup so the
-api package stays free of an `internal/ai` import; the patrol
-service holds the canonical findings store and projects each
-`Finding` into the snapshot shape. Active findings and recent
-actions are always arrays (never null) so agents can iterate
-without nil-checking; absent operator state surfaces as a missing
-`operatorState` field (omitempty), distinguishing "no operator
-overrides" from "all-zero overrides recorded."
+the seven-question schema fields agents need), pending approvals
+scoped to this resource as the `AgentResourceApprovalSummary`
+projection (id, command, riskLevel, requestedBy, requestedAt,
+expiresAt — same vocabulary as `approval.pending` SSE events so
+"what's pending right now" and "what just became pending" agree
+on shape), and recent action audits including refused dispatches
+with their stable token prefixes (`resource_remediation_locked:`,
+`plan_drift:`) preserved verbatim. The shape is intentionally
+narrower than the full internal types so agents see a stable
+agent-paradigm contract, decoupled from internal type evolution.
+Active findings come through the `AgentFindingsProvider` adapter
+wired at startup so the api package stays free of an
+`internal/ai` import; the patrol service holds the canonical
+findings store and projects each `Finding` into the snapshot
+shape. Pending approvals come through the parallel
+`AgentApprovalsProvider` adapter — the router wires a closure
+that resolves `approval.GetStore()` at request time (so
+multi-tenant store rebuilds stay honored), filters via
+`approval.BelongsToOrg` for tenant scope, and matches
+`req.CanonicalResourceID()` against the requested resource so
+cross-resource approvals don't leak into the bundle. Active
+findings, pending approvals, and recent actions are always arrays
+(never null) so agents can iterate without nil-checking; absent
+operator state surfaces as a missing `operatorState` field
+(omitempty), distinguishing "no operator overrides" from
+"all-zero overrides recorded."
The TS client `frontend-modern/src/api/resourceOperatorState.ts`
mirrors the canonical Go shape from
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 05ee069b26..9b4a809351 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -531,11 +531,14 @@ record is persisted. Goroutine dispatch keeps the approval and
dispatch hot paths independent of consumer drain rate; per-event
cost is one channel send per subscriber.
-`/api/agent/resource-context/{id}` does at most three reads per
+`/api/agent/resource-context/{id}` does at most four reads per
request: one operator-state SQLite point lookup (already covered by
the `resource_operator_state` index), one in-memory findings lookup
-via the patrol findings store's `byResource` index, and one bounded
-action-audit query (limit 10, since-1-week filter). No fan-out, no
+via the patrol findings store's `byResource` index, one in-memory
+filter against `approval.GetStore().GetPendingApprovals()` (bounded
+by the store's `MaxApprovals=100` ceiling — a fixed-cost scan
+independent of resource cardinality), and one bounded action-audit
+query (limit 10, since-1-week filter). No fan-out, no
cross-resource scan — the bundle is leveraged for substrate use
without becoming a per-request hot path that scales with global
finding volume.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index be7edcb5c9..c0d09e819f 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -973,9 +973,13 @@ flows are not affected.
The agent-consumable bundled context endpoint
`/api/agent/resource-context/{id}` reads the same durable
`resource_operator_state` table and `action_audits` table through the
-canonical `unified.ResourceStore` accessors. No new persistence is
-introduced; the endpoint is a read-only bundle over existing storage,
-so storage/recovery flows that rehydrate the unified-resources store
+canonical `unified.ResourceStore` accessors, and additionally
+filters the in-memory approval store (durably persisted to the
+`approvals.json` file the approval store already manages, hydrated
+on startup). No new persistence is introduced for the
+pending-approvals section either; the bundle is still a read-only
+bundle over existing storage, so storage/recovery flows that
+rehydrate the unified-resources store and the approval store
already cover everything the agent endpoint surfaces.
The findings runtime reads operator-set state through the same
diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.go
index fa00749e36..094ec79cf7 100644
--- a/internal/api/agent_capabilities.go
+++ b/internal/api/agent_capabilities.go
@@ -93,7 +93,7 @@ var agentCapabilitiesManifest = AgentCapabilitiesManifest{
Capabilities: []AgentCapability{
{
Name: "get_resource_context",
- Description: "Return the situated picture of a resource — identity, operator-set state with maintenance-window-active flag, active findings, recent actions including refused dispatches.",
+ Description: "Return the situated picture of a resource — identity, operator-set state with maintenance-window-active flag, active findings, pending approvals scoped to this resource, recent actions including refused dispatches.",
Category: "context",
Method: http.MethodGet,
Path: "/api/agent/resource-context/{resourceId}",
diff --git a/internal/api/agent_resource_context.go b/internal/api/agent_resource_context.go
index ccc0b6238e..62313dba5c 100644
--- a/internal/api/agent_resource_context.go
+++ b/internal/api/agent_resource_context.go
@@ -47,6 +47,22 @@ type AgentResourceActionSummary struct {
UpdatedAt time.Time `json:"updatedAt"`
}
+// AgentResourceApprovalSummary is the agent-consumable projection of
+// a pending approval request scoped to a specific resource. Carries
+// just enough for an agent that holds approval authority to decide
+// whether to act, fetch full context via /api/approvals/{id}, or
+// escalate. Mirrors the shape of approval.pending SSE events so
+// "what's pending right now" (this bundle) and "what just became
+// pending" (the SSE stream) speak the same vocabulary.
+type AgentResourceApprovalSummary struct {
+ ID string `json:"id"`
+ Command string `json:"command"`
+ RiskLevel string `json:"riskLevel"`
+ RequestedBy string `json:"requestedBy,omitempty"`
+ RequestedAt time.Time `json:"requestedAt"`
+ ExpiresAt time.Time `json:"expiresAt"`
+}
+
// AgentResourceOperatorState mirrors the canonical
// `unified.ResourceOperatorState` but with the same JSON shape the
// `/api/resources/{id}/operator-state` endpoint already returns. Kept
@@ -81,14 +97,15 @@ type AgentResourceOperatorState struct {
// detail (full finding records, full audit history) remains available
// via the existing per-finding / per-audit endpoints.
type AgentResourceContext struct {
- CanonicalID string `json:"canonicalId"`
- ResourceType string `json:"resourceType"`
- ResourceName string `json:"resourceName"`
- Technology string `json:"technology,omitempty"`
- OperatorState *AgentResourceOperatorState `json:"operatorState,omitempty"`
- ActiveFindings []AgentResourceFindingSnapshot `json:"activeFindings"`
- RecentActions []AgentResourceActionSummary `json:"recentActions"`
- GeneratedAt time.Time `json:"generatedAt"`
+ CanonicalID string `json:"canonicalId"`
+ ResourceType string `json:"resourceType"`
+ ResourceName string `json:"resourceName"`
+ Technology string `json:"technology,omitempty"`
+ OperatorState *AgentResourceOperatorState `json:"operatorState,omitempty"`
+ ActiveFindings []AgentResourceFindingSnapshot `json:"activeFindings"`
+ PendingApprovals []AgentResourceApprovalSummary `json:"pendingApprovals"`
+ RecentActions []AgentResourceActionSummary `json:"recentActions"`
+ GeneratedAt time.Time `json:"generatedAt"`
}
// AgentFindingsProvider returns the active findings for a resource as
@@ -111,6 +128,27 @@ func (f agentFindingsProviderFunc) ActiveFindingsForResource(resourceID string)
return f(resourceID)
}
+// AgentApprovalsProvider returns the still-pending approvals scoped
+// to a single resource as agent-stable summaries. The implementation
+// lives outside this package (the approval store is owned by the
+// AIHandler); this interface keeps the bundle handler decoupled
+// from the global approval store and lets tests pass a fake.
+type AgentApprovalsProvider interface {
+ PendingApprovalsForResource(resourceID, orgID string) []AgentResourceApprovalSummary
+}
+
+// agentApprovalsProviderFunc is a function adapter so wire-up code
+// can pass a closure without declaring a struct.
+type agentApprovalsProviderFunc func(resourceID, orgID string) []AgentResourceApprovalSummary
+
+// PendingApprovalsForResource implements AgentApprovalsProvider.
+func (f agentApprovalsProviderFunc) PendingApprovalsForResource(resourceID, orgID string) []AgentResourceApprovalSummary {
+ if f == nil {
+ return nil
+ }
+ return f(resourceID, orgID)
+}
+
// AgentContextHandler owns the agent-paradigm bundled context
// endpoint. Kept as a separate type from `ResourceHandlers` so the
// agent surface evolves independently of the resource CRUD surface
@@ -119,8 +157,9 @@ func (f agentFindingsProviderFunc) ActiveFindingsForResource(resourceID string)
// access (those are the canonical accessors); the
// agent-findings adapter is held here.
type AgentContextHandler struct {
- resources *ResourceHandlers
- findingsProvider AgentFindingsProvider
+ resources *ResourceHandlers
+ findingsProvider AgentFindingsProvider
+ approvalsProvider AgentApprovalsProvider
}
// NewAgentContextHandler creates a new agent context handler. The
@@ -136,6 +175,14 @@ func (h *AgentContextHandler) SetFindingsProvider(p AgentFindingsProvider) {
h.findingsProvider = p
}
+// SetApprovalsProvider wires the pending-approvals adapter. Pass nil
+// to disable the pending-approvals section of the bundle (callers
+// will always see `pendingApprovals: []` rather than a missing field
+// so agents can iterate without nil-checking).
+func (h *AgentContextHandler) SetApprovalsProvider(p AgentApprovalsProvider) {
+ h.approvalsProvider = p
+}
+
// HandleResourceContext serves
// `GET /api/agent/resource-context/{id}` — the agent-consumable
// situated picture of a resource. Bundle is computed at request time
@@ -177,13 +224,14 @@ func (h *AgentContextHandler) HandleResourceContext(w http.ResponseWriter, r *ht
}
bundle := AgentResourceContext{
- CanonicalID: resourceID,
- ResourceType: string(resource.Type),
- ResourceName: resource.Name,
- Technology: resource.Technology,
- ActiveFindings: []AgentResourceFindingSnapshot{},
- RecentActions: []AgentResourceActionSummary{},
- GeneratedAt: time.Now().UTC(),
+ CanonicalID: resourceID,
+ ResourceType: string(resource.Type),
+ ResourceName: resource.Name,
+ Technology: resource.Technology,
+ ActiveFindings: []AgentResourceFindingSnapshot{},
+ PendingApprovals: []AgentResourceApprovalSummary{},
+ RecentActions: []AgentResourceActionSummary{},
+ GeneratedAt: time.Now().UTC(),
}
// Operator-set state — single point lookup.
@@ -204,6 +252,18 @@ func (h *AgentContextHandler) HandleResourceContext(w http.ResponseWriter, r *ht
}
}
+ // Pending approvals — in-memory filter against the approval
+ // store, scoped to this org. Same pattern as findings: the
+ // provider adapter keeps the api package free of approval-store
+ // internals at the bundle layer; the wire-up step in router.go
+ // does the global lookup and resource-id filter.
+ if h.approvalsProvider != nil {
+ bundle.PendingApprovals = h.approvalsProvider.PendingApprovalsForResource(resourceID, orgID)
+ if bundle.PendingApprovals == nil {
+ bundle.PendingApprovals = []AgentResourceApprovalSummary{}
+ }
+ }
+
// Recent action audits — limit to 10 by default; agents that need
// deeper history can call the existing per-resource action audit
// endpoint. Filter window of "since one week ago" mirrors the
diff --git a/internal/api/agent_resource_context_test.go b/internal/api/agent_resource_context_test.go
index 2d5820c69f..98d0f62e53 100644
--- a/internal/api/agent_resource_context_test.go
+++ b/internal/api/agent_resource_context_test.go
@@ -28,6 +28,21 @@ func (s staticFindingsProvider) ActiveFindingsForResource(resourceID string) []A
return s.byResource[resourceID]
}
+// staticApprovalsProvider is a tiny test double for
+// AgentApprovalsProvider — keyed by (resource id, org id) so each
+// test can stage the pending approvals it expects to see in the
+// bundle without setting up a global approval store.
+type staticApprovalsProvider struct {
+ byResource map[string][]AgentResourceApprovalSummary
+}
+
+func (s staticApprovalsProvider) PendingApprovalsForResource(resourceID, _ string) []AgentResourceApprovalSummary {
+ if s.byResource == nil {
+ return nil
+ }
+ return s.byResource[resourceID]
+}
+
// agentContextFixtureHandlers wires a ResourceHandlers around a
// pre-built unified-resource seed (using the same
// `resourceUnifiedSeedProvider` pattern from resources_test.go) plus
@@ -284,6 +299,81 @@ func TestHandleAgentResourceContext_RecentActionsCarryRefusalTokens(t *testing.T
}
}
+func TestHandleAgentResourceContext_PendingApprovalsAreScopedToResource(t *testing.T) {
+ // pendingApprovals must list every still-pending approval
+ // targeting the bundle's resource. The provider is the seam that
+ // scopes by (resource id, org id) — the bundle handler trusts
+ // the provider's filtering. Pin the contract: if the provider
+ // returns N entries, the bundle returns N entries with the same
+ // agent-stable shape (id, command, riskLevel, requestedBy,
+ // requestedAt, expiresAt) and an empty array (never null) when
+ // the provider returns nothing.
+ h, _ := agentContextFixtureHandlers(t, "vm:101")
+ now := time.Now().UTC()
+ expires := now.Add(5 * time.Minute)
+ h.SetApprovalsProvider(staticApprovalsProvider{
+ byResource: map[string][]AgentResourceApprovalSummary{
+ "vm:101": {
+ {
+ ID: "appr-1",
+ Command: "systemctl restart nginx",
+ RiskLevel: "medium",
+ RequestedBy: "ai:patrol",
+ RequestedAt: now,
+ ExpiresAt: expires,
+ },
+ },
+ },
+ })
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/agent/resource-context/vm:101", nil)
+ h.HandleResourceContext(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status: got %d, body=%s", rec.Code, rec.Body.String())
+ }
+ var bundle AgentResourceContext
+ if err := json.NewDecoder(rec.Body).Decode(&bundle); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(bundle.PendingApprovals) != 1 {
+ t.Fatalf("PendingApprovals len = %d; want 1; body=%s", len(bundle.PendingApprovals), rec.Body.String())
+ }
+ got := bundle.PendingApprovals[0]
+ if got.ID != "appr-1" {
+ t.Errorf("ID: got %q, want %q", got.ID, "appr-1")
+ }
+ if got.Command != "systemctl restart nginx" {
+ t.Errorf("Command did not round-trip: got %q", got.Command)
+ }
+ if got.RiskLevel != "medium" {
+ t.Errorf("RiskLevel did not round-trip: got %q", got.RiskLevel)
+ }
+ if !got.ExpiresAt.Equal(expires) {
+ t.Errorf("ExpiresAt did not round-trip: got %v, want %v", got.ExpiresAt, expires)
+ }
+}
+
+func TestHandleAgentResourceContext_PendingApprovalsEmptyArrayWhenNone(t *testing.T) {
+ // Absent or empty must surface as an empty array, not as a
+ // missing field — agents iterate without nil-checking. This
+ // mirrors the contract for ActiveFindings and RecentActions.
+ h, _ := agentContextFixtureHandlers(t, "vm:404")
+ // No approvals provider wired — same observable shape as a
+ // provider that returns nil for this resource.
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/agent/resource-context/vm:404", nil)
+ h.HandleResourceContext(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status: got %d", rec.Code)
+ }
+ body := rec.Body.String()
+ if !strings.Contains(body, `"pendingApprovals":[]`) {
+ t.Errorf("expected pendingApprovals to surface as empty array; body=%s", body)
+ }
+}
+
func TestExtractAgentResourceContextID(t *testing.T) {
cases := []struct {
path string
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 91e3dc493a..9097ed6c9d 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -13509,14 +13509,14 @@ func TestContract_AgentResourceContextEndpointSurfacesStableShape(t *testing.T)
}
src := string(source)
// Always-array initialization for the iteration-safe contract.
- if !strings.Contains(src, "ActiveFindings: []AgentResourceFindingSnapshot{}") {
+ if !strings.Contains(src, "ActiveFindings: []AgentResourceFindingSnapshot{},") {
t.Error("activeFindings must default to an empty slice, not nil — agents iterate without nil-checks")
}
- if !strings.Contains(src, "RecentActions: []AgentResourceActionSummary{}") {
+ if !strings.Contains(src, "RecentActions: []AgentResourceActionSummary{},") {
t.Error("recentActions must default to an empty slice, not nil")
}
// Field-presence branching contract for operatorState.
- if !strings.Contains(src, "OperatorState *AgentResourceOperatorState `json:\"operatorState,omitempty\"`") {
+ if !strings.Contains(src, "OperatorState *AgentResourceOperatorState `json:\"operatorState,omitempty\"`") {
t.Error("operatorState must be omitempty so absent entries surface as missing field")
}
// Server-computed maintenance-active flag — server pre-computes so
@@ -13529,6 +13529,61 @@ func TestContract_AgentResourceContextEndpointSurfacesStableShape(t *testing.T)
if !strings.Contains(src, "summary.ErrorMessage = audit.Result.ErrorMessage") {
t.Error("audit ErrorMessage must round-trip verbatim so refusal tokens (resource_remediation_locked:, plan_drift:) reach agents")
}
+ // pendingApprovals must initialize as an empty slice so agents
+ // iterate without nil-checking — same iteration-safe contract
+ // as activeFindings and recentActions.
+ if !strings.Contains(src, "PendingApprovals: []AgentResourceApprovalSummary{}") {
+ t.Error("pendingApprovals must default to an empty slice, not nil — agents iterate without nil-checks")
+ }
+ // Pending approvals must reuse the AgentResourceApprovalSummary
+ // shape so the bundle and approval.pending SSE events stay in
+ // the same vocabulary.
+ if !strings.Contains(src, "PendingApprovals []AgentResourceApprovalSummary `json:\"pendingApprovals\"`") {
+ t.Error("AgentResourceContext must carry PendingApprovals as a stable []AgentResourceApprovalSummary field")
+ }
+}
+
+// TestContract_AgentResourceContextWiresApprovalsProvider pins the
+// startup-time wire-up that lets the bundle endpoint surface pending
+// approvals scoped to a resource. Drift here means the field always
+// shows up as an empty array even when there ARE pending approvals,
+// silently breaking the substrate's "everything an agent needs in
+// one read" contract for the governance dimension.
+func TestContract_AgentResourceContextWiresApprovalsProvider(t *testing.T) {
+ source, err := os.ReadFile("router.go")
+ if err != nil {
+ t.Fatalf("read router.go: %v", err)
+ }
+ src := string(source)
+ if !strings.Contains(src, "r.agentContextHandler.SetApprovalsProvider(agentApprovalsProviderFunc(") {
+ t.Error("router.go must wire the approvals provider on the agent context handler so the bundle's pendingApprovals section is populated")
+ }
+ if !strings.Contains(src, "store := approval.GetStore()") {
+ t.Error("router.go must resolve the approval store at request time so multi-tenant store rebuilds stay honored")
+ }
+ if !strings.Contains(src, "if !approval.BelongsToOrg(req, orgID)") {
+ t.Error("router.go must scope pending approvals via BelongsToOrg so cross-tenant requests don't leak into a resource-context bundle")
+ }
+ if !strings.Contains(src, "if req.CanonicalResourceID() != resourceID") {
+ t.Error("router.go must filter pending approvals by CanonicalResourceID so the bundle only carries approvals targeting the requested resource")
+ }
+}
+
+// TestContract_GetResourceContextCapabilityListsPendingApprovals pins
+// the discovery contract: the capabilities manifest must mention
+// pendingApprovals under get_resource_context so an agent reading
+// the manifest learns the bundle now carries the governance
+// dimension. Drift here means external agents still expect the
+// pre-slice-45 shape.
+func TestContract_GetResourceContextCapabilityListsPendingApprovals(t *testing.T) {
+ source, err := os.ReadFile("agent_capabilities.go")
+ if err != nil {
+ t.Fatalf("read agent_capabilities.go: %v", err)
+ }
+ src := string(source)
+ if !strings.Contains(src, "pending approvals scoped to this resource") {
+ t.Error("get_resource_context description must mention pending approvals so agents discover the bundle's new governance section through the manifest")
+ }
}
// TestContract_FindingsResourceOperatorStateProviderIsWired pins the
diff --git a/internal/api/router.go b/internal/api/router.go
index d7b0e58b17..f6cdd57b8b 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -411,6 +411,46 @@ func (r *Router) setupRoutes() {
r.kubernetesAgentHandlers.SetRecoveryIngestor(r.recoveryHandlers)
r.resourceHandlers = NewResourceHandlers(r.config)
r.agentContextHandler = NewAgentContextHandler(r.resourceHandlers)
+ // Wire pending-approvals into the bundle. The closure resolves
+ // the approval store at request time so multi-tenant rebuilds
+ // (which install a new global store via approval.SetStore) stay
+ // honored without a re-wire — the bundle just reads whatever is
+ // currently global. Org scoping uses BelongsToOrg so cross-tenant
+ // pending requests don't leak into a resource-context read for
+ // the wrong org.
+ r.agentContextHandler.SetApprovalsProvider(agentApprovalsProviderFunc(
+ func(resourceID, orgID string) []AgentResourceApprovalSummary {
+ store := approval.GetStore()
+ if store == nil || strings.TrimSpace(resourceID) == "" {
+ return nil
+ }
+ pending := store.GetPendingApprovals()
+ if len(pending) == 0 {
+ return nil
+ }
+ out := make([]AgentResourceApprovalSummary, 0, len(pending))
+ for _, req := range pending {
+ if req == nil {
+ continue
+ }
+ if !approval.BelongsToOrg(req, orgID) {
+ continue
+ }
+ if req.CanonicalResourceID() != resourceID {
+ continue
+ }
+ out = append(out, AgentResourceApprovalSummary{
+ ID: req.ID,
+ Command: req.Command,
+ RiskLevel: string(req.RiskLevel),
+ RequestedBy: req.RequestedBy,
+ RequestedAt: req.RequestedAt,
+ ExpiresAt: req.ExpiresAt,
+ })
+ }
+ return out
+ },
+ ))
r.agentEventBroadcaster = NewAgentEventBroadcaster()
if r.resourceHandlers != nil {
if store, err := r.resourceHandlers.getStore("default"); err == nil && store != nil {