domain

package
v1.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PIITypeEmail         = "email"
	PIITypeName          = "name"
	PIITypePhone         = "phone"
	PIITypeAddress       = "address"
	PIITypeSSN           = "ssn"
	PIITypeNationalID    = "national_id"
	PIITypeIPAddress     = "ip_address"
	PIITypeDateOfBirth   = "date_of_birth"
	PIITypeDriverLicense = "driver_license"
)

PII type constants for display and filtering.

View Source
const (
	SecretTypeAPIKey             = "api_key"
	SecretTypeBearerToken        = "bearer_token"
	SecretTypeOAuthToken         = "oauth_token"
	SecretTypePassword           = "password"
	SecretTypePasswordHash       = "password_hash"
	SecretTypeDatabaseCredential = "database_credential"
	SecretTypeConnectionString   = "connection_string"
	SecretTypePrivateKey         = "private_key"
	SecretTypeCertificate        = "certificate"
	SecretTypeEncryptionKey      = "encryption_key"
	SecretTypeSigningKey         = "signing_key"
	SecretTypeWebhookSecret      = "webhook_secret"
	SecretTypeSessionToken       = "session_token"
)

Secret type constants for display and filtering.

View Source
const (
	PHITypeDiagnosisCode       = "diagnosis_code"
	PHITypeProcedureCode       = "procedure_code"
	PHITypePrescription        = "prescription"
	PHITypeLabResult           = "lab_result"
	PHITypeMedicalRecordNumber = "medical_record_number"
	PHITypePatientIdentifier   = "patient_identifier"
	PHITypeHealthInsuranceID   = "health_insurance_id"
	PHITypeBiometric           = "biometric"
	PHITypeGeneticData         = "genetic_data"
)

PHI type constants for display and filtering.

View Source
const (
	PaymentTypeCreditCard     = "credit_card"
	PaymentTypeCVV            = "cvv"
	PaymentTypePIN            = "pin"
	PaymentTypeBankAccount    = "bank_account"
	PaymentTypeRoutingNumber  = "routing_number"
	PaymentTypePaymentToken   = "payment_token"
	PaymentTypeMagneticStripe = "magnetic_stripe"
)

Payment data type constants for display and filtering.

Variables

View Source
var DatadogRegions = []DatadogRegion{
	{DatadogSiteUS1, "US1 (datadoghq.com)", "United States"},
	{DatadogSiteUS3, "US3 (us3.datadoghq.com)", "United States"},
	{DatadogSiteUS5, "US5 (us5.datadoghq.com)", "United States"},
	{DatadogSiteEU1, "EU1 (datadoghq.eu)", "Europe"},
	{DatadogSiteAP1, "AP1 (ap1.datadoghq.com)", "Asia Pacific"},
	{DatadogSiteUS1Fed, "US1-FED (ddog-gov.com)", "US Government"},
}

DatadogRegions is the list of available Datadog regions.

Functions

func EncodeBlocks

func EncodeBlocks(blocks []Block) (string, error)

EncodeBlocks serializes blocks to JSON string for storage.

func EncodeText

func EncodeText(content string) (string, error)

EncodeText is a convenience function to encode a single text block.

func EncodeToolResults

func EncodeToolResults(results []ToolResult) (string, error)

EncodeToolResults encodes tool results as blocks for storage.

func FormatInterval added in v1.18.0

func FormatInterval(seconds int) string

FormatInterval renders seconds as a human-friendly duration.

func PolicyCategoryStatusByCostDesc added in v1.18.0

func PolicyCategoryStatusByCostDesc(a, b PolicyCategoryStatus) int

PolicyCategoryStatusByCostDesc sorts by estimated cost descending (highest impact first), with nil costs last. Ties break by pending count descending.

Types

type Account

type Account struct {
	ID   AccountID `json:"id"`
	Name string    `json:"name"`
}

Account represents a billing/Datadog account within an organization.

func (Account) FilterValue

func (a Account) FilterValue() string

FilterValue returns the string used for filtering/searching.

type AccountID

type AccountID string

AccountID is a unique identifier for an account.

func NewAccountID

func NewAccountID() AccountID

NewAccountID generates a new unique AccountID.

func (AccountID) String

func (id AccountID) String() string

type AccountSummary added in v1.14.0

type AccountSummary struct {
	ReadyForUse bool

	// Health.
	Health    ServiceHealth
	Error     string
	ErrorAt   string
	Warning   string
	WarningAt string

	// Service counts.
	ServiceCount     int64
	ActiveServices   int64
	OkServices       int64
	ErrorServices    int64
	DisabledServices int64
	InactiveServices int64

	// Event counts.
	EventCount       int64
	AnalyzedCount    int64
	QuarantinedCount int64

	// Policy counts.
	PendingPolicyCount   int64
	ApprovedPolicyCount  int64
	DismissedPolicyCount int64

	// Service-level throughput (ground truth).
	TotalServiceVolumePerHour *float64
	TotalServiceCostPerHour   *float64

	// Log event throughput (discovered events). Nil when unmeasured.
	TotalCostPerHour       *float64
	TotalCostPerHourBytes  *float64
	TotalCostPerHourVolume *float64
	TotalVolumePerHour     *float64
	TotalBytesPerHour      *float64

	// Estimated savings from pending policies. Nil when unmeasured.
	EstimatedCostPerHour       *float64
	EstimatedCostPerHourBytes  *float64
	EstimatedCostPerHourVolume *float64
	EstimatedVolumePerHour     *float64
	EstimatedBytesPerHour      *float64

	// Observed impact from approved policies (before/after). Nil when unmeasured.
	ObservedCostBefore       *float64
	ObservedCostBeforeBytes  *float64
	ObservedCostBeforeVolume *float64
	ObservedCostAfter        *float64
	ObservedCostAfterBytes   *float64
	ObservedCostAfterVolume  *float64
	ObservedVolumeBefore     *float64
	ObservedVolumeAfter      *float64
	ObservedBytesBefore      *float64
	ObservedBytesAfter       *float64
}

AccountSummary mirrors datadog_account_statuses_cache aggregated across all Datadog accounts. All columns included; callers pick what they need.

func (AccountSummary) AnalysisReady added in v1.16.0

func (s AccountSummary) AnalysisReady() bool

AnalysisReady returns true when enough discovered events have been analyzed for waste and compliance numbers to be meaningful.

type AnalysisEnvelope added in v1.18.0

type AnalysisEnvelope map[string]json.RawMessage

AnalysisEnvelope wraps the category-keyed analysis JSON from log_event_policies.analysis. The column stores {"category_name": { ...analysis... }} — one key per policy.

func (AnalysisEnvelope) Parse added in v1.18.0

func (e AnalysisEnvelope) Parse(category string, target any) error

Parse extracts and unmarshals the analysis for a given category into the target type.

type Attr added in v1.18.0

type Attr struct {
	Key   string
	Value string
}

Attr is a single flattened log attribute for display.

type Block

type Block struct {
	Index      int         `json:"index"`
	Type       BlockType   `json:"type"`
	Text       *TextBlock  `json:"text,omitempty"`
	Thinking   *Thinking   `json:"thinking,omitempty"`
	ToolUse    *ToolUse    `json:"tool_use,omitempty"`
	ToolResult *ToolResult `json:"tool_result,omitempty"`
}

Block is one element in a message's content array. Exactly one of the typed fields is populated, determined by Type.

func NewTextBlock

func NewTextBlock(content string) Block

NewTextBlock creates a text block.

func ParseBlocks

func ParseBlocks(data string) ([]Block, error)

ParseBlocks parses a JSON string into content blocks.

type BlockType

type BlockType string

BlockType identifies the kind of content block.

const (
	// Persistable block types - stored in the database.
	BlockTypeText       BlockType = "text"
	BlockTypeThinking   BlockType = "thinking"
	BlockTypeToolUse    BlockType = "tool_use"
	BlockTypeToolResult BlockType = "tool_result"
)

type BotTrafficAnalysis added in v1.18.0

type BotTrafficAnalysis struct {
	UserAgentField FieldPath `json:"user_agent_field"`         // Path to user-agent attribute
	BotProportion  *float64  `json:"bot_proportion,omitempty"` // Fraction of traffic identified as bot/crawler (0.0–1.0)
	// contains filtered or unexported fields
}

BotTrafficAnalysis identifies log events with a user-agent field for bot filtering.

func (BotTrafficAnalysis) ActionDetail added in v1.18.0

func (a BotTrafficAnalysis) ActionDetail() string

func (BotTrafficAnalysis) Category added in v1.18.0

func (a BotTrafficAnalysis) Category() PolicyCategory

func (BotTrafficAnalysis) Rationale added in v1.18.0

func (a BotTrafficAnalysis) Rationale() string

func (BotTrafficAnalysis) RelevantKeys added in v1.18.0

func (a BotTrafficAnalysis) RelevantKeys() []FieldPath

func (BotTrafficAnalysis) Subtitle added in v1.18.0

func (a BotTrafficAnalysis) Subtitle() string

type BrokenRecordsAnalysis added in v1.18.0

type BrokenRecordsAnalysis struct {
	MinIntervalSeconds int `json:"min_interval_seconds"` // Suggested minimum interval between kept events (1-30s)
	// contains filtered or unexported fields
}

BrokenRecordsAnalysis identifies near-identical events repeating endlessly.

func (BrokenRecordsAnalysis) ActionDetail added in v1.18.0

func (a BrokenRecordsAnalysis) ActionDetail() string

func (BrokenRecordsAnalysis) Category added in v1.18.0

func (BrokenRecordsAnalysis) Rationale added in v1.18.0

func (a BrokenRecordsAnalysis) Rationale() string

func (BrokenRecordsAnalysis) RelevantKeys added in v1.18.0

func (a BrokenRecordsAnalysis) RelevantKeys() []FieldPath

func (BrokenRecordsAnalysis) Subtitle added in v1.18.0

func (a BrokenRecordsAnalysis) Subtitle() string

type CategoryType added in v1.18.0

type CategoryType string

CategoryType drives which tab owns a category.

const (
	CategoryTypeCompliance CategoryType = "compliance" // Legal/security risk
	CategoryTypeWaste      CategoryType = "waste"      // Event-level cuts
	CategoryTypeQuality    CategoryType = "quality"    // Field-level improvements
)

type CommodityTrafficAnalysis added in v1.18.0

type CommodityTrafficAnalysis struct {
	MinIntervalSeconds int `json:"min_interval_seconds"` // Suggested minimum interval between kept events (1-30s)
	// contains filtered or unexported fields
}

CommodityTrafficAnalysis identifies high-volume events where aggregate patterns matter more than individual records.

func (CommodityTrafficAnalysis) ActionDetail added in v1.18.0

func (a CommodityTrafficAnalysis) ActionDetail() string

func (CommodityTrafficAnalysis) Category added in v1.18.0

func (CommodityTrafficAnalysis) Rationale added in v1.18.0

func (a CommodityTrafficAnalysis) Rationale() string

func (CommodityTrafficAnalysis) RelevantKeys added in v1.18.0

func (a CommodityTrafficAnalysis) RelevantKeys() []FieldPath

func (CommodityTrafficAnalysis) Subtitle added in v1.18.0

func (a CommodityTrafficAnalysis) Subtitle() string

type ComplianceAnalysisEnvelope added in v1.16.0

type ComplianceAnalysisEnvelope struct {
	PIILeakage         *PIILeakageAnalysis         `json:"pii_leakage,omitempty"`
	SecretsLeakage     *SecretsLeakageAnalysis     `json:"secrets_leakage,omitempty"`
	PHILeakage         *PHILeakageAnalysis         `json:"phi_leakage,omitempty"`
	PaymentDataLeakage *PaymentDataLeakageAnalysis `json:"payment_data_leakage,omitempty"`
}

ComplianceAnalysisEnvelope wraps the category-keyed analysis JSON from the database. Each field corresponds to one compliance category.

type ComplianceCategorySummary added in v1.16.0

type ComplianceCategorySummary struct {
	Category       PolicyCategory // One of the 4 compliance categories
	DisplayName    string         // Human-readable name from control plane
	Principle      string         // One-liner explaining what this category catches
	LeakingCount   int64          // Policies with observed sensitive data
	AtRiskCount    int64          // Policies without observed data (but flagged)
	FixedCount     int64          // Approved policies
	VolumePerHour  float64        // Total volume across all policies in this category
	ServiceCount   int            // Number of unique services affected
	UniqueServices []string
}

ComplianceCategorySummary provides counts and stats for a single compliance category.

func (ComplianceCategorySummary) Name added in v1.18.0

Name returns the human-readable name for the compliance category. Uses the display name from the control plane, falling back to short labels.

type CompliancePolicy added in v1.16.0

type CompliancePolicy struct {
	Category      PolicyCategory   // One of: pii_leakage, secrets_leakage, phi_leakage, payment_data_leakage
	LogEventName  string           // Log event name
	ServiceName   string           // Service name
	Fields        []SensitiveField // Parsed from analysis JSON
	VolumePerHour *float64         // Log event volume; nil when unmeasured
	AnyObserved   bool             // True if any field has observed sensitive data
}

CompliancePolicy represents a single compliance finding (any category) with context from joined tables.

type ConstantVariesEvidence added in v1.18.0

type ConstantVariesEvidence struct {
	Constant     []FieldValue
	Varying      []VaryingField
	ExampleCount int
}

ConstantVariesEvidence shows which fields are identical across multiple log examples and which vary. Proves that instances are near-identical. Used by broken_records and commodity_traffic.

type ContextEntity

type ContextEntity struct {
	EntityType string `json:"entity_type"` // "service", "log_event", "policy", etc.
	EntityID   string `json:"entity_id"`
}

ContextEntity is an entity attached to a conversation for the AI to reference. The client sends entity IDs; the server loads full entity data for the system prompt.

type ContextSource

type ContextSource string

ContextSource indicates who added an entity to context.

const (
	ContextSourceUser      ContextSource = "user"
	ContextSourceAssistant ContextSource = "assistant"
)

type Conversation

type Conversation struct {
	ID          ConversationID `json:"id"`
	WorkspaceID WorkspaceID    `json:"workspace_id"`
	Title       string         `json:"title"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
}

Conversation represents a chat conversation.

type ConversationID

type ConversationID string

ConversationID is a typed identifier for conversations.

func NewConversationID

func NewConversationID() ConversationID

NewConversationID generates a new unique ConversationID.

func (ConversationID) String

func (id ConversationID) String() string

String returns the string representation of the ConversationID.

type DatadogAccountID

type DatadogAccountID string

DatadogAccountID is a unique identifier for a Datadog account integration.

func (DatadogAccountID) String

func (id DatadogAccountID) String() string

type DatadogRegion

type DatadogRegion struct {
	Site DatadogSite
	Name string
	Desc string
}

DatadogRegion contains display information for a Datadog site.

type DatadogSite

type DatadogSite string

DatadogSite represents a Datadog datacenter region.

const (
	DatadogSiteUS1    DatadogSite = "US1"
	DatadogSiteUS3    DatadogSite = "US3"
	DatadogSiteUS5    DatadogSite = "US5"
	DatadogSiteEU1    DatadogSite = "EU1"
	DatadogSiteAP1    DatadogSite = "AP1"
	DatadogSiteUS1Fed DatadogSite = "US1_FED"
)

func (DatadogSite) String

func (s DatadogSite) String() string

type DeadWeightAnalysis added in v1.18.0

type DeadWeightAnalysis struct {
	// contains filtered or unexported fields
}

DeadWeightAnalysis identifies events with no discernible value across any dimension.

func (DeadWeightAnalysis) ActionDetail added in v1.18.0

func (a DeadWeightAnalysis) ActionDetail() string

func (DeadWeightAnalysis) Category added in v1.18.0

func (a DeadWeightAnalysis) Category() PolicyCategory

func (DeadWeightAnalysis) Rationale added in v1.18.0

func (a DeadWeightAnalysis) Rationale() string

func (DeadWeightAnalysis) RelevantKeys added in v1.18.0

func (a DeadWeightAnalysis) RelevantKeys() []FieldPath

func (DeadWeightAnalysis) Subtitle added in v1.18.0

func (a DeadWeightAnalysis) Subtitle() string

type DebugArtifactsAnalysis added in v1.18.0

type DebugArtifactsAnalysis struct {
	// contains filtered or unexported fields
}

DebugArtifactsAnalysis is the analysis for developer debugging code that shipped to production.

func (DebugArtifactsAnalysis) ActionDetail added in v1.18.0

func (a DebugArtifactsAnalysis) ActionDetail() string

func (DebugArtifactsAnalysis) Category added in v1.18.0

func (DebugArtifactsAnalysis) Rationale added in v1.18.0

func (a DebugArtifactsAnalysis) Rationale() string

func (DebugArtifactsAnalysis) RelevantKeys added in v1.18.0

func (a DebugArtifactsAnalysis) RelevantKeys() []FieldPath

func (DebugArtifactsAnalysis) Subtitle added in v1.18.0

func (a DebugArtifactsAnalysis) Subtitle() string

type DuplicateFieldsAnalysis added in v1.18.0

type DuplicateFieldsAnalysis struct {
	Pairs []DuplicatePair `json:"pairs"` // Duplicate field pairs to deduplicate
	// contains filtered or unexported fields
}

DuplicateFieldsAnalysis identifies fields with the same data stored redundantly under different names within a single log event.

func (DuplicateFieldsAnalysis) ActionDetail added in v1.18.0

func (a DuplicateFieldsAnalysis) ActionDetail() string

func (DuplicateFieldsAnalysis) Category added in v1.18.0

func (DuplicateFieldsAnalysis) Rationale added in v1.18.0

func (a DuplicateFieldsAnalysis) Rationale() string

func (DuplicateFieldsAnalysis) RelevantKeys added in v1.18.0

func (a DuplicateFieldsAnalysis) RelevantKeys() []FieldPath

func (DuplicateFieldsAnalysis) Subtitle added in v1.18.0

func (a DuplicateFieldsAnalysis) Subtitle() string

type DuplicatePair added in v1.18.0

type DuplicatePair struct {
	Remove []FieldPath `json:"remove"` // Duplicate field paths to remove
	Keep   FieldPath   `json:"keep"`   // Canonical field path to keep
}

DuplicatePair identifies a set of duplicate fields — one to keep, others to remove.

type Evidence added in v1.18.0

type Evidence interface {
	// contains filtered or unexported methods
}

Evidence is a marker interface for polymorphic evidence types. Each evidence shape represents a different way of presenting log example data to prove a policy's findings. Consumers type-switch to render the appropriate shape.

func BuildEvidence added in v1.18.0

func BuildEvidence(p *Policy) Evidence

BuildEvidence derives the evidence structure for a policy from its analysis type and log examples. Returns nil if no evidence can be built (no examples, unsupported category, etc.).

type FieldListEvidence added in v1.18.0

type FieldListEvidence struct {
	Fields        []FieldSize
	TotalBytes    float64 // Sum of targeted fields' bytes
	EventAvgBytes float64 // Whole-event average bytes (baseline)
	BytesFraction float64 // TotalBytes / EventAvgBytes
}

FieldListEvidence lists the fields a quality policy targets, each with its measured byte size. Used by instrumentation_bloat, oversized_fields, and duplicate_fields when per-field byte data is available. Fields are sorted by BytesPerEvent descending (biggest impact first).

type FieldPath added in v1.18.0

type FieldPath []string

FieldPath is the canonical representation of an attribute path in a log event. It wraps the segment slice that the control plane stores (e.g. ["attributes", "http", "status"]) and provides a stable dot-key for display and matching (e.g. "http.status").

Three representations exist in the wild:

  1. JSON array of strings — analysis JSON fields (["attributes", "http", "status"])
  2. PostgreSQL text array literal — log_event_fields.field_path ("{attributes,http,status}")
  3. Dot-key — display and matching ("http.status")

FieldPath normalizes all three into one type. Construct via:

  • JSON unmarshal (handles #1 automatically)
  • ParseFieldPathPg (handles #2)
  • NewFieldPath (wraps a raw []string)

func NewFieldPath added in v1.18.0

func NewFieldPath(segments []string) FieldPath

NewFieldPath wraps a segment slice into a FieldPath.

func ParseFieldPathPg added in v1.18.0

func ParseFieldPathPg(s string) FieldPath

ParseFieldPathPg parses a PostgreSQL text array literal into a FieldPath.

"{attributes,http,status}" → ["attributes", "http", "status"]
""                         → nil

func (FieldPath) IsEmpty added in v1.18.0

func (p FieldPath) IsEmpty() bool

IsEmpty returns true if the path has no segments.

func (FieldPath) Key added in v1.18.0

func (p FieldPath) Key() string

Key returns the dot-separated display key, stripping the leading "attributes" prefix since log examples already flatten under that namespace.

["attributes", "http", "status"] → "http.status"
["http", "status"]              → "http.status"
["body"]                        → "body"

func (FieldPath) MarshalJSON added in v1.18.0

func (p FieldPath) MarshalJSON() ([]byte, error)

MarshalJSON serializes as a JSON array of strings.

func (FieldPath) Segments added in v1.18.0

func (p FieldPath) Segments() []string

Segments returns the underlying path segments.

func (FieldPath) String added in v1.18.0

func (p FieldPath) String() string

String implements fmt.Stringer via Key().

func (*FieldPath) UnmarshalJSON added in v1.18.0

func (p *FieldPath) UnmarshalJSON(data []byte) error

UnmarshalJSON supports direct deserialization from JSON arrays (["attributes", "http", "status"]). This means analysis structs can use FieldPath directly instead of []string.

type FieldSize added in v1.18.0

type FieldSize struct {
	Key           string  // Dot-key (e.g. "http.request.body")
	BytesPerEvent float64 // Average bytes this field contributes per event
}

FieldSize is a single field targeted by a quality policy with its measured byte impact.

type FieldValue added in v1.18.0

type FieldValue struct {
	Key   string
	Value string
}

FieldValue is a single key-value pair from a flattened log attribute.

type HealthChecksAnalysis added in v1.18.0

type HealthChecksAnalysis struct {
	// contains filtered or unexported fields
}

HealthChecksAnalysis is the analysis for health check / readiness probe events.

func (HealthChecksAnalysis) ActionDetail added in v1.18.0

func (a HealthChecksAnalysis) ActionDetail() string

func (HealthChecksAnalysis) Category added in v1.18.0

func (a HealthChecksAnalysis) Category() PolicyCategory

func (HealthChecksAnalysis) Rationale added in v1.18.0

func (a HealthChecksAnalysis) Rationale() string

func (HealthChecksAnalysis) RelevantKeys added in v1.18.0

func (a HealthChecksAnalysis) RelevantKeys() []FieldPath

func (HealthChecksAnalysis) Subtitle added in v1.18.0

func (a HealthChecksAnalysis) Subtitle() string

type HighlightedExampleEvidence added in v1.18.0

type HighlightedExampleEvidence struct {
	Attrs        []FieldValue // All attributes from the example, ordered with relevant first
	RelevantKeys []FieldPath  // Keys that should be visually highlighted
}

HighlightedExampleEvidence shows a single log example with specific fields called out as relevant to the finding. Used by compliance (sensitive fields), bot_traffic (user-agent field), and as a fallback for field-targeting quality categories when byte sizes aren't available.

type InstrumentationBloatAnalysis added in v1.18.0

type InstrumentationBloatAnalysis struct {
	Fields []FieldPath `json:"fields"` // Attribute paths to remove
	// contains filtered or unexported fields
}

InstrumentationBloatAnalysis identifies SDK/collector metadata fields that no engineer added intentionally and no engineer would ever query.

func (InstrumentationBloatAnalysis) ActionDetail added in v1.18.0

func (a InstrumentationBloatAnalysis) ActionDetail() string

func (InstrumentationBloatAnalysis) Category added in v1.18.0

func (InstrumentationBloatAnalysis) Rationale added in v1.18.0

func (a InstrumentationBloatAnalysis) Rationale() string

func (InstrumentationBloatAnalysis) RelevantKeys added in v1.18.0

func (a InstrumentationBloatAnalysis) RelevantKeys() []FieldPath

func (InstrumentationBloatAnalysis) Subtitle added in v1.18.0

func (a InstrumentationBloatAnalysis) Subtitle() string

type LogEventStatus

type LogEventStatus struct {
	Name                string
	VolumePerHour       *float64
	BytesPerHour        *float64
	CostPerHourUSD      *float64
	PendingPolicyCount  int64
	ApprovedPolicyCount int64
}

LogEventStatus is a per-log-event status within a service. Used for the service detail drill-down in the statusbar drawer.

type LogExample added in v1.18.0

type LogExample struct {
	Body       string         `json:"body"`
	Severity   string         `json:"severity_text"`
	Attributes map[string]any `json:"attributes"`
}

LogExample is a parsed log record for rendering in cards and other views. Parsed from the log_events.examples JSON column.

func ParseLogExamples added in v1.18.0

func ParseLogExamples(jsonStr string) []LogExample

ParseLogExamples parses the log_events.examples JSON column and returns clean examples with infrastructure/resource/scope attributes stripped.

func (LogExample) FlatAttrs added in v1.18.0

func (e LogExample) FlatAttrs(relevantKeys []FieldPath) []Attr

FlatAttrs returns all attributes flattened and ordered by relevance. Relevant keys appear first (in the order provided), then remaining attributes sorted alphabetically. Returns all attributes — callers decide how many to display.

func (LogExample) IsEmpty added in v1.18.0

func (e LogExample) IsEmpty() bool

IsEmpty returns true if the example has no body and no attributes.

type MalformedAnalysis added in v1.18.0

type MalformedAnalysis struct {
	// contains filtered or unexported fields
}

MalformedAnalysis is the analysis for unparseable or corrupted log data.

func (MalformedAnalysis) ActionDetail added in v1.18.0

func (a MalformedAnalysis) ActionDetail() string

func (MalformedAnalysis) Category added in v1.18.0

func (a MalformedAnalysis) Category() PolicyCategory

func (MalformedAnalysis) Rationale added in v1.18.0

func (a MalformedAnalysis) Rationale() string

func (MalformedAnalysis) RelevantKeys added in v1.18.0

func (a MalformedAnalysis) RelevantKeys() []FieldPath

func (MalformedAnalysis) Subtitle added in v1.18.0

func (a MalformedAnalysis) Subtitle() string

type Message

type Message struct {
	ID             MessageID      `json:"id"`
	ConversationID ConversationID `json:"conversation_id"`
	Role           Role           `json:"role"`
	Content        []Block        `json:"content"`
	Model          string         `json:"model,omitempty"`
	StopReason     string         `json:"stop_reason,omitempty"`
	CreatedAt      time.Time      `json:"created_at"`
}

Message represents a chat message.

type MessageID

type MessageID string

MessageID is a typed identifier for messages.

func NewMessageID

func NewMessageID() MessageID

NewMessageID generates a new unique MessageID.

func (MessageID) String

func (id MessageID) String() string

String returns the string representation of the MessageID.

type Organization

type Organization struct {
	ID                   OrganizationID       `json:"id"`
	Name                 string               `json:"name"`
	WorkosOrganizationID WorkosOrganizationID `json:"workos_organization_id,omitempty"`
}

Organization represents a customer organization.

func (Organization) FilterValue

func (o Organization) FilterValue() string

FilterValue returns the string used for filtering/searching.

type OrganizationID

type OrganizationID string

OrganizationID is a unique identifier for an organization.

func NewOrganizationID

func NewOrganizationID() OrganizationID

NewOrganizationID generates a new unique OrganizationID.

func (OrganizationID) String

func (id OrganizationID) String() string

type OversizedFieldsAnalysis added in v1.18.0

type OversizedFieldsAnalysis struct {
	Fields []FieldPath `json:"fields"` // Attribute paths to truncate
	// contains filtered or unexported fields
}

OversizedFieldsAnalysis identifies fields where the value is disproportionately large relative to its diagnostic utility.

func (OversizedFieldsAnalysis) ActionDetail added in v1.18.0

func (a OversizedFieldsAnalysis) ActionDetail() string

func (OversizedFieldsAnalysis) Category added in v1.18.0

func (OversizedFieldsAnalysis) Rationale added in v1.18.0

func (a OversizedFieldsAnalysis) Rationale() string

func (OversizedFieldsAnalysis) RelevantKeys added in v1.18.0

func (a OversizedFieldsAnalysis) RelevantKeys() []FieldPath

func (OversizedFieldsAnalysis) Subtitle added in v1.18.0

func (a OversizedFieldsAnalysis) Subtitle() string

type PHILeakageAnalysis added in v1.16.0

type PHILeakageAnalysis struct {
	Fields []SensitiveField `json:"fields"`
	// contains filtered or unexported fields
}

PHILeakageAnalysis is the category-specific analysis for PHI leakage policies.

func (PHILeakageAnalysis) ActionDetail added in v1.18.0

func (a PHILeakageAnalysis) ActionDetail() string

func (PHILeakageAnalysis) Category added in v1.18.0

func (a PHILeakageAnalysis) Category() PolicyCategory

func (PHILeakageAnalysis) Rationale added in v1.16.0

func (a PHILeakageAnalysis) Rationale() string

func (PHILeakageAnalysis) RelevantKeys added in v1.18.0

func (a PHILeakageAnalysis) RelevantKeys() []FieldPath

func (PHILeakageAnalysis) Subtitle added in v1.18.0

func (a PHILeakageAnalysis) Subtitle() string

type PIILeakageAnalysis added in v1.15.0

type PIILeakageAnalysis struct {
	Fields []SensitiveField `json:"fields"`
	// contains filtered or unexported fields
}

PIILeakageAnalysis is the category-specific analysis for PII leakage policies.

func (PIILeakageAnalysis) ActionDetail added in v1.18.0

func (a PIILeakageAnalysis) ActionDetail() string

func (PIILeakageAnalysis) Category added in v1.18.0

func (a PIILeakageAnalysis) Category() PolicyCategory

func (PIILeakageAnalysis) Rationale added in v1.15.0

func (a PIILeakageAnalysis) Rationale() string

func (PIILeakageAnalysis) RelevantKeys added in v1.18.0

func (a PIILeakageAnalysis) RelevantKeys() []FieldPath

func (PIILeakageAnalysis) Subtitle added in v1.18.0

func (a PIILeakageAnalysis) Subtitle() string

type PaymentDataLeakageAnalysis added in v1.16.0

type PaymentDataLeakageAnalysis struct {
	Fields []SensitiveField `json:"fields"`
	// contains filtered or unexported fields
}

PaymentDataLeakageAnalysis is the category-specific analysis for payment data leakage policies.

func (PaymentDataLeakageAnalysis) ActionDetail added in v1.18.0

func (a PaymentDataLeakageAnalysis) ActionDetail() string

func (PaymentDataLeakageAnalysis) Category added in v1.18.0

func (PaymentDataLeakageAnalysis) Rationale added in v1.16.0

func (a PaymentDataLeakageAnalysis) Rationale() string

func (PaymentDataLeakageAnalysis) RelevantKeys added in v1.18.0

func (a PaymentDataLeakageAnalysis) RelevantKeys() []FieldPath

func (PaymentDataLeakageAnalysis) Subtitle added in v1.18.0

func (a PaymentDataLeakageAnalysis) Subtitle() string

type Policy added in v1.18.0

type Policy struct {
	ID                  PolicyID
	ServiceName         string
	LogEventName        string
	Category            PolicyCategory
	CategoryType        CategoryType
	Action              PolicyAction
	Status              PolicyStatus
	Severity            PolicySeverity
	CategoryDisplayName string

	// Metrics (nil = not measured)
	VolumePerHour          *float64
	BytesPerHour           *float64
	EstimatedCostPerHour   *float64
	EstimatedVolumePerHour *float64
	EstimatedBytesPerHour  *float64
	SurvivalRate           *float64

	// Event-level baselines from log_events.
	EventBaselineAvgBytes      *float64 // Trailing 7-day avg bytes per event
	EventBaselineVolumePerHour *float64 // Trailing 7-day volume per hour

	// Per-field byte sizes from log_event_fields, keyed by dot-path (e.g. "http.status").
	// Populated for quality categories via PolicyCard. nil for other categories.
	FieldSizes map[string]float64

	// Parsed from JSON
	Analysis     PolicyAnalysis // nil if analysis JSON is empty or unparseable
	Examples     []LogExample   // parsed, infrastructure stripped
	RelevantKeys []FieldPath    // attribute paths relevant to this category
}

Policy is a fully parsed policy ready for any consumer. Built from PolicyCard (the raw DB type) via ParsePolicy. Analysis is typed per category, examples are parsed, and relevant keys are extracted.

func ParsePolicy added in v1.18.0

func ParsePolicy(card *PolicyCard) *Policy

ParsePolicy converts a raw PolicyCard (from the DB) into a fully parsed Policy.

func (*Policy) CostPerYear added in v1.18.0

func (p *Policy) CostPerYear() string

CostPerYear returns the formatted estimated annual cost savings, or "" if not applicable. Only meaningful for waste and quality categories.

func (*Policy) Headline added in v1.18.0

func (p *Policy) Headline() string

Headline returns the one-line action description for this policy. Examples: "Sample — keep ~1% of volume", "Drop this event", "Trim — 3 bloat fields".

func (*Policy) Impact added in v1.18.0

func (p *Policy) Impact() *PolicyImpact

Impact returns the before/after metrics for this policy, or nil if no estimates exist.

func (*Policy) Mechanism added in v1.18.0

func (p *Policy) Mechanism() string

Mechanism explains what approving this policy does. Examples: "Approving keeps 1 in every ~8,837 events.", "Approving creates a pipeline rule that drops this event before ingestion."

func (*Policy) Pitch added in v1.18.0

func (p *Policy) Pitch() string

Pitch returns the first sentence of the analysis rationale.

type PolicyAction added in v1.18.0

type PolicyAction string

PolicyAction describes what a policy does to log events.

const (
	PolicyActionDrop   PolicyAction = "drop"   // Drops entire events
	PolicyActionSample PolicyAction = "sample" // Keeps a fraction of events
	PolicyActionFilter PolicyAction = "filter" // Drops a subset by field value
	PolicyActionTrim   PolicyAction = "trim"   // Removes or truncates fields
	PolicyActionNone   PolicyAction = "none"   // Informational only
)

type PolicyAnalysis added in v1.18.0

type PolicyAnalysis interface {
	Category() PolicyCategory
	Rationale() string
	Subtitle() string
	ActionDetail() string
	RelevantKeys() []FieldPath
}

PolicyAnalysis is the parsed, typed analysis for a policy. Each category implements this interface on its analysis struct.

type PolicyCard added in v1.18.0

type PolicyCard struct {
	PolicyID               string
	ServiceName            string
	LogEventName           string
	Category               string
	CategoryType           string
	Action                 string
	Status                 string
	Severity               string
	CategoryDisplayName    string
	VolumePerHour          *float64
	BytesPerHour           *float64
	EstimatedCostPerHour   *float64
	EstimatedVolumePerHour *float64
	EstimatedBytesPerHour  *float64
	SurvivalRate           *float64
	Analysis               string // Raw category-keyed JSON from log_event_policies.analysis
	Examples               string // Raw JSON array from log_events.examples

	// Event-level baselines from log_events.
	EventBaselineAvgBytes      *float64 // Trailing 7-day avg bytes per event
	EventBaselineVolumePerHour *float64 // Trailing 7-day volume per hour

	// Per-field byte sizes from log_event_fields, keyed by dot-path (e.g. "http.status").
	// Populated by the sqlite layer for quality categories. nil for other categories.
	FieldSizes map[string]float64
}

PolicyCard contains all data needed to render a rich policy card. Fetched from log_event_policy_statuses_cache with enrichment JOINs.

type PolicyCategory added in v1.18.0

type PolicyCategory string

PolicyCategory is a policy category slug from the control plane.

const (
	CategoryPIILeakage         PolicyCategory = "pii_leakage"
	CategorySecretsLeakage     PolicyCategory = "secrets_leakage"
	CategoryPHILeakage         PolicyCategory = "phi_leakage"
	CategoryPaymentDataLeakage PolicyCategory = "payment_data_leakage"
)

Compliance category constants matching control plane schema.

const (
	CategoryDuplicateFields      PolicyCategory = "duplicate_fields"
	CategoryInstrumentationBloat PolicyCategory = "instrumentation_bloat"
	CategoryOversizedFields      PolicyCategory = "oversized_fields"
	CategoryWrongLevel           PolicyCategory = "wrong_level"
)

Quality category slug constants matching control plane schema.

const (
	CategoryHealthChecks     PolicyCategory = "health_checks"
	CategoryBotTraffic       PolicyCategory = "bot_traffic"
	CategoryDebugArtifacts   PolicyCategory = "debug_artifacts"
	CategoryMalformed        PolicyCategory = "malformed"
	CategoryBrokenRecords    PolicyCategory = "broken_records"
	CategoryCommodityTraffic PolicyCategory = "commodity_traffic"
	CategoryRedundantEvents  PolicyCategory = "redundant_events"
	CategoryDeadWeight       PolicyCategory = "dead_weight"
)

Waste category slug constants matching control plane schema.

func (PolicyCategory) String added in v1.18.0

func (c PolicyCategory) String() string

type PolicyCategoryStatus

type PolicyCategoryStatus struct {
	Category    PolicyCategory
	DisplayName string // Human-readable name from control plane (e.g. "Bot Traffic")
	Principle   string // One-liner explaining what this category catches

	PendingCount   int64
	ApprovedCount  int64
	DismissedCount int64

	// Estimated impact from pending policies.
	EstimatedVolumePerHour *float64
	EstimatedBytesPerHour  *float64
	EstimatedCostPerHour   *float64

	// Volume discovery coverage.
	EventsWithVolumes int64 // Log events in this category that have volume data
	TotalEvents       int64 // Total log events in this category

	// What policies in this category do.
	Action PolicyAction
}

PolicyCategoryStatus is the per-category policy breakdown. Float pointers are nil when no data exists (e.g. no pending/approved policies contribute).

func (PolicyCategoryStatus) ActionLabel added in v1.18.0

func (c PolicyCategoryStatus) ActionLabel() string

ActionLabel returns a human-readable description of what this category's policies do.

func (PolicyCategoryStatus) Name added in v1.18.0

func (c PolicyCategoryStatus) Name() string

Name returns the human-readable name for the category. Uses the display name from the control plane, falling back to title-cased slug.

func (PolicyCategoryStatus) ReducesVolume added in v1.16.0

func (c PolicyCategoryStatus) ReducesVolume() bool

ReducesVolume reports whether this category's policies drop entire events.

type PolicyID added in v1.18.0

type PolicyID string

PolicyID is a unique identifier for a policy.

func (PolicyID) String added in v1.18.0

func (id PolicyID) String() string

type PolicyImpact added in v1.18.0

type PolicyImpact struct {
	VolumeFrom  string // "883.7k evt/hr"
	VolumeTo    string // "~8.8k evt/hr"
	VolumePct   string // "▼ 99%"
	StorageFrom string // "3.5 GB/hr"
	StorageTo   string // "~35 MB/hr"
	StoragePct  string // "▼ 99%"
	Savings     string // "~$16.3k/yr"
}

PolicyImpact holds the before/after metrics for a policy's estimated impact.

type PolicySeverity added in v1.18.0

type PolicySeverity string

PolicySeverity is the compliance severity level of a policy. Computed by the control plane and stored on the policy row.

const (
	SeverityLow      PolicySeverity = "low"
	SeverityMedium   PolicySeverity = "medium"
	SeverityHigh     PolicySeverity = "high"
	SeverityCritical PolicySeverity = "critical"
)

type PolicyStatus added in v1.18.0

type PolicyStatus string

PolicyStatus is the lifecycle status for a policy.

const (
	PolicyStatusPending   PolicyStatus = "PENDING"
	PolicyStatusApproved  PolicyStatus = "APPROVED"
	PolicyStatusDismissed PolicyStatus = "DISMISSED"
)

func (PolicyStatus) String added in v1.18.0

func (s PolicyStatus) String() string

type RedundantEventsAnalysis added in v1.18.0

type RedundantEventsAnalysis struct {
	// contains filtered or unexported fields
}

RedundantEventsAnalysis identifies events where another event in the same execution context already captures the same information.

func (RedundantEventsAnalysis) ActionDetail added in v1.18.0

func (a RedundantEventsAnalysis) ActionDetail() string

func (RedundantEventsAnalysis) Category added in v1.18.0

func (RedundantEventsAnalysis) Rationale added in v1.18.0

func (a RedundantEventsAnalysis) Rationale() string

func (RedundantEventsAnalysis) RelevantKeys added in v1.18.0

func (a RedundantEventsAnalysis) RelevantKeys() []FieldPath

func (RedundantEventsAnalysis) Subtitle added in v1.18.0

func (a RedundantEventsAnalysis) Subtitle() string

type Role

type Role string

Role identifies who sent a message.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
)

type SecretsLeakageAnalysis added in v1.16.0

type SecretsLeakageAnalysis struct {
	Fields []SensitiveField `json:"fields"`
	// contains filtered or unexported fields
}

SecretsLeakageAnalysis is the category-specific analysis for secrets leakage policies.

func (SecretsLeakageAnalysis) ActionDetail added in v1.18.0

func (a SecretsLeakageAnalysis) ActionDetail() string

func (SecretsLeakageAnalysis) Category added in v1.18.0

func (SecretsLeakageAnalysis) Rationale added in v1.16.0

func (a SecretsLeakageAnalysis) Rationale() string

func (SecretsLeakageAnalysis) RelevantKeys added in v1.18.0

func (a SecretsLeakageAnalysis) RelevantKeys() []FieldPath

func (SecretsLeakageAnalysis) Subtitle added in v1.18.0

func (a SecretsLeakageAnalysis) Subtitle() string

type SensitiveField added in v1.16.0

type SensitiveField struct {
	Path     FieldPath `json:"path"`     // Attribute path, e.g. ["attributes", "user", "email"]
	Types    []string  `json:"types"`    // Types of sensitive data this field could contain
	Observed bool      `json:"observed"` // True if actual sensitive data was seen in log values
}

SensitiveField identifies a field that may contain sensitive data. Matches control plane's SensitiveField struct used across all compliance categories.

type ServiceHealth added in v1.15.0

type ServiceHealth string

ServiceHealth is the health status for a service or account.

const (
	ServiceHealthDisabled ServiceHealth = "DISABLED"
	ServiceHealthInactive ServiceHealth = "INACTIVE"
	ServiceHealthError    ServiceHealth = "ERROR"
	ServiceHealthOK       ServiceHealth = "OK"
)

func (ServiceHealth) String added in v1.15.0

func (s ServiceHealth) String() string

type ServiceID added in v1.15.0

type ServiceID string

ServiceID is a unique identifier for a service.

func (ServiceID) String added in v1.15.0

func (id ServiceID) String() string

type ServiceStatus

type ServiceStatus struct {
	Name   string
	Health ServiceHealth

	// Error / warning state.
	Error     string
	ErrorAt   string
	Warning   string
	WarningAt string

	// Event counts.
	LogEventCount            int64
	LogEventAnalyzedCount    int64
	LogEventQuarantinedCount int64

	// Policy counts.
	PolicyPendingCount   int64
	PolicyApprovedCount  int64
	PolicyDismissedCount int64

	// Service-level throughput (ground truth from service_log_volumes). Nil when unmeasured.
	ServiceVolumePerHour        *float64
	ServiceDebugVolumePerHour   *float64
	ServiceInfoVolumePerHour    *float64
	ServiceWarnVolumePerHour    *float64
	ServiceErrorVolumePerHour   *float64
	ServiceOtherVolumePerHour   *float64
	ServiceCostPerHourVolumeUSD *float64

	// Log event throughput (discovered events subset). Nil when unmeasured.
	LogEventVolumePerHour        *float64
	LogEventBytesPerHour         *float64
	LogEventCostPerHourUSD       *float64
	LogEventCostPerHourBytesUSD  *float64
	LogEventCostPerHourVolumeUSD *float64

	// Estimated savings from pending policies. Nil when unmeasured.
	EstimatedVolumeReductionPerHour     *float64
	EstimatedBytesReductionPerHour      *float64
	EstimatedCostReductionPerHourUSD    *float64
	EstimatedCostReductionPerHourBytes  *float64
	EstimatedCostReductionPerHourVolume *float64

	// Observed impact from approved policies (before/after). Nil when unmeasured.
	ObservedVolumePerHourBefore        *float64
	ObservedVolumePerHourAfter         *float64
	ObservedBytesPerHourBefore         *float64
	ObservedBytesPerHourAfter          *float64
	ObservedCostPerHourBeforeUSD       *float64
	ObservedCostPerHourBeforeBytesUSD  *float64
	ObservedCostPerHourBeforeVolumeUSD *float64
	ObservedCostPerHourAfterUSD        *float64
	ObservedCostPerHourAfterBytesUSD   *float64
	ObservedCostPerHourAfterVolumeUSD  *float64
}

ServiceStatus mirrors service_statuses_cache. All columns included; callers pick what they need.

type TextBlock

type TextBlock struct {
	Content string `json:"content"`
}

TextBlock is prose content.

type Thinking

type Thinking struct {
	Content string `json:"content"`
}

Thinking is the AI's internal reasoning.

type ToolInputDelta

type ToolInputDelta struct {
	ToolUseID string `json:"tool_use_id"`
	Delta     string `json:"delta"`
}

ToolInputDelta is a streaming fragment of tool input JSON.

type ToolResult

type ToolResult struct {
	ToolUseID string         `json:"tool_use_id"`
	IsError   bool           `json:"is_error,omitempty"`
	Error     string         `json:"error,omitempty"`
	Content   map[string]any `json:"content,omitempty"`
}

ToolResult is the outcome of a tool call (wire/storage format).

type ToolUse

type ToolUse struct {
	ID            string          `json:"id"`
	Name          string          `json:"name"`
	Input         json.RawMessage `json:"input"`
	InputComplete bool            `json:"-"` // True when input is fully received (after content_block_stop)
}

ToolUse represents the AI calling a tool.

type VaryingField added in v1.18.0

type VaryingField struct {
	Key    string
	Values []string // deduplicated, up to 4
}

VaryingField is a key with multiple distinct values across examples.

type WastePolicy added in v1.15.0

type WastePolicy struct {
	LogEventName               string
	ServiceName                string
	VolumePerHour              *float64 // Current throughput in events/hour; nil when unmeasured
	BytesPerHour               *float64 // Current throughput in bytes/hour; nil when unmeasured
	EstimatedCostPerHour       *float64 // Estimated cost reduction (total); nil when unmeasured
	EstimatedCostPerHourBytes  *float64 // Estimated cost reduction from bytes; nil when unmeasured
	EstimatedCostPerHourVolume *float64 // Estimated cost reduction from volume; nil when unmeasured
	EstimatedBytesPerHour      *float64 // Estimated bytes reduction; nil when unmeasured
	EstimatedVolumePerHour     *float64 // Estimated volume reduction; nil when unmeasured
}

WastePolicy is a single pending waste policy with context from joined tables. Float pointers are nil when the underlying data hasn't been measured yet.

type WorkosOrganizationID

type WorkosOrganizationID string

WorkosOrganizationID is the external ID from WorkOS.

func (WorkosOrganizationID) String

func (id WorkosOrganizationID) String() string

type Workspace

type Workspace struct {
	ID   WorkspaceID `json:"id"`
	Name string      `json:"name"`
}

Workspace represents a workspace within an account.

func (Workspace) FilterValue

func (w Workspace) FilterValue() string

FilterValue returns the string used for filtering/searching.

type WorkspaceID

type WorkspaceID string

WorkspaceID is a unique identifier for a workspace.

func NewWorkspaceID

func NewWorkspaceID() WorkspaceID

NewWorkspaceID generates a new unique WorkspaceID.

func (WorkspaceID) String

func (id WorkspaceID) String() string

type WrongLevelAnalysis added in v1.18.0

type WrongLevelAnalysis struct {
	CurrentLevel   string `json:"current_level"`   // Normalized level the event currently uses (debug, info, warn, error)
	SuggestedLevel string `json:"suggested_level"` // Normalized level the event should use
	// contains filtered or unexported fields
}

WrongLevelAnalysis identifies events emitted at the wrong severity level.

func (WrongLevelAnalysis) ActionDetail added in v1.18.0

func (a WrongLevelAnalysis) ActionDetail() string

func (WrongLevelAnalysis) Category added in v1.18.0

func (a WrongLevelAnalysis) Category() PolicyCategory

func (WrongLevelAnalysis) Rationale added in v1.18.0

func (a WrongLevelAnalysis) Rationale() string

func (WrongLevelAnalysis) RelevantKeys added in v1.18.0

func (a WrongLevelAnalysis) RelevantKeys() []FieldPath

func (WrongLevelAnalysis) Subtitle added in v1.18.0

func (a WrongLevelAnalysis) Subtitle() string

Directories

Path Synopsis
Package domaintest provides factories for creating domain objects in tests.
Package domaintest provides factories for creating domain objects in tests.
Package tools defines tool input/output types.
Package tools defines tool input/output types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL