mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-03 18:43:38 +01:00
I added Schema v26 content-free Infrastructure Map topology read telemetry for external live GET /api/agent/topology requests (total read days, CLI days, MCP days, anonymized days, and an explicit availability flag) alongside hardened opt-out zero-write boundaries, credential-binding checks, and read-only SQLite/config guards. Key changes: - Added a dedicated root-scoped daily tally store (infrastructure_map_topology_tally.json) with strict schema validation, fail-closed degraded sidecar accounting, and strict zero-write guarantees when telemetry is disabled by settings or PULSE_TELEMETRY=false. - Added X-Pulse-Agent-Surface attribution for pulse-cli and MCP clients while filtering out first-party browser traffic, mock-mode snapshots, and unverified monitor states. - Updated Settings payload preview, localization copy, shipped PRIVACY.md disclosure, integration specs, and schema parity tooling for Schema v26. - Hardened host/agent token hash binding, self-uninstall live authority and durable hash-scoped tombstones, Patrol investigation replay-floor provenance, bounded non-blocking regular-file config reads, and cold read-only legacy SQLite history queries.
656 lines
24 KiB
Go
656 lines
24 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/ai"
|
|
"github.com/rcourtman/pulse-go-rewrite/internal/telemetry"
|
|
unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
|
|
"github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// pulseIntelligencePatrolBlockedCause returns the fixed machine cause code
|
|
// for a Patrol that is enabled but blocked from running (for example
|
|
// provider_not_configured), or an empty string when Patrol is disabled,
|
|
// healthy, mid-run, or unavailable. Only the enum cause code leaves the
|
|
// process: no blocked-reason text, provider endpoint, model name, or
|
|
// configuration.
|
|
func (r *Router) pulseIntelligencePatrolBlockedCause() string {
|
|
if r == nil || r.aiSettingsHandler == nil {
|
|
return ""
|
|
}
|
|
patrol := r.aiSettingsHandler.getPatrolService(context.Background())
|
|
if patrol == nil {
|
|
return ""
|
|
}
|
|
status := retireQuickstartPatrolStatus(patrol.GetStatus())
|
|
return pulseIntelligencePatrolBlockedCauseForTelemetry(status)
|
|
}
|
|
|
|
// pulseIntelligencePatrolBlockedCauseForTelemetry reduces a patrol status to
|
|
// the content-free cause code exported by usage telemetry. Anything but a
|
|
// currently blocked Patrol exports nothing, and a blocked reason that carries
|
|
// no typed cause exports nothing rather than free text.
|
|
func pulseIntelligencePatrolBlockedCauseForTelemetry(status ai.PatrolStatus) string {
|
|
if status.RuntimeState != ai.PatrolRuntimeStateBlocked {
|
|
return ""
|
|
}
|
|
cause := strings.TrimSpace(string(status.BlockedCause))
|
|
if cause == string(ai.PatrolFailureCauseNone) {
|
|
return ""
|
|
}
|
|
if len(cause) > 64 {
|
|
cause = cause[:64]
|
|
}
|
|
return cause
|
|
}
|
|
|
|
// pulseIntelligencePatrolAutonomyLevel returns the effective Patrol autonomy
|
|
// level for the default tenant after licence and Autopilot acknowledgement
|
|
// gating, bounded to the four released modes. An install without an AI
|
|
// service reports monitor, which is what the runtime enforces in that state.
|
|
func (r *Router) pulseIntelligencePatrolAutonomyLevel() string {
|
|
if r == nil || r.aiSettingsHandler == nil {
|
|
return telemetry.NormalizePatrolAutonomyLevelForTelemetry("")
|
|
}
|
|
svc := r.aiSettingsHandler.GetAIService(context.Background())
|
|
if svc == nil {
|
|
return telemetry.NormalizePatrolAutonomyLevelForTelemetry("")
|
|
}
|
|
return telemetry.NormalizePatrolAutonomyLevelForTelemetry(svc.GetEffectivePatrolAutonomyLevel())
|
|
}
|
|
|
|
// ApplyUpdateTelemetrySnapshot adds router-owned, content-free update funnel
|
|
// counters to the outbound usage telemetry snapshot.
|
|
func (r *Router) ApplyUpdateTelemetrySnapshot(s *telemetry.Snapshot, now time.Time) {
|
|
if r == nil || s == nil {
|
|
return
|
|
}
|
|
telemetry.ApplyUpdateTelemetrySnapshot(s, r.updateHistory, now)
|
|
if r.updateManager != nil {
|
|
telemetry.ApplyUpdateCheckTelemetrySnapshot(s, r.updateManager.LastUpdateCheck())
|
|
}
|
|
}
|
|
|
|
// GetPulseIntelligenceActionTelemetry returns count-only action-governance
|
|
// telemetry for the outbound Pulse Intelligence usage loop. It deliberately drops
|
|
// command text, approval actors/reasons, action outputs, and resource IDs.
|
|
func (r *Router) GetPulseIntelligenceActionTelemetry(since time.Time) telemetry.PulseIntelligenceActionSnapshot {
|
|
var snapshot telemetry.PulseIntelligenceActionSnapshot
|
|
if r == nil {
|
|
return snapshot
|
|
}
|
|
snapshot.PatrolBlockedCause = r.pulseIntelligencePatrolBlockedCause()
|
|
snapshot.PatrolAutonomyLevel = r.pulseIntelligencePatrolAutonomyLevel()
|
|
if r.resourceHandlers == nil {
|
|
return snapshot
|
|
}
|
|
|
|
orgIDs, orgErr := r.pulseIntelligenceTelemetryOrgIDs()
|
|
if orgErr != nil {
|
|
return telemetry.PulseIntelligenceActionSnapshot{
|
|
PatrolBlockedCause: snapshot.PatrolBlockedCause,
|
|
PatrolAutonomyLevel: snapshot.PatrolAutonomyLevel,
|
|
}
|
|
}
|
|
|
|
incomplete := false
|
|
var lastFailureAt time.Time
|
|
now := time.Now().UTC()
|
|
for _, orgID := range orgIDs {
|
|
func(orgID string) {
|
|
store, closeStore, err := r.resourceHandlers.StoreReadOnly(orgID)
|
|
if err != nil {
|
|
incomplete = true
|
|
log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to resolve action audit store for telemetry summary")
|
|
return
|
|
}
|
|
if store == nil {
|
|
return
|
|
}
|
|
defer closeStore()
|
|
approvedAttemptIDs, approvedSuccessIDs, err := pulseIntelligenceApprovedActionOutcomeIDs(store, orgID, since)
|
|
if err != nil {
|
|
incomplete = true
|
|
return
|
|
}
|
|
rejectedDecisionIDs, err := pulseIntelligenceRejectedActionDecisionIDs(store, orgID, since)
|
|
if err != nil {
|
|
incomplete = true
|
|
return
|
|
}
|
|
approvedDecisionIDs, err := pulseIntelligenceApprovedActionDecisionIDs(store, orgID, since)
|
|
if err != nil {
|
|
incomplete = true
|
|
return
|
|
}
|
|
records, err := store.GetActionAudits("", since, 0)
|
|
if err != nil {
|
|
incomplete = true
|
|
log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to query action audit telemetry summary")
|
|
return
|
|
}
|
|
recordsByID := make(map[string]unifiedresources.ActionAuditRecord, len(records))
|
|
for _, record := range records {
|
|
if actionID := strings.TrimSpace(record.ID); actionID != "" {
|
|
recordsByID[actionID] = record
|
|
}
|
|
snapshot.ActionPlans30d++
|
|
patrolOrigin := isPatrolActionOrigin(record.Origin)
|
|
if patrolOrigin {
|
|
snapshot.PatrolActionPlans30d++
|
|
}
|
|
if pulseIntelligenceActionRequiresApproval(record) {
|
|
snapshot.ApprovalRequests30d++
|
|
if patrolOrigin {
|
|
snapshot.PatrolApprovalRequests30d++
|
|
}
|
|
}
|
|
if pulseIntelligenceActionWasRejected(record) {
|
|
if actionID := strings.TrimSpace(record.ID); actionID != "" {
|
|
rejectedDecisionIDs[actionID] = struct{}{}
|
|
}
|
|
}
|
|
if pulseIntelligenceActionWasApprovedSince(record, since) {
|
|
if actionID := strings.TrimSpace(record.ID); actionID != "" {
|
|
approvedDecisionIDs[actionID] = struct{}{}
|
|
}
|
|
}
|
|
if pulseIntelligenceApprovedActionAttempt(record) {
|
|
if actionID := strings.TrimSpace(record.ID); actionID != "" {
|
|
approvedAttemptIDs[actionID] = struct{}{}
|
|
}
|
|
}
|
|
if pulseIntelligenceApprovedActionSuccess(record) {
|
|
if actionID := strings.TrimSpace(record.ID); actionID != "" {
|
|
approvedSuccessIDs[actionID] = struct{}{}
|
|
}
|
|
}
|
|
}
|
|
patrolRejected, err := pulseIntelligencePatrolOriginActionCount(store, rejectedDecisionIDs, recordsByID)
|
|
if err != nil {
|
|
incomplete = true
|
|
return
|
|
}
|
|
patrolApproved, err := pulseIntelligencePatrolOriginActionCount(store, approvedDecisionIDs, recordsByID)
|
|
if err != nil {
|
|
incomplete = true
|
|
return
|
|
}
|
|
patrolAttempts, err := pulseIntelligencePatrolOriginActionCount(store, approvedAttemptIDs, recordsByID)
|
|
if err != nil {
|
|
incomplete = true
|
|
return
|
|
}
|
|
patrolSuccesses, err := pulseIntelligencePatrolOriginActionCount(store, approvedSuccessIDs, recordsByID)
|
|
if err != nil {
|
|
incomplete = true
|
|
return
|
|
}
|
|
snapshot.RejectedActionDecisions30d += len(rejectedDecisionIDs)
|
|
snapshot.ApprovedActionDecisions30d += len(approvedDecisionIDs)
|
|
snapshot.ApprovedActionAttempts30d += len(approvedAttemptIDs)
|
|
snapshot.ApprovedActionSuccesses30d += len(approvedSuccessIDs)
|
|
snapshot.PatrolRejectedActionDecisions30d += patrolRejected
|
|
snapshot.PatrolApprovedActionDecisions30d += patrolApproved
|
|
snapshot.PatrolApprovedActionAttempts30d += patrolAttempts
|
|
snapshot.PatrolApprovedActionSuccesses30d += patrolSuccesses
|
|
if err := accumulatePulseIntelligenceApprovedActionOutcomes(&snapshot, &lastFailureAt, store, orgID, approvedAttemptIDs, approvedSuccessIDs, recordsByID, now); err != nil {
|
|
incomplete = true
|
|
return
|
|
}
|
|
}(orgID)
|
|
}
|
|
if incomplete {
|
|
return telemetry.PulseIntelligenceActionSnapshot{
|
|
PatrolBlockedCause: snapshot.PatrolBlockedCause,
|
|
PatrolAutonomyLevel: snapshot.PatrolAutonomyLevel,
|
|
}
|
|
}
|
|
|
|
return snapshot
|
|
}
|
|
|
|
func pulseIntelligencePatrolOriginActionCount(store unifiedresources.ReadOnlyResourceStore, actionIDs map[string]struct{}, recordsByID map[string]unifiedresources.ActionAuditRecord) (int, error) {
|
|
count := 0
|
|
for actionID := range actionIDs {
|
|
record, ok := recordsByID[actionID]
|
|
if !ok && store != nil {
|
|
fetched, found, err := store.GetActionAudit(actionID)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if found {
|
|
record = fetched
|
|
ok = true
|
|
}
|
|
}
|
|
if ok && isPatrolActionOrigin(record.Origin) {
|
|
count++
|
|
}
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
// pulseIntelligenceStuckExecutingThreshold separates an in-flight dispatch
|
|
// from an abandoned one. The longest legitimate typed dispatch transport wait
|
|
// is 30 minutes, so an executing record untouched for longer is stuck.
|
|
const pulseIntelligenceStuckExecutingThreshold = time.Hour
|
|
|
|
// pulseIntelligenceAllowedFailureReasonCodes is the closed allowlist of
|
|
// content-free machine reason codes permitted in outbound telemetry. Unknown
|
|
// or identifying strings (such as hostnames or IPv4 addresses) map to a fixed
|
|
// fallback so outbound pings can never leak user-identifying text.
|
|
var pulseIntelligenceAllowedFailureReasonCodes = map[string]struct{}{
|
|
"plan_drift": {},
|
|
"action_plan_drift": {},
|
|
"action_plan_expired": {},
|
|
"action_replan_required": {},
|
|
"resource_remediation_locked": {},
|
|
"policy_authorization_expired": {},
|
|
"policy_authorization_invalid": {},
|
|
"policy_authorization_revoked": {},
|
|
"action_emergency_stop": {},
|
|
"action_dry_run_only": {},
|
|
"action_execution_unavailable": {},
|
|
"agent_capability_unavailable": {},
|
|
"target_state_changed": {},
|
|
"target_precondition_failed": {},
|
|
"package_inventory_changed": {},
|
|
"cleanup_inventory_changed": {},
|
|
"image_unchanged": {},
|
|
"target_inspection_unavailable": {},
|
|
"package_manager_busy": {},
|
|
"package_index_refresh_failed": {},
|
|
"package_preflight_failed": {},
|
|
"package_manager_unhealthy": {},
|
|
"package_manager_health_unknown": {},
|
|
"cleanup_preflight_failed": {},
|
|
"image_pull_failed": {},
|
|
"container_stop_failed": {},
|
|
"container_rename_failed": {},
|
|
"action_contract_invalid": {},
|
|
actionRefusalUncoded: {},
|
|
"pre_dispatch_refused": {},
|
|
"pre_dispatch_other": {},
|
|
"execution_failed": {},
|
|
"verification_unconfirmed": {},
|
|
"verification_timeout": {},
|
|
"stuck_executing": {},
|
|
"operator_force_failed": {},
|
|
"proxmox_command_failed": {},
|
|
"possible_partial_effect": {},
|
|
"agent_readback_unavailable": {},
|
|
"agent_readback_inconclusive": {},
|
|
"stale_agent_readback": {},
|
|
"independent_observation_required": {},
|
|
"independent_observation_unavailable": {},
|
|
"compose_rollout_observation_pending": {},
|
|
"postcondition_contradicted": {},
|
|
"postcondition_unregistered": {},
|
|
"observed_field_missing": {},
|
|
"comparison_field_missing": {},
|
|
"action_start_missing": {},
|
|
"observed_timestamp_invalid": {},
|
|
"before_field_missing": {},
|
|
"observed_number_invalid": {},
|
|
"before_value_insufficient": {},
|
|
"comparator_unsupported": {},
|
|
"before_state_mismatch": {},
|
|
"unsupported_handler": {},
|
|
"agent_preflight_unavailable": {},
|
|
"executor_readiness_unavailable": {},
|
|
"command_agent_disconnected": {},
|
|
"legacy_execution_failed": {},
|
|
"legacy_missing_result": {},
|
|
"legacy_result_invalid": {},
|
|
"legacy_unknown_effect": {},
|
|
"legacy_verification_inconclusive": {},
|
|
"result_v2_invalid": {},
|
|
"execution_outcome_inconclusive": {},
|
|
"redaction_contract_violation": {},
|
|
"tenant_emergency_stop": {},
|
|
"tenant_policy_unavailable": {},
|
|
"resource_policy_missing": {},
|
|
"resource_policy_unavailable": {},
|
|
"resource_window_closed": {},
|
|
"resource_never_auto_remediate": {},
|
|
"resource_capability_not_allowed": {},
|
|
"capability_dry_run_only": {},
|
|
"unknown": {},
|
|
}
|
|
|
|
// accumulatePulseIntelligenceApprovedActionOutcomes attributes every approved
|
|
// attempt to exactly one success, failure, stuck, in-flight, or unclassified
|
|
// bucket. It also records fixed refusal categories and the machine reason code
|
|
// of the most recent failure across all organizations.
|
|
func accumulatePulseIntelligenceApprovedActionOutcomes(snapshot *telemetry.PulseIntelligenceActionSnapshot, lastFailureAt *time.Time, store unifiedresources.ReadOnlyResourceStore, orgID string, attemptIDs, successIDs map[string]struct{}, recordsByID map[string]unifiedresources.ActionAuditRecord, now time.Time) error {
|
|
for actionID := range attemptIDs {
|
|
_, isSuccess := successIDs[actionID]
|
|
record, ok := recordsByID[actionID]
|
|
if !ok {
|
|
fetched, found, err := store.GetActionAudit(actionID)
|
|
if err != nil {
|
|
log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to resolve action audit for failure-cause telemetry summary")
|
|
return err
|
|
}
|
|
if !found {
|
|
// A success outcome is already accounted by its lifecycle event;
|
|
// only unresolved non-success attempts belong in unclassified.
|
|
if !isSuccess {
|
|
snapshot.ApprovedActionUnclassified30d++
|
|
}
|
|
continue
|
|
}
|
|
record = fetched
|
|
}
|
|
if isSuccess {
|
|
if pulseIntelligenceVerifiedFindingResolution(record) {
|
|
snapshot.VerifiedFindingResolutions30d++
|
|
}
|
|
continue
|
|
}
|
|
cause, reason, refusalCategory := pulseIntelligenceApprovedActionFailureCause(record, now)
|
|
switch cause {
|
|
case "pre_dispatch":
|
|
snapshot.ApprovedActionFailuresPreDispatch30d++
|
|
switch refusalCategory {
|
|
case "plan_stale":
|
|
snapshot.ApprovedActionRefusalsPlanStale30d++
|
|
case "policy":
|
|
snapshot.ApprovedActionRefusalsPolicy30d++
|
|
case "capability":
|
|
snapshot.ApprovedActionRefusalsCapability30d++
|
|
case "target_changed":
|
|
snapshot.ApprovedActionRefusalsTargetChanged30d++
|
|
case "prerequisite":
|
|
snapshot.ApprovedActionRefusalsPrerequisite30d++
|
|
case "contract":
|
|
snapshot.ApprovedActionRefusalsContract30d++
|
|
case "uncoded":
|
|
snapshot.ApprovedActionRefusalsUncoded30d++
|
|
default:
|
|
snapshot.ApprovedActionRefusalsOther30d++
|
|
}
|
|
case "execution":
|
|
snapshot.ApprovedActionFailuresExecution30d++
|
|
case "unverified":
|
|
snapshot.ApprovedActionFailuresUnverified30d++
|
|
case "stuck_executing":
|
|
snapshot.ApprovedActionStuckExecuting30d++
|
|
case "in_flight":
|
|
snapshot.ApprovedActionInFlight30d++
|
|
continue
|
|
default:
|
|
snapshot.ApprovedActionUnclassified30d++
|
|
continue
|
|
}
|
|
if record.UpdatedAt.After(*lastFailureAt) || (record.UpdatedAt.Equal(*lastFailureAt) && snapshot.ApprovedActionLastFailureReason30d != "" && reason < snapshot.ApprovedActionLastFailureReason30d) {
|
|
*lastFailureAt = record.UpdatedAt
|
|
snapshot.ApprovedActionLastFailureReason30d = reason
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// pulseIntelligenceApprovedActionFailureCause classifies an approved attempt
|
|
// that is not a verified success into a coarse cause bucket, a closed-allowlist
|
|
// machine reason code, and (for pre-dispatch refusals) a fixed refusal bucket.
|
|
func pulseIntelligenceApprovedActionFailureCause(record unifiedresources.ActionAuditRecord, now time.Time) (string, string, string) {
|
|
switch record.State {
|
|
case unifiedresources.ActionStateExecuting:
|
|
if record.UpdatedAt.IsZero() || now.Sub(record.UpdatedAt) >= pulseIntelligenceStuckExecutingThreshold {
|
|
return "stuck_executing", "stuck_executing", ""
|
|
}
|
|
return "in_flight", "", ""
|
|
case unifiedresources.ActionStateFailed:
|
|
truth := unifiedresources.CanonicalActionResultV2(record)
|
|
if truth.Execution.Status == unifiedresources.ActionExecutionNotRun {
|
|
raw := strings.TrimSpace(truth.Execution.ReasonCode)
|
|
if raw == "" {
|
|
return "pre_dispatch", "pre_dispatch_refused", "uncoded"
|
|
}
|
|
cat := pulseIntelligenceApprovedActionRefusalCategory(raw)
|
|
fallback := "pre_dispatch_other"
|
|
if cat == "uncoded" {
|
|
fallback = "pre_dispatch_refused"
|
|
}
|
|
return "pre_dispatch", pulseIntelligenceSanitizedReasonCode(raw, fallback), cat
|
|
}
|
|
return "execution", pulseIntelligenceSanitizedReasonCode(truth.Execution.ReasonCode, "execution_failed"), ""
|
|
case unifiedresources.ActionStateCompleted:
|
|
truth := unifiedresources.CanonicalActionResultV2(record)
|
|
return "unverified", pulseIntelligenceSanitizedReasonCode(truth.Verification.ReasonCode, "verification_unconfirmed"), ""
|
|
default:
|
|
return "", "", ""
|
|
}
|
|
}
|
|
|
|
func pulseIntelligenceApprovedActionRefusalCategory(reason string) string {
|
|
switch reason {
|
|
case "plan_drift", "action_plan_expired", "action_replan_required":
|
|
return "plan_stale"
|
|
case "resource_remediation_locked", "policy_authorization_expired",
|
|
"policy_authorization_invalid", "policy_authorization_revoked", "action_emergency_stop":
|
|
return "policy"
|
|
case "action_dry_run_only", "action_execution_unavailable", "agent_capability_unavailable":
|
|
return "capability"
|
|
case "target_state_changed", "target_precondition_failed", "package_inventory_changed", "cleanup_inventory_changed",
|
|
"image_unchanged":
|
|
return "target_changed"
|
|
case "target_inspection_unavailable", "package_manager_busy", "package_index_refresh_failed",
|
|
"package_preflight_failed", "package_manager_unhealthy", "cleanup_preflight_failed",
|
|
"image_pull_failed", "container_stop_failed", "container_rename_failed":
|
|
return "prerequisite"
|
|
case "action_contract_invalid":
|
|
return "contract"
|
|
case actionRefusalUncoded, "pre_dispatch_refused":
|
|
// The refusal carried no machine reason code, so there is nothing to
|
|
// categorize. This is what an agent older than the typed refusal
|
|
// contract reports, and it must stay separable from a code this server
|
|
// simply does not recognise: the first says the split is waiting on
|
|
// agent rollout, the second says the split is wrong.
|
|
return "uncoded"
|
|
default:
|
|
return "other"
|
|
}
|
|
}
|
|
|
|
func pulseIntelligenceVerifiedFindingResolution(record unifiedresources.ActionAuditRecord) bool {
|
|
return isPatrolActionOrigin(record.Origin) &&
|
|
pulseIntelligenceApprovedActionSuccess(record) &&
|
|
patrolOutcomeForActionAudit(record) == aicontracts.OutcomeFixVerified
|
|
}
|
|
|
|
func pulseIntelligenceSanitizedReasonCode(code, fallback string) string {
|
|
code = strings.TrimSpace(code)
|
|
if _, ok := pulseIntelligenceAllowedFailureReasonCodes[code]; ok {
|
|
return code
|
|
}
|
|
return fallback
|
|
}
|
|
|
|
func (r *Router) pulseIntelligenceTelemetryOrgIDs() ([]string, error) {
|
|
if r == nil || r.multiTenant == nil {
|
|
return []string{"default"}, nil
|
|
}
|
|
rawIDs, err := r.multiTenant.ListOrganizationIDs()
|
|
if err != nil {
|
|
log.Warn().Err(err).Msg("Unable to list organizations for telemetry summary")
|
|
return nil, err
|
|
}
|
|
seen := map[string]struct{}{}
|
|
orgIDs := make([]string, 0, len(rawIDs))
|
|
for _, rawID := range rawIDs {
|
|
orgID := strings.TrimSpace(rawID)
|
|
if orgID == "" {
|
|
orgID = "default"
|
|
}
|
|
if _, ok := seen[orgID]; ok {
|
|
continue
|
|
}
|
|
seen[orgID] = struct{}{}
|
|
orgIDs = append(orgIDs, orgID)
|
|
}
|
|
if len(orgIDs) == 0 {
|
|
return []string{"default"}, nil
|
|
}
|
|
return orgIDs, nil
|
|
}
|
|
|
|
func pulseIntelligenceActionRequiresApproval(record unifiedresources.ActionAuditRecord) bool {
|
|
if record.Plan.RequiresApproval {
|
|
return true
|
|
}
|
|
return len(record.Approvals) > 0 || record.State == unifiedresources.ActionStatePending ||
|
|
record.State == unifiedresources.ActionStateApproved || record.State == unifiedresources.ActionStateRejected
|
|
}
|
|
|
|
func pulseIntelligenceApprovedActionOutcomeIDs(store unifiedresources.ReadOnlyResourceStore, orgID string, since time.Time) (map[string]struct{}, map[string]struct{}, error) {
|
|
attemptIDs := map[string]struct{}{}
|
|
successIDs := map[string]struct{}{}
|
|
if store == nil {
|
|
return attemptIDs, successIDs, nil
|
|
}
|
|
events, err := store.GetActionLifecycleEvents("", since, 0)
|
|
if err != nil {
|
|
log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to query action lifecycle telemetry summary")
|
|
return nil, nil, err
|
|
}
|
|
for _, event := range events {
|
|
if !pulseIntelligenceActionLifecycleIndicatesAttempt(event) {
|
|
continue
|
|
}
|
|
actionID := strings.TrimSpace(event.ActionID)
|
|
if actionID == "" {
|
|
continue
|
|
}
|
|
record, ok, err := store.GetActionAudit(actionID)
|
|
if err != nil {
|
|
log.Warn().Err(err).Str("org_id", orgID).Msg("Unable to resolve action audit for lifecycle telemetry summary")
|
|
return nil, nil, err
|
|
}
|
|
if ok && pulseIntelligenceActionWasApproved(record) {
|
|
attemptIDs[actionID] = struct{}{}
|
|
if event.State == unifiedresources.ActionStateCompleted && pulseIntelligenceApprovedActionSuccess(record) {
|
|
successIDs[actionID] = struct{}{}
|
|
}
|
|
}
|
|
}
|
|
return attemptIDs, successIDs, nil
|
|
}
|
|
|
|
func pulseIntelligenceRejectedActionDecisionIDs(store unifiedresources.ReadOnlyResourceStore, orgID string, since time.Time) (map[string]struct{}, error) {
|
|
return pulseIntelligenceActionDecisionIDs(store, orgID, since, unifiedresources.ActionStateRejected, "rejected", pulseIntelligenceActionWasRejected)
|
|
}
|
|
|
|
func pulseIntelligenceApprovedActionDecisionIDs(store unifiedresources.ReadOnlyResourceStore, orgID string, since time.Time) (map[string]struct{}, error) {
|
|
return pulseIntelligenceActionDecisionIDs(store, orgID, since, unifiedresources.ActionStateApproved, "approved", pulseIntelligenceActionWasApproved)
|
|
}
|
|
|
|
func pulseIntelligenceActionDecisionIDs(store unifiedresources.ReadOnlyResourceStore, orgID string, since time.Time, state unifiedresources.ActionState, decisionLabel string, auditMatches func(unifiedresources.ActionAuditRecord) bool) (map[string]struct{}, error) {
|
|
decisionIDs := map[string]struct{}{}
|
|
if store == nil {
|
|
return decisionIDs, nil
|
|
}
|
|
events, err := store.GetActionLifecycleEvents("", since, 0)
|
|
if err != nil {
|
|
log.Warn().Err(err).Str("org_id", orgID).Msgf("Unable to query %s action lifecycle telemetry summary", decisionLabel)
|
|
return nil, err
|
|
}
|
|
for _, event := range events {
|
|
if event.State != state {
|
|
continue
|
|
}
|
|
actionID := strings.TrimSpace(event.ActionID)
|
|
if actionID == "" {
|
|
continue
|
|
}
|
|
record, ok, err := store.GetActionAudit(actionID)
|
|
if err != nil {
|
|
log.Warn().Err(err).Str("org_id", orgID).Msgf("Unable to resolve %s action audit for telemetry summary", decisionLabel)
|
|
return nil, err
|
|
}
|
|
if ok && auditMatches(record) {
|
|
decisionIDs[actionID] = struct{}{}
|
|
}
|
|
}
|
|
return decisionIDs, nil
|
|
}
|
|
|
|
func pulseIntelligenceApprovedActionAttempt(record unifiedresources.ActionAuditRecord) bool {
|
|
if !pulseIntelligenceActionWasApproved(record) {
|
|
return false
|
|
}
|
|
switch record.State {
|
|
case unifiedresources.ActionStateExecuting, unifiedresources.ActionStateCompleted, unifiedresources.ActionStateFailed:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func pulseIntelligenceApprovedActionSuccess(record unifiedresources.ActionAuditRecord) bool {
|
|
if record.State != unifiedresources.ActionStateCompleted {
|
|
return false
|
|
}
|
|
return pulseIntelligenceActionVerifiedOutcome(record)
|
|
}
|
|
|
|
func pulseIntelligenceActionVerifiedOutcome(record unifiedresources.ActionAuditRecord) bool {
|
|
if !pulseIntelligenceActionWasApproved(record) {
|
|
return false
|
|
}
|
|
truth := unifiedresources.CanonicalActionResultV2(record)
|
|
return truth.Execution.Status == unifiedresources.ActionExecutionSucceeded && truth.Verification.Status == unifiedresources.ActionVerificationConfirmed
|
|
}
|
|
|
|
func pulseIntelligenceActionLifecycleIndicatesAttempt(event unifiedresources.ActionLifecycleEvent) bool {
|
|
switch event.State {
|
|
case unifiedresources.ActionStateExecuting, unifiedresources.ActionStateCompleted, unifiedresources.ActionStateFailed:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func pulseIntelligenceActionWasApproved(record unifiedresources.ActionAuditRecord) bool {
|
|
if record.State == unifiedresources.ActionStateApproved {
|
|
return true
|
|
}
|
|
for _, approval := range record.Approvals {
|
|
if approval.Outcome == unifiedresources.OutcomeApproved {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func pulseIntelligenceActionWasApprovedSince(record unifiedresources.ActionAuditRecord, since time.Time) bool {
|
|
for _, approval := range record.Approvals {
|
|
if approval.Outcome != unifiedresources.OutcomeApproved {
|
|
continue
|
|
}
|
|
if approval.Timestamp.IsZero() || approval.Timestamp.Before(since) {
|
|
continue
|
|
}
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func pulseIntelligenceActionWasRejected(record unifiedresources.ActionAuditRecord) bool {
|
|
if record.State == unifiedresources.ActionStateRejected {
|
|
return true
|
|
}
|
|
for _, approval := range record.Approvals {
|
|
if approval.Outcome == unifiedresources.OutcomeRejected {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|