Documentation
¶
Overview ¶
Package state is AgentShield's PostgreSQL store: contribution publication, the current graph, the change feed, findings, detection signals, the investigation queue, and detector persistence.
Pipeline position ¶
Discovery plugins and the telemetry rollup produce complete contributions. Store.ReplaceContribution publishes authoritative complete checkpoints; Store.ApplyContributionDelta publishes explicit changes between them. Both validate with the graph compiler and commit in one transaction. Publication appends to a transactional outbox that the detection service reads with Store.ReadContributionChanges and Store.ReadGraphCheckpoint; detection then records DetectionSignal values and rule Finding values, enqueues investigation jobs, and advances a ReasoningCursor. The investigation worker claims and admits jobs (Store.ClaimInvestigationJob, Store.AdmitInvestigationJob) and records agentic findings. Detector rulesets, resource rule-authoring jobs, and their review status (Store.ReadResourceRules, Store.ReadResourceRulesForDetector) are stored here as well.
Contributions and generations ¶
A Contribution is the complete assertion set owned by one (plugin, source, name) tuple. Each publication is a new generation; assertions omitted from it are retracted. Generations must increase: an older generation is rejected, the same generation with the same input digest is an idempotent retry, and the same generation with a different digest is an error. Store.ContributionGeneration lets a restarted plugin resume above its last durable generation.
Publication ¶
Publication locks the graph revision and contribution head, persists new content-addressed assertions, advances the contribution head, updates active membership and the affected projection closure, and appends at most one outbox event. Readers never see a partially published contribution.
Change feed ¶
Each outbox event carries a monotonic sequence and the non-telemetry assertions added and retracted by one contribution version. Telemetry-only publications that do not change readiness, health, or status are committed without an outbox event, so telemetry cadence does not drive detection.
Reads ¶
Store.Latest and Store.ReadGraphCheckpoint read the current projection inside a repeatable-read transaction, so the returned graph and revision are coherent with each other and with the checkpoint sequence. Store.CreateManifest pins the active contribution versions for reproducible analysis.
Schema files are embedded and verified by checksum at startup. Until the first release, baseline changes require recreating the database.
See https://agent-shield.dev/docs/architecture/publication-and-storage/ and https://agent-shield.dev/docs/concepts/data-model/.
Index ¶
- Constants
- Variables
- func NormalizeObservedOperation(operation string) string
- func ValidateNeighborhoodQuery(resourceID string, depth int, direction string) error
- type AnalysisViewToken
- type AssertionChange
- type Config
- type Contribution
- type ContributionChangeEvent
- type ContributionDelta
- type ContributionEventOwner
- type DetectionSignal
- type DetectionSignalQuery
- type EntityLocator
- type Finding
- type FindingPage
- type FindingQuery
- type GraphCheckpoint
- type GraphManifest
- type GraphView
- type InvestigationAdmission
- type InvestigationJob
- type InvestigationJobRecord
- type InvestigationJobSummary
- type ManifestContribution
- type ManifestStatus
- type NativeEvent
- type Neighborhood
- type ObservedRequest
- type Publication
- type ReasoningCursor
- type RelationshipDetail
- type RelationshipPage
- type RelationshipQuery
- type ResourceAuthoringContext
- type ResourceDetail
- type ResourcePage
- type ResourceQuery
- type ResourceRuleJob
- type ResourceRuleJobSummary
- type ResourceRuleQueueStats
- type ResourceRuleRetry
- type Store
- func (s *Store) ActivateDetectorRuleset(ctx context.Context, id string, expectedRevision uint64, actor string) (uint64, error)
- func (s *Store) AdmitInvestigationJob(ctx context.Context, jobID int64, workerID string, ...) (string, error)
- func (s *Store) AdvanceReasoningCursor(ctx context.Context, cursor ReasoningCursor) error
- func (s *Store) ApplyContributionDelta(ctx context.Context, delta ContributionDelta) (Publication, error)
- func (s *Store) ClaimInvestigationJob(ctx context.Context, workerID string, lease time.Duration) (InvestigationJob, bool, error)
- func (s *Store) ClaimResourceRuleJob(ctx context.Context, workerID string, leaseInterval, minAge time.Duration) (ResourceRuleJob, bool, error)
- func (s *Store) Close() error
- func (s *Store) CompleteInvestigationJob(ctx context.Context, jobID int64, workerID string, outcome json.RawMessage) error
- func (s *Store) CompleteResourceRuleJob(ctx context.Context, jobID int64, workerID string, proposal json.RawMessage) error
- func (s *Store) ContributionGeneration(ctx context.Context, pluginID, sourceID string) (uint64, error)
- func (s *Store) CreateAnalysisView(ctx context.Context, evaluationTime time.Time) (AnalysisViewToken, GraphManifest, error)
- func (s *Store) CreateManifest(ctx context.Context) (GraphManifest, error)
- func (s *Store) CurrentGraph(ctx context.Context) (GraphView, error)
- func (s *Store) EnqueueInvestigationJob(ctx context.Context, record InvestigationJobRecord, batchWindow time.Duration, ...) (int64, bool, error)
- func (s *Store) EnsureDefaultDetectorRuleset(ctx context.Context) error
- func (s *Store) GetFinding(ctx context.Context, findingID string) (Finding, error)
- func (s *Store) GetRelationshipDetail(ctx context.Context, relationshipID string) (RelationshipDetail, error)
- func (s *Store) GetResourceDetail(ctx context.Context, resourceID string) (ResourceDetail, error)
- func (s *Store) GraphRevision(ctx context.Context) (uint64, error)
- func (s *Store) InvalidateFindings(ctx context.Context, graphRevision uint64, throughSequence uint64, ...) error
- func (s *Store) Latest(ctx context.Context) (GraphView, error)
- func (s *Store) ListDetectionSignals(ctx context.Context, query DetectionSignalQuery) ([]DetectionSignal, error)
- func (s *Store) ListInvestigationJobs(ctx context.Context, limit int) ([]InvestigationJobSummary, error)
- func (s *Store) ListResourceRuleJobs(ctx context.Context, limit int, resourceID string) ([]ResourceRuleJobSummary, error)
- func (s *Store) Neighborhood(ctx context.Context, resourceID string, depth int, direction string, limit int) (Neighborhood, error)
- func (s *Store) NormalizeIdentityClaim(claim graph.IdentityClaim) (graph.IdentityClaim, error)
- func (s *Store) Ping(ctx context.Context) error
- func (s *Store) PruneDetectionSignals(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PruneInvestigationJobs(ctx context.Context, before time.Time) (int64, error)
- func (s *Store) PutFinding(ctx context.Context, finding Finding) error
- func (s *Store) QueryFindings(ctx context.Context, query FindingQuery) (FindingPage, error)
- func (s *Store) QueryRelationships(ctx context.Context, query RelationshipQuery) (RelationshipPage, error)
- func (s *Store) QueryResources(ctx context.Context, query ResourceQuery) (ResourcePage, error)
- func (s *Store) ReadActiveDetectorRuleset(ctx context.Context) (detector.Activation, error)
- func (s *Store) ReadContributionChanges(ctx context.Context, afterSequence uint64, limit int) ([]ContributionChangeEvent, error)
- func (s *Store) ReadDetectorRuleset(ctx context.Context, id string) (detector.Ruleset, error)
- func (s *Store) ReadGraphCheckpoint(ctx context.Context) (GraphCheckpoint, error)
- func (s *Store) ReadReasoningCursor(ctx context.Context, consumerID string) (ReasoningCursor, bool, error)
- func (s *Store) ReadResourceRules(ctx context.Context) ([]detector.ResourceRule, error)
- func (s *Store) ReadResourceRulesForDetector(ctx context.Context) ([]detector.ResourceRule, error)
- func (s *Store) RecordDetectionSignals(ctx context.Context, signals []DetectionSignal) error
- func (s *Store) RecordNative(ctx context.Context, event NativeEvent) error
- func (s *Store) RenewInvestigationJob(ctx context.Context, jobID int64, workerID string, lease time.Duration) (bool, error)
- func (s *Store) RenewResourceRuleJob(ctx context.Context, jobID int64, workerID string, leaseInterval time.Duration) (bool, error)
- func (s *Store) ReplaceContribution(ctx context.Context, contribution Contribution) (Publication, error)
- func (s *Store) RequestResourceRuleJob(ctx context.Context, resourceID, actor string) (ResourceRuleJobSummary, error)
- func (s *Store) ResourceRuleJobStatus(ctx context.Context, jobID int64) (ResourceRuleJobSummary, bool, error)
- func (s *Store) ResourceRuleProposal(ctx context.Context, jobID int64) (json.RawMessage, bool, error)
- func (s *Store) ResourceRuleQueueStats(ctx context.Context, minAge time.Duration) (ResourceRuleQueueStats, error)
- func (s *Store) RetireContribution(ctx context.Context, pluginID, sourceID, name string, generation uint64, ...) (Publication, error)
- func (s *Store) RetryInvestigationJob(ctx context.Context, jobID int64, workerID, failure string, ...) error
- func (s *Store) RetryResourceRuleJob(ctx context.Context, jobID int64, workerID, failure string, ...) (ResourceRuleRetry, error)
- func (s *Store) ReviewResourceRuleJobRules(ctx context.Context, jobID int64, decision, actor string, ...) error
- func (s *Store) SaveDetectorRuleset(ctx context.Context, ruleset detector.Ruleset, actor string) error
- func (s *Store) SkipInvestigationJob(ctx context.Context, jobID int64, workerID, reason string) error
- func (s *Store) WorkloadObservedBehavior(ctx context.Context, resourceID string) (WorkloadBehavior, error)
- type WorkloadBehavior
Constants ¶
const ( // InvestigationInvestigated means agentic investigation analyzed the signal inline. InvestigationInvestigated = "investigated" // InvestigationQueued means the signal was handed to the agentic investigation queue, // whose job records whether it was investigated, batched, or sampled out. InvestigationQueued = "queued" // InvestigationBelowThreshold means no signal in the window was eligible, so no agent ran. InvestigationBelowThreshold = "below_threshold" // InvestigationDisabled means the window had an eligible signal but agentic investigation is disabled. InvestigationDisabled = "disabled" // InvestigationShadow means the signal came from an unreviewed resource rule and is never investigated. InvestigationShadow = "shadow" // InvestigationRuleFinding means the signal came from an active detection rule and became a finding directly. InvestigationRuleFinding = "rule_finding" )
Detection signal investigation states.
const ( FindingStatusActive = "active" FindingStatusInvalidated = "invalidated" )
Finding statuses. Invalidated findings are retained for audit but cannot launch remediation.
const ( FindingOriginAgenticInvestigation = "agentic_investigation" FindingOriginDetectionRule = "detection_rule" )
Finding origins. Agentic investigation findings are promoted from a model assessment; detection rule findings are created directly from an active rule match.
const ( InvestigationJobQueued = "queued" InvestigationJobRunning = "running" InvestigationJobRetryable = "retryable" InvestigationJobCompleted = "completed" InvestigationJobSampledOut = "sampled_out" InvestigationJobFailed = "failed" )
Investigation job states. Terminal states are completed, sampled_out, and failed.
const ( InvestigationAdmitted = "admitted" InvestigationDuplicate = "duplicate" InvestigationOverBudget = "budget" InvestigationDeferred = "deferred" )
Admission decisions for a claimed investigation job.
const ( MaxObservedRequests = 32 MaxCollectedTelemetry = 16 )
Limits on WorkloadBehavior, which is sent to a model.
const ( ResourceRuleReviewPending = "pending" ResourceRuleReviewApproved = "approved" ResourceRuleReviewRejected = "rejected" )
Resource rule review decisions. Pending drafts run in shadow mode; approved rules run in active mode; rejected rules are not loaded.
const ( SourceHealthHealthy = "healthy" SourceHealthDegraded = "degraded" SourceHealthStale = "stale" SourceHealthUnknown = "unknown" )
Source health values accepted on a Contribution. They describe the upstream source, independently of contribution readiness.
const ( ContributionStatusActive = "active" ContributionStatusDegraded = "degraded" ContributionStatusStale = "stale" ContributionStatusRetired = "retired" )
Contribution head statuses, derived from Retired, Ready, and SourceHealth by contributionStatus. They appear in manifests and change events.
const MaxInvestigationJobSpan = 1000
MaxInvestigationJobSpan is the largest change range one job may cover, matching the change reader's batch limit.
const MaxResourceRuleProposalRules = 3
MaxResourceRuleProposalRules bounds rules stored in one authoring proposal.
const (
ResourceAuthoringContextMaxBytes = 48 << 10
)
Variables ¶
var ( ErrResourceRuleJobNotFound = errors.New("resource rule authoring job not found") ErrResourceRuleJobNotReviewable = errors.New("resource rule job is not reviewable") ErrResourceRuleJobInProgress = errors.New("resource rule authoring is already in progress") ErrResourceRuleSelectionInvalid = errors.New("resource rule selection is invalid") )
Resource rule job errors.
var ErrContributionDeltaBaseMismatch = errors.New("contribution delta base generation does not match current generation")
ErrContributionDeltaBaseMismatch requires the publisher to recover with a complete contribution replacement based on the current durable generation.
var ErrContributionDeltaMembershipMismatch = errors.New("contribution delta does not match current membership")
ErrContributionDeltaMembershipMismatch requires the publisher to recover with a complete contribution replacement.
var ErrFindingNotFound = errors.New("finding not found")
ErrFindingNotFound is returned by GetFinding for an unknown ID.
var ErrGraphEntityNotFound = errors.New("graph entity not found")
ErrGraphEntityNotFound is returned by current-projection detail reads.
var ErrNotMaterialized = errors.New("graph is not materialized")
ErrNotMaterialized is returned by graph reads before any contribution has been published.
Functions ¶
func NormalizeObservedOperation ¶
NormalizeObservedOperation drops the query string and fragment from an operation of the form "METHOD path" and replaces identifier-like path segments (all digits, or 16 or more hex characters and dashes, such as a UUID) with {id}, so a baseline describes API shape rather than individual records.
func ValidateNeighborhoodQuery ¶
ValidateNeighborhoodQuery checks the arguments Store.Neighborhood accepts. Its errors describe only the arguments, so callers may show them to clients.
Types ¶
type AnalysisViewToken ¶
type AnalysisViewToken struct {
ManifestID string `json:"manifestId"`
EvaluationTime time.Time `json:"evaluationTime"`
}
AnalysisViewToken adds evaluation time to a manifest for reproducible analysis.
type AssertionChange ¶
type AssertionChange struct {
AssertionType string `json:"assertionType"`
AssertionID string `json:"assertionId"`
Entity EntityLocator `json:"entity"`
}
AssertionChange is one assertion added to or retracted from a contribution.
type Config ¶
type Config struct {
DatabaseURL string
MaxConnections int32
MinConnections int32
MaxConnLifetime time.Duration
MaxConnIdleTime time.Duration
// UnresolvedRetention sets expires_at on projected unresolved
// relationships. It is recorded for consumers but not enforced: an
// unresolved edge leaves the projection only when its endpoints resolve
// or its owning contribution omits it. Default 24h.
UnresolvedRetention time.Duration
// PublicationTimeout bounds one whole publication so a stuck publication
// cannot hold a pooled connection indefinitely. It is also the transaction's
// idle_in_transaction_session_timeout. Default 5m.
PublicationTimeout time.Duration
// PublicationLockTimeout is the publication transaction's lock_timeout.
// Default 2m.
PublicationLockTimeout time.Duration
// PublicationStatementTimeout is the publication transaction's
// statement_timeout. Default 2m.
PublicationStatementTimeout time.Duration
// MigrationTimeout bounds schema migration in Open. Migration does not
// inherit the caller's deadline, because a migration that rebuilds a
// constraint on a large table can outlast a short startup budget and
// would then fail every start. Default 30m.
MigrationTimeout time.Duration
// InvestigationMaxAttempts fails an investigation job instead of
// reclaiming it once an expired lease would bring its attempt count to
// this value. An expired lease counts as a failed attempt, so a job that
// crashes its worker cannot be re-leased forever. Default 5, matching the
// investigation worker's default.
InvestigationMaxAttempts int
}
Config configures the PostgreSQL store. Zero values select defaults.
type Contribution ¶
type Contribution struct {
PluginID string `json:"pluginId"`
SourceID string `json:"sourceId"`
Name string `json:"name"`
Generation uint64 `json:"generation"`
Input graph.Input `json:"input"`
// SourceObservedAt is when the source state behind Input was observed.
// Zero defaults to the publication time.
SourceObservedAt time.Time `json:"sourceObservedAt"`
// Ready reports that Input reflects a coherent source view. It is
// independent of collection readiness and of SourceHealth.
Ready bool `json:"ready"`
// SourceHealth is one of the SourceHealth constants; empty means healthy.
SourceHealth string `json:"sourceHealth"`
// Retired marks a terminal empty generation; see RetireContribution.
Retired bool `json:"retired,omitempty"`
// UpdatedAt is set by the store at publication time.
UpdatedAt time.Time `json:"updatedAt"`
}
Contribution is the complete assertion set owned by one plugin, source, and name. Advancing its generation replaces membership and retracts omissions.
type ContributionChangeEvent ¶
type ContributionChangeEvent struct {
Sequence uint64 `json:"sequence"`
Contribution ContributionEventOwner `json:"contribution"`
Added []AssertionChange `json:"added,omitempty"`
Retracted []AssertionChange `json:"retracted,omitempty"`
}
ContributionChangeEvent is one outbox entry: the non-telemetry membership delta of one contribution version. Several events may touch the same graph entity; consumers should batch and resolve current truth from a checkpoint.
type ContributionDelta ¶
type ContributionDelta struct {
PluginID string `json:"pluginId"`
SourceID string `json:"sourceId"`
Name string `json:"name"`
BaseGeneration uint64 `json:"baseGeneration"`
Generation uint64 `json:"generation"`
Added graph.Input `json:"added"`
Retracted graph.Input `json:"retracted"`
SourceObservedAt time.Time `json:"sourceObservedAt"`
Ready bool `json:"ready"`
SourceHealth string `json:"sourceHealth"`
}
ContributionDelta advances one existing contribution by explicitly adding and retracting assertions relative to BaseGeneration.
type ContributionEventOwner ¶
type ContributionEventOwner struct {
VersionID int64 `json:"versionId"`
PluginID string `json:"pluginId"`
SourceID string `json:"sourceId"`
Name string `json:"name"`
Generation uint64 `json:"generation"`
Ready bool `json:"ready"`
SourceHealth string `json:"sourceHealth"`
SourceObservedAt time.Time `json:"sourceObservedAt"`
Status string `json:"status"`
}
ContributionEventOwner identifies the contribution version that produced a change event, with its readiness and health at that version.
type DetectionSignal ¶
type DetectionSignal struct {
Signal detector.InvestigationSignal `json:"signal"`
ThroughSequence uint64 `json:"throughSequence"`
GraphRevision uint64 `json:"graphRevision"`
Investigation string `json:"investigation"`
RecordedAt time.Time `json:"recordedAt"`
}
DetectionSignal is one recorded detector signal and what happened to it.
type DetectionSignalQuery ¶
type EntityLocator ¶
type EntityLocator struct {
EntityType string `json:"entityType"`
ID string `json:"id"`
ResourceID string `json:"resourceId,omitempty"`
SubjectID string `json:"subjectId,omitempty"`
Predicate string `json:"predicate,omitempty"`
ObjectID string `json:"objectId,omitempty"`
Kind string `json:"kind,omitempty"`
Qualifier string `json:"qualifier,omitempty"`
}
EntityLocator identifies the compiled graph entity an assertion belongs to. For relationships it carries both endpoints and the predicate so a consumer can act on a retraction without reading the retracted row.
type Finding ¶
type Finding struct {
ID string `json:"id"`
Origin string `json:"origin"`
AnalysisID string `json:"analysisId"`
GraphRevision uint64 `json:"graphRevision"`
Category string `json:"category"`
Severity string `json:"severity"`
ModelUncertainty string `json:"modelUncertainty,omitempty"`
DetectionRuleID string `json:"detectionRuleId,omitempty"`
DetectionRuleRevision uint64 `json:"detectionRuleRevision,omitempty"`
Summary string `json:"summary"`
SignalIDs []string `json:"signalIds"`
AffectedEntityIDs []string `json:"affectedEntityIds"`
Remediations []remediation.Proposal `json:"remediations"`
Status string `json:"status"`
CreatedAt time.Time `json:"createdAt"`
InvalidatedAt *time.Time `json:"invalidatedAt,omitempty"`
InvalidatedBySequence *uint64 `json:"invalidatedBySequence,omitempty"`
InvalidatedGraphRevision uint64 `json:"invalidatedGraphRevision,omitempty"`
}
Finding is a promoted reasoning result grounded in one graph revision. AffectedEntityIDs drive invalidation when later publications touch those entities.
type FindingPage ¶
FindingPage is one page of findings. Total counts every finding matching the filters, ignoring the cursor.
type FindingQuery ¶
type FindingQuery struct {
Status string
Severity string
Category string
AffectedEntityID string
Limit int
BeforeCreatedAt *time.Time
BeforeFindingID string
}
FindingQuery filters and pages findings. BeforeCreatedAt and BeforeFindingID together form the keyset cursor for the next page.
func (FindingQuery) Validate ¶
func (query FindingQuery) Validate() error
Validate checks status, limit (1-100), and cursor completeness.
type GraphCheckpoint ¶
type GraphCheckpoint struct {
ThroughSequence uint64 `json:"throughSequence"`
View GraphView `json:"view"`
}
GraphCheckpoint pairs an outbox position with the graph compiled from the same database snapshot.
type GraphManifest ¶
type GraphManifest struct {
ID string `json:"id"`
CreatedAt time.Time `json:"createdAt"`
Digest string `json:"digest"`
ParentID string `json:"parentId,omitempty"`
StatusSummary ManifestStatus `json:"statusSummary"`
Contributions []ManifestContribution `json:"contributions"`
}
GraphManifest pins one active version of each contribution, forming a reproducible system-wide graph selection without a global graph revision.
type GraphView ¶
type GraphView struct {
GeneratedAt time.Time `json:"generatedAt"`
Revision uint64 `json:"revision"`
Snapshot graph.Snapshot `json:"snapshot"`
}
GraphView is a compiled graph at one committed publication revision. GeneratedAt is the most recent contribution head update.
type InvestigationAdmission ¶
type InvestigationAdmission struct {
// DedupWindow skips a job whose fingerprint was admitted within the window; zero disables it.
DedupWindow time.Duration
// MaxPerHour caps admissions in any trailing hour; zero is unlimited.
MaxPerHour int
// DeferRiskRank defers, rather than skips, over-budget jobs at or above this rank.
DeferRiskRank int
// DeferFor is how long an over-budget job at or above DeferRiskRank waits before retrying admission.
DeferFor time.Duration
}
InvestigationAdmission bounds model spend for claimed jobs.
type InvestigationJob ¶
type InvestigationJob struct {
ID int64 `json:"id"`
InvestigationJobRecord
AttemptCount int `json:"attemptCount"`
Admitted bool `json:"admitted"`
}
InvestigationJob is a claimed job.
type InvestigationJobRecord ¶
type InvestigationJobRecord struct {
RiskRank int `json:"riskRank"`
AnchorIDs []string `json:"anchorIds"`
Fingerprint string `json:"fingerprint"`
SampleKey string `json:"sampleKey"`
FirstSequence uint64 `json:"firstSequence"`
LastSequence uint64 `json:"lastSequence"`
Request json.RawMessage `json:"request"`
}
InvestigationJobRecord is the indexed form of an investigation request. Request is opaque to storage; the caller owns its schema and merge semantics.
type InvestigationJobSummary ¶
type InvestigationJobSummary struct {
ID int64 `json:"id"`
Status string `json:"status"`
RiskRank int `json:"riskRank"`
AnchorIDs []string `json:"anchorIds"`
FirstSequence uint64 `json:"firstSequence"`
LastSequence uint64 `json:"lastSequence"`
AttemptCount int `json:"attemptCount"`
SkipReason string `json:"skipReason,omitempty"`
LastError string `json:"lastError,omitempty"`
Outcome json.RawMessage `json:"outcome,omitempty"`
CreatedAt time.Time `json:"createdAt"`
AvailableAt time.Time `json:"availableAt"`
AdmittedAt *time.Time `json:"admittedAt,omitempty"`
CompletedAt *time.Time `json:"completedAt,omitempty"`
}
type ManifestContribution ¶
type ManifestContribution struct {
ContributionID int64 `json:"contributionId"`
PluginID string `json:"pluginId"`
SourceID string `json:"sourceId"`
Name string `json:"name"`
ContributionVersionID int64 `json:"contributionVersionId"`
Generation uint64 `json:"generation"`
Status string `json:"status"`
SourceObservedAt time.Time `json:"sourceObservedAt"`
PublishedAt time.Time `json:"publishedAt"`
Ready bool `json:"ready"`
SourceHealth string `json:"sourceHealth"`
}
ManifestContribution is one contribution version pinned by a manifest.
type ManifestStatus ¶
type ManifestStatus struct {
Contributions int `json:"contributions"`
UnresolvedRelationships int `json:"unresolvedRelationships"`
Conflicts int `json:"conflicts"`
}
ManifestStatus summarizes projection health at manifest creation.
type NativeEvent ¶
type NativeEvent struct {
EventID string `json:"eventId"`
PluginID string `json:"pluginId"`
SourceID string `json:"sourceId"`
Collection string `json:"collection"`
Key string `json:"key"`
Revision string `json:"revision,omitempty"`
Operation string `json:"operation"`
ObservedAt time.Time `json:"observedAt"`
Payload json.RawMessage `json:"payload,omitempty"`
}
NativeEvent is one provider observation delivered through the discovery hub. PostgreSQL retains its metadata and content digest, not Payload. EventID must be stable: re-recording an ID with the same content is a no-op and with different content is an error.
type Neighborhood ¶
type Neighborhood struct {
Revision uint64 `json:"revision"`
Resources []graph.Resource `json:"resources"`
Relationships []graph.Relationship `json:"relationships"`
}
Neighborhood is a bounded subgraph around one resource.
type ObservedRequest ¶
type ObservedRequest struct {
Telemetry string `json:"telemetry"`
Destination string `json:"destination,omitempty"`
DestinationResourceID string `json:"destinationResourceId,omitempty"`
DestinationKind string `json:"destinationKind"`
DestinationRole string `json:"destinationRole,omitempty"`
Operation string `json:"operation,omitempty"`
Outcome string `json:"outcome,omitempty"`
Count uint64 `json:"count"`
}
ObservedRequest is one distinct (telemetry kind, destination, operation, outcome) combination and how often it was observed. Destinations include a stable graph resource ID but never a raw address.
type Publication ¶
type ReasoningCursor ¶
type ReasoningCursor struct {
ConsumerID string `json:"consumerId"`
ThroughSequence uint64 `json:"throughSequence"`
GraphRevision uint64 `json:"graphRevision"`
UpdatedAt time.Time `json:"updatedAt"`
}
ReasoningCursor is a consumer's durable outbox position and graph revision it evaluated at that position.
type RelationshipDetail ¶
type RelationshipPage ¶
type RelationshipPage struct {
GraphRevision uint64
Relationships []graph.Relationship
Next string
}
type RelationshipQuery ¶
type ResourceAuthoringContext ¶
type ResourceAuthoringContext struct {
ResourceID string `json:"resourceId"`
Kind string `json:"kind"`
Name string `json:"name,omitempty"`
Namespace string `json:"namespace,omitempty"`
ContextSHA256 string `json:"contextSha256"`
Context json.RawMessage `json:"context"`
Attributes map[string]string `json:"attributes,omitempty"`
// ObservedBehavior is the workload's baseline of outbound requests. Nil
// means no baseline was taken; an empty request list means one was taken
// and the workload made no outbound requests. The authoring worker sets
// it when it claims a job; the queue stores only identity.
ObservedBehavior *WorkloadBehavior `json:"observedBehavior,omitempty"`
}
ResourceAuthoringContext is the bounded plugin context given to the rule author.
func ResourceAuthoringContextFor ¶
func ResourceAuthoringContextFor(resource graph.Resource) ResourceAuthoringContext
ResourceAuthoringContextFor returns a resource's bounded plugin context.
type ResourceDetail ¶
type ResourcePage ¶
type ResourceQuery ¶
type ResourceRuleJob ¶
type ResourceRuleJob struct {
ID int64 `json:"id"`
Context ResourceAuthoringContext `json:"context"`
AttemptCount int `json:"attemptCount"`
}
ResourceRuleJob is a claimed rule-authoring job.
type ResourceRuleJobSummary ¶
type ResourceRuleJobSummary struct {
ID int64 `json:"id"`
ResourceID string `json:"resourceId"`
// ContextSHA256 identifies the bounded authoring context for this job.
ContextSHA256 string `json:"contextSha256,omitempty"`
// Status is queued, running, retryable, completed, or failed.
Status string `json:"status"`
AttemptCount int `json:"attemptCount"`
LastError string `json:"lastError,omitempty"`
ReviewStatus string `json:"reviewStatus"`
ReviewedBy string `json:"reviewedBy,omitempty"`
ReviewedAt *time.Time `json:"reviewedAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
CompletedAt *time.Time `json:"completedAt,omitempty"`
// RuleCount is the number of rules in a completed proposal.
RuleCount int `json:"ruleCount"`
// RequestedBy and RequestedAt record the operator's last regeneration request.
RequestedBy string `json:"requestedBy,omitempty"`
RequestedAt *time.Time `json:"requestedAt,omitempty"`
// CurrentRevision reports whether the job is for the resource's current authoring context.
CurrentRevision bool `json:"currentRevision"`
}
ResourceRuleJobSummary is a job's status without its proposal.
type ResourceRuleQueueStats ¶
type ResourceRuleQueueStats struct {
// WaitingForStabilization jobs are queued but younger than the stabilization window.
WaitingForStabilization int
// Ready jobs can be claimed now.
Ready int
Running int
Retrying int
// Failed jobs exhausted their attempts and wait for an operator request.
Failed int
// NextEligibleAt is when the next stabilization wait ends, if any job is waiting.
NextEligibleAt *time.Time
}
ResourceRuleQueueStats counts authoring jobs by what they wait for.
type ResourceRuleRetry ¶
type ResourceRuleRetry int
ResourceRuleRetry is what Store.RetryResourceRuleJob did with a job.
const ( // ResourceRuleRetryScheduled made the job available again after the delay. ResourceRuleRetryScheduled ResourceRuleRetry = iota // ResourceRuleRetryFailed ended the job as failed; only an operator // request queues it again. ResourceRuleRetryFailed // ResourceRuleRetrySuperseded deleted the job because it went stale. ResourceRuleRetrySuperseded )
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the PostgreSQL-backed graph and reasoning store. It is safe for concurrent use.
func Open ¶
Open connects to PostgreSQL and applies pending embedded migrations. The compiler must be built from a registry containing every identity scheme that stored assertions use, because startup may rebuild the materialized view.
func (*Store) ActivateDetectorRuleset ¶
func (s *Store) ActivateDetectorRuleset(ctx context.Context, id string, expectedRevision uint64, actor string) (uint64, error)
ActivateDetectorRuleset makes ruleset id active as revision expectedRevision+1. It is a compare-and-set: if the current activation revision is not expectedRevision it returns detector.ErrActivationConflict. Every activation is kept as an audit row, so rollback is activating an older ruleset again.
func (*Store) AdmitInvestigationJob ¶
func (s *Store) AdmitInvestigationJob(ctx context.Context, jobID int64, workerID string, admission InvestigationAdmission) (string, error)
AdmitInvestigationJob atomically applies deduplication and the hourly budget to a claimed job. Admitted jobs keep their admission across retries.
func (*Store) AdvanceReasoningCursor ¶
func (s *Store) AdvanceReasoningCursor(ctx context.Context, cursor ReasoningCursor) error
AdvanceReasoningCursor moves a consumer's cursor forward. Writing the same sequence and revision again is a no-op; moving backwards, or reusing a sequence with a different revision, is an error. A per-consumer advisory lock makes concurrent first writes for one consumer safe. Callers should advance only after durably recording what they did with the range.
func (*Store) ApplyContributionDelta ¶
func (s *Store) ApplyContributionDelta(ctx context.Context, delta ContributionDelta) (Publication, error)
func (*Store) ClaimInvestigationJob ¶
func (s *Store) ClaimInvestigationJob(ctx context.Context, workerID string, lease time.Duration) (InvestigationJob, bool, error)
ClaimInvestigationJob leases the highest-risk available job, oldest first, or a running job whose lease expired.
AttemptCount counts failed attempts, and an expired lease is one: the previous worker is presumed to have crashed. Reclaiming an expired job increments it, and an expired job that would reach the store's maximum attempts is failed instead, so a job that crashes every worker cannot stay at the head of the queue forever.
func (*Store) ClaimResourceRuleJob ¶
func (s *Store) ClaimResourceRuleJob(ctx context.Context, workerID string, leaseInterval, minAge time.Duration) (ResourceRuleJob, bool, error)
ClaimResourceRuleJob leases the oldest available job to workerID. Queued and retryable jobs past available_at are eligible once they are minAge old (the stabilization window) or were requested by an operator, as are running jobs whose lease expired (the previous worker is presumed dead). Eligible jobs that went stale (see [staleResourceRuleJob]) are deleted first, so no model call is spent on them. SKIP LOCKED lets concurrent workers claim different jobs. It returns false when nothing is available.
func (*Store) CompleteInvestigationJob ¶
func (s *Store) CompleteInvestigationJob(ctx context.Context, jobID int64, workerID string, outcome json.RawMessage) error
CompleteInvestigationJob records the outcome of an investigated job.
func (*Store) CompleteResourceRuleJob ¶
func (s *Store) CompleteResourceRuleJob(ctx context.Context, jobID int64, workerID string, proposal json.RawMessage) error
CompleteResourceRuleJob stores the proposal and completes the job. It fails if workerID no longer holds the lease, so a worker whose lease expired cannot overwrite the result of the worker that reclaimed it.
func (*Store) ContributionGeneration ¶
func (s *Store) ContributionGeneration(ctx context.Context, pluginID, sourceID string) (uint64, error)
ContributionGeneration returns the highest durable generation across all named contributions of (plugin, source), or zero. Plugins call it at startup and publish from the next value, which keeps generations monotonic across restarts without a per-process counter.
func (*Store) CreateAnalysisView ¶
func (s *Store) CreateAnalysisView(ctx context.Context, evaluationTime time.Time) (AnalysisViewToken, GraphManifest, error)
CreateAnalysisView pins the current manifest with an evaluation time. A zero evaluationTime means now.
func (*Store) CreateManifest ¶
func (s *Store) CreateManifest(ctx context.Context) (GraphManifest, error)
CreateManifest records the active version of every non-retired contribution. The manifest ID is derived from the version vector and status counts, so calling it again with no intervening publication returns the existing manifest instead of creating a new one.
func (*Store) CurrentGraph ¶
CurrentGraph returns the revision-validated materialized graph for consumers that intentionally need the complete graph.
func (*Store) EnqueueInvestigationJob ¶
func (s *Store) EnqueueInvestigationJob(ctx context.Context, record InvestigationJobRecord, batchWindow time.Duration, merge func(existing InvestigationJobRecord) (InvestigationJobRecord, bool, error)) (int64, bool, error)
EnqueueInvestigationJob coalesces record into the oldest queued, unclaimed job that shares an anchor and whose combined change range stays within MaxInvestigationJobSpan, when merge accepts it. Otherwise it inserts a new job available after batchWindow.
func (*Store) EnsureDefaultDetectorRuleset ¶
EnsureDefaultDetectorRuleset saves and activates the built-in ruleset when nothing is active. Losing the activation race to another process is not an error.
func (*Store) GetFinding ¶
GetFinding returns one finding or ErrFindingNotFound.
func (*Store) GetRelationshipDetail ¶
func (*Store) GetResourceDetail ¶
func (*Store) GraphRevision ¶
GraphRevision returns the compare-and-swap revision of the materialized graph.
func (*Store) InvalidateFindings ¶
func (s *Store) InvalidateFindings(ctx context.Context, graphRevision uint64, throughSequence uint64, affectedEntityIDs []string, invalidatedAt time.Time) error
InvalidateFindings marks active agentic investigation findings grounded in a revision other than graphRevision as invalidated by throughSequence. A nil affectedEntityIDs invalidates all of them (used on a rebase where change history is unavailable); a non-nil empty slice invalidates none; otherwise only findings touching one of the IDs, or recording no affected entities, are invalidated. Findings already grounded in graphRevision are left alone, which keeps repeated evaluation idempotent. Detection rule findings record that a rule matched and are never invalidated.
func (*Store) ListDetectionSignals ¶
func (s *Store) ListDetectionSignals(ctx context.Context, query DetectionSignalQuery) ([]DetectionSignal, error)
ListDetectionSignals returns the most recently recorded signals first.
func (*Store) ListInvestigationJobs ¶
func (s *Store) ListInvestigationJobs(ctx context.Context, limit int) ([]InvestigationJobSummary, error)
ListInvestigationJobs returns the newest jobs first.
func (*Store) ListResourceRuleJobs ¶
func (s *Store) ListResourceRuleJobs(ctx context.Context, limit int, resourceID string) ([]ResourceRuleJobSummary, error)
ListResourceRuleJobs returns up to limit (1-1000) jobs, current revisions first and then newest first. A non-empty resourceID restricts the result.
func (*Store) Neighborhood ¶
func (s *Store) Neighborhood(ctx context.Context, resourceID string, depth int, direction string, limit int) (Neighborhood, error)
Neighborhood returns resolved edges reachable from resourceID within depth hops (1-3) in the given direction ("outgoing", "incoming", or "both"), stopping at limit edges (default and maximum 500). It filters the full compiled graph rather than querying projections.
func (*Store) NormalizeIdentityClaim ¶
func (s *Store) NormalizeIdentityClaim(claim graph.IdentityClaim) (graph.IdentityClaim, error)
func (*Store) PruneDetectionSignals ¶
PruneDetectionSignals deletes signals recorded before the cutoff.
func (*Store) PruneInvestigationJobs ¶
PruneInvestigationJobs deletes terminal jobs that finished before the cutoff.
func (*Store) PutFinding ¶
PutFinding inserts a finding keyed by its deterministic ID. Re-putting the same content is a no-op, so a reasoning evaluation repeated after a crash is harmless; different content under an existing ID is an error. CreatedAt is ignored when comparing.
func (*Store) QueryFindings ¶
func (s *Store) QueryFindings(ctx context.Context, query FindingQuery) (FindingPage, error)
QueryFindings returns findings newest first.
func (*Store) QueryRelationships ¶
func (s *Store) QueryRelationships(ctx context.Context, query RelationshipQuery) (RelationshipPage, error)
func (*Store) QueryResources ¶
func (s *Store) QueryResources(ctx context.Context, query ResourceQuery) (ResourcePage, error)
func (*Store) ReadActiveDetectorRuleset ¶
ReadActiveDetectorRuleset loads the currently activated ruleset and its activation revision, or detector.ErrNoActiveRuleset.
func (*Store) ReadContributionChanges ¶
func (s *Store) ReadContributionChanges(ctx context.Context, afterSequence uint64, limit int) ([]ContributionChangeEvent, error)
ReadContributionChanges returns up to limit (1-1000) outbox events with a sequence greater than afterSequence, in sequence order.
func (*Store) ReadDetectorRuleset ¶
ReadDetectorRuleset loads a stored ruleset and verifies its checksum.
func (*Store) ReadGraphCheckpoint ¶
func (s *Store) ReadGraphCheckpoint(ctx context.Context) (GraphCheckpoint, error)
ReadGraphCheckpoint returns the latest outbox sequence and the graph compiled from the same snapshot, so a reasoning consumer can start or recover at a point where feed position and graph agree. The graph may include telemetry rollups newer than the sequence, because telemetry-only publications do not advance it.
func (*Store) ReadReasoningCursor ¶
func (s *Store) ReadReasoningCursor(ctx context.Context, consumerID string) (ReasoningCursor, bool, error)
ReadReasoningCursor returns the stored cursor for consumerID and whether one exists.
func (*Store) ReadResourceRules ¶
ReadResourceRules returns every rule from completed, non-rejected resource proposals whose resource is still in the graph. Approved rules are active; unreviewed drafts run in shadow mode.
func (*Store) ReadResourceRulesForDetector ¶
ReadResourceRulesForDetector returns active rules before shadow rules and stops after the detector's capacity plus one overflow rule.
func (*Store) RecordDetectionSignals ¶
func (s *Store) RecordDetectionSignals(ctx context.Context, signals []DetectionSignal) error
RecordDetectionSignals stores signals idempotently; a retried window does not duplicate rows.
func (*Store) RecordNative ¶
func (s *Store) RecordNative(ctx context.Context, event NativeEvent) error
RecordNative stores a provider observation idempotently by EventID. The content digest covers provenance, collection, key, revision, operation, and normalized payload but not ObservedAt, so a redelivery observed later is still the same event.
func (*Store) RenewInvestigationJob ¶
func (*Store) RenewResourceRuleJob ¶
func (s *Store) RenewResourceRuleJob(ctx context.Context, jobID int64, workerID string, leaseInterval time.Duration) (bool, error)
RenewResourceRuleJob extends a lease still held by workerID and reports whether it was.
func (*Store) ReplaceContribution ¶
func (s *Store) ReplaceContribution(ctx context.Context, contribution Contribution) (Publication, error)
ReplaceContribution publishes contribution as the complete current output of its (plugin, source, name) tuple. Replacement semantics: any assertion the tuple owned before and that is absent now is retracted, so a plugin removes a fact by omitting it, never by sending a delete. Assertions owned by other contributions are untouched even when they describe the same entities.
Validation and compilation happen before the transaction so malformed input never enters the commit path. Assertion provenance must match the contribution owner; it is rejected, not rewritten.
func (*Store) RequestResourceRuleJob ¶
func (s *Store) RequestResourceRuleJob(ctx context.Context, resourceID, actor string) (ResourceRuleJobSummary, error)
RequestResourceRuleJob asks for the resource's current authoring context to be authored now. A queued or retrying job is woken: it skips the stabilization wait and any retry backoff. A completed job is reset to queued, dropping its proposal and review, so the next proposal starts in shadow mode; a previously approved draft's rules stop running actively until the new draft is approved. It returns ErrResourceRuleJobInProgress with the job while a worker is authoring it, and ErrResourceRuleJobNotFound when the resource has no job for its current revision. actor is audit metadata, not authorization.
func (*Store) ResourceRuleJobStatus ¶
func (s *Store) ResourceRuleJobStatus(ctx context.Context, jobID int64) (ResourceRuleJobSummary, bool, error)
ResourceRuleJobStatus returns one job's summary and whether it exists.
func (*Store) ResourceRuleProposal ¶
func (s *Store) ResourceRuleProposal(ctx context.Context, jobID int64) (json.RawMessage, bool, error)
ResourceRuleProposal returns a completed job's proposal and whether the job exists and is completed.
func (*Store) ResourceRuleQueueStats ¶
func (s *Store) ResourceRuleQueueStats(ctx context.Context, minAge time.Duration) (ResourceRuleQueueStats, error)
ResourceRuleQueueStats reports the authoring queue for a worker that waits minAge (the stabilization window) before claiming unrequested jobs.
func (*Store) RetireContribution ¶
func (s *Store) RetireContribution(ctx context.Context, pluginID, sourceID, name string, generation uint64, observedAt time.Time) (Publication, error)
RetireContribution publishes an empty terminal generation, retracting every active assertion of the tuple and marking its head retired. generation must be newer than the current one.
func (*Store) RetryInvestigationJob ¶
func (s *Store) RetryInvestigationJob(ctx context.Context, jobID int64, workerID, failure string, retryAfter time.Duration, terminal bool) error
RetryInvestigationJob records a failed attempt. A terminal failure ends the job.
func (*Store) RetryResourceRuleJob ¶
func (s *Store) RetryResourceRuleJob(ctx context.Context, jobID int64, workerID, failure string, retryAfter time.Duration, terminal bool) (ResourceRuleRetry, error)
RetryResourceRuleJob releases a held lease after a failed attempt. A job that went stale is deleted, whatever terminal says. Otherwise a terminal failure ends the job as failed, and any other failure makes it available again after retryAfter, clamped to 1s-24h. failure is truncated to 2 KiB.
func (*Store) ReviewResourceRuleJobRules ¶
func (*Store) SaveDetectorRuleset ¶
func (s *Store) SaveDetectorRuleset(ctx context.Context, ruleset detector.Ruleset, actor string) error
SaveDetectorRuleset stores a validated ruleset and its rule revisions. Rulesets and rule revisions are immutable: saving identical content again is a no-op and different content under an existing ID or revision fails. Saving does not activate.
func (*Store) SkipInvestigationJob ¶
func (s *Store) SkipInvestigationJob(ctx context.Context, jobID int64, workerID, reason string) error
SkipInvestigationJob ends a claimed job without investigating it.
func (*Store) WorkloadObservedBehavior ¶
func (s *Store) WorkloadObservedBehavior(ctx context.Context, resourceID string) (WorkloadBehavior, error)
WorkloadObservedBehavior summarizes the current graph's telemetry for a supported workload controller; see WorkloadBehaviorFor.
type WorkloadBehavior ¶
type WorkloadBehavior struct {
// CollectedTelemetry lists the telemetry kinds observed anywhere in the
// graph, so an empty Requests list can be told apart from telemetry that is
// not collected at all.
CollectedTelemetry []string `json:"collectedTelemetry"`
Requests []ObservedRequest `json:"requests"`
// Truncated reports that more distinct requests were observed than
// MaxObservedRequests; the most frequent are kept.
Truncated bool `json:"truncated,omitempty"`
}
WorkloadBehavior summarizes the telemetry whose subject is one workload or a Pod instantiated by it. Operations are normalized by NormalizeObservedOperation.
func WorkloadBehaviorFor ¶
func WorkloadBehaviorFor(snapshot graph.Snapshot, resourceID string) WorkloadBehavior
WorkloadBehaviorFor summarizes the telemetry in snapshot whose subject is the resource. The result is deterministic for a given snapshot.