reasoning

package
v0.0.1-rc.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 26 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package reasoning turns committed graph changes into signals and evidence-backed findings, in two independent stages: deterministic detection and agentic investigation.

The model is an advisory investigator. This package stays authoritative for which graph state is analyzed, what the model may see and retrieve, which references a response may cite, and whether a response becomes a finding.

Pipeline

Service.Run is detection. It consumes the contribution change outbox written by pkg/state, processes one window at a time, and never calls a model:

  1. ReadChangeWindow reads a contiguous batch of state.ContributionChangeEvent values after the durable cursor, plus the coherent state.GraphCheckpoint that contains them. A sequence gap, or a batch that does not reach the checkpoint, is never filled by inference: the window is marked as a rebase to the checkpoint instead.
  2. A detector.Detector compares the previous and current snapshots and emits neutral detector.InvestigationSignal values. The window's signals are split by origin: active rule matches, shadow rule matches, and built-in novelty signals.
  3. IncidentHistory accumulates bounded telemetry baselines and an ordered timeline across windows; IncidentContext is the pinned view of it.
  4. When a novelty signal is medium risk or higher, the window yields an InvestigationRequest: the change range, novelty signals, topology classification, and incident context scoped to the signals' anchors.
  5. The ResultSink values record the Evaluation: FindingSink stores RuleFindings and invalidates agentic findings grounded in a superseded graph revision, SignalSink records every signal, and InvestigationQueue enqueues the request, coalescing it with queued requests that share an anchor. Only then does the cursor advance.

InvestigationWorker is agentic investigation. It drains the queue independently, so a model failure retries a job instead of stopping detection:

  1. Claim the highest-risk job, drop anchors that left the graph, and apply the SamplingPolicy: deterministic rate sampling of medium risk, deduplication, and an hourly budget.
  2. Re-read the request's change range and build the canonical Packet against the current checkpoint. Its AnalysisID is the SHA-256 of its canonical encoding, so identical inputs analyze identically.
  3. An Analyzer (normally pkg/reasoning/modelanalyzer) runs AnalyzeCandidateWithTools. The model retrieves more context through the read-only MCP tools in pkg/reasoning/mcpserver, each answered by a ContextProvider pinned to the packet's AnalysisToken.
  4. ValidateClassification checks the response against the effective packet, with one tool-free repair turn. Promote then applies the stricter promotion gate.
  5. FindingSink.RecordInvestigation persists a promoted finding with hydrated remediation proposals, and the worker invalidates it at once if changes committed during the model call touched its entities.

Service.EvaluateWindow and Service.EvaluateWindowWithIncident run detection and then the same Investigator inline, for evaluation harnesses.

Remediation is not part of this pipeline. Reasoning may attach validated remediation.Suggestion values to a promoted finding, but it never selects a provider or plans, prepares, executes, or verifies an action; see pkg/remediation and pkg/api.

What reaches the model

The initial packet contains no telemetry facts, provider-native configuration, candidate paths, or fixture labels. Packet and context construction additionally:

  • replaces evidence IDs with opaque "evidence:sha256:" handles;
  • drops resource and facet attributes whose key suggests credentials (password, token, authorization, cookie, API or access key, private key) and bounds attribute and name counts and lengths;
  • forwards only an allowlist of telemetry properties; and
  • omits telemetry assertion changes from the trigger window.

Eval campaign expectations live in the evals scorer and are never supplied to the model. Graph strings are untrusted data; SystemPrompt says so, and validation never relies on the model having obeyed it.

Invariants

  • Every retrieval is pinned to one analysis ID and graph revision; a query with another token is rejected.
  • A candidate that relied on truncated retrieval is rejected, because absence cannot be inferred from a partial view.
  • Finding identity is a digest of the promoted signal IDs and graph revision, so replaying an evaluation is idempotent.
  • The cursor advances only after the sinks record the evaluation.
  • Detection never calls a model; rule findings never depend on one.

See https://agent-shield.dev/docs/architecture/change-feed-and-reasoning/ for the design and https://agent-shield.dev/docs/operations/configuration/ for runtime flags.

Index

Constants

View Source
const (
	RetrievalModelSelected = "model_selected"
	RetrievalDeterministic = "deterministic"
)

Retrieval modes. In model-selected mode the model chooses every MCP call. In deterministic mode the host first retrieves the behavior baseline, incident timeline, default graph path, and governance posture for the signal anchors, and the model may still call more tools.

View Source
const (
	// ValidationNotApplicable means no model request was made.
	ValidationNotApplicable = "not_applicable"
	// ValidationAccepted means the final response passed classification
	// validation; promotion may still reject it.
	ValidationAccepted = "accepted"
	// ValidationRejected means the response was invalid after the repair turn
	// or relied on truncated context.
	ValidationRejected = "rejected"
)

Validation outcomes recorded on AnalysisOutcome. These values are persisted; do not rename them.

View Source
const (
	TemplateSecurityNeighborhood = "security_neighborhood"
	TemplateTelemetryChain       = "telemetry_chain"
	TemplateGovernancePosture    = "governance_posture"
	TemplateGraphPath            = "graph_path"
	TemplateIncidentTimeline     = "incident_timeline"
	TemplateBehaviorBaseline     = "behavior_baseline"
)

Context templates accepted by ContextProvider.Query. Each MCP tool in pkg/reasoning/mcpserver maps to exactly one template.

View Source
const (
	// ClosureUntruncated means every match in the pinned graph view fit within
	// the query bounds. It does not establish source readiness, freshness,
	// observation coverage, or global graph completeness.
	ClosureUntruncated = "untruncated"
	// ClosureTruncated means at least one collection hit its bound. A candidate
	// that relied on a truncated result is rejected.
	ClosureTruncated = "truncated"
)

Context result closures.

View Source
const (
	InvestigationSkipStale   = "stale"
	InvestigationSkipSampled = "sampled"
)

Investigation job skip reasons decided by the worker; admission adds duplicate and budget.

View Source
const (
	// PromotionSuppressed means the packet never warranted a model request.
	PromotionSuppressed = "suppressed"
	// PromotionRejected means a model response did not pass the promotion gate.
	PromotionRejected = "rejected"
	// PromotionPromoted means the response became a finding.
	PromotionPromoted = "promoted"
)

Promotion statuses. These values are persisted in evaluation records and eval reports; do not rename them.

View Source
const (
	ReasonBaseline                   = "baseline"
	ReasonNoInvestigationSignal      = "no_investigation_signal"
	ReasonModelDidNotSelectCandidate = "model_did_not_select_candidate"
	ReasonNoveltyWithoutConsequence  = "novelty_without_security_consequence"
	ReasonCandidateValidationFailed  = "candidate_validation_failed"
	ReasonCandidateContextTruncated  = "candidate_context_truncated"
	ReasonNoEligibleCandidate        = "no_eligible_candidate_selected"
	ReasonEvidenceBackedSignal       = "evidence_backed_signal"
)

Promotion reasons, paired with a status in Promotion. These values are persisted; do not rename them.

View Source
const (
	// RebaseChangeWindowUnavailable means the outbox could not supply a
	// contiguous window ending at the checkpoint.
	RebaseChangeWindowUnavailable = "change_window_unavailable"
	// RebaseStartupWithoutHistory means the consumer started with no cursor,
	// or behind the checkpoint, and no historical snapshot to diff against.
	RebaseStartupWithoutHistory = "startup_without_historical_snapshot"
)

Rebase reasons recorded on Evaluation. These values are persisted; do not rename them.

View Source
const (
	// InvestigationInvestigated means the window was investigated inline (EvaluateWindow).
	InvestigationInvestigated = "investigated"
	// InvestigationQueued means the window's request was handed to the investigation queue.
	InvestigationQueued = "queued"
	// InvestigationBelowThreshold means no signal could support promotion, so no agent ran.
	InvestigationBelowThreshold = "below_threshold"
	// InvestigationDisabled means an eligible signal existed but agentic investigation is disabled.
	InvestigationDisabled = "disabled"
)

Investigation states for an evaluated change window.

View Source
const (
	DecisionNoFinding        = "no_finding"
	DecisionCandidateFinding = "candidate_finding"
	DecisionUnsupported      = "unsupported"
)

Assessment decisions. These values are part of the strict model response schema, eval campaign expectations, and persisted reports.

View Source
const (
	// CategoryNewObservedCommunication is novelty without a stated consequence;
	// [Promote] never promotes it.
	CategoryNewObservedCommunication = "new_observed_communication"
	CategoryBoundaryCrossing         = "boundary_crossing"
	CategoryLossOfGovernance         = "loss_of_governance"
	CategoryNewExposure              = "new_exposure"
	CategoryIdentityReuse            = "identity_reuse"
	CategoryPossibleLateralPath      = "possible_lateral_path"
	CategoryUnknownSecurityEffect    = "unknown_security_effect"
)

Assessment categories. These values are part of the strict model response schema and persisted findings.

View Source
const IncidentContextSchemaVersion = "agentshield.ai/incident-context/v1alpha1"

IncidentContextSchemaVersion identifies the IncidentContext encoding.

View Source
const InvestigationRequestSchemaVersion = "agentshield.ai/investigation-request/v1alpha1"
View Source
const Model = "gpt-6-astra"

Model is the default OpenAI Responses model for reasoning.

View Source
const SchemaVersion = "agentshield.ai/change-analysis/v1alpha1"

SchemaVersion identifies the packet encoding sent to the model.

Variables

View Source
var ErrLeaseLost = errors.New("job lease is no longer owned by this worker")

ErrLeaseLost means a job's lease is now owned by another worker.

View Source
var SystemPrompt string

SystemPrompt is the reasoning system prompt. It restates the evidence and promotion rules the host enforces so that a compliant response survives validation; enforcement never depends on the model following it.

Functions

func EncodePacket

func EncodePacket(packet Packet) ([]byte, error)

EncodePacket returns the canonical JSON encoding of packet.

func InvestigationEligible

func InvestigationEligible(signal detector.InvestigationSignal) bool

InvestigationEligible reports whether a signal can support promotion. Agentic investigation of a window without an eligible signal can never promote a finding.

func IsPermanentModelError

func IsPermanentModelError(err error) bool

IsPermanentModelError reports whether err contains a StatusError that retrying cannot fix.

func KeepLease

func KeepLease(ctx context.Context, lease time.Duration, renew func(context.Context) (bool, error)) error

KeepLease renews a job lease every third of lease until ctx ends, then returns nil. renew reports whether this worker still owns the lease. A lost lease returns ErrLeaseLost at once, because another worker may own the job. A failed renewal, such as a brief database outage, is tolerated while the lease would still be held at the next attempt; after that the last error is returned. The caller cancels its work when KeepLease returns an error.

func NewRemediationProposals

func NewRemediationProposals(outcome AnalysisOutcome) ([]remediation.Proposal, error)

NewRemediationProposals hydrates each validated suggestion on a promoted outcome into a canonical remediation.Proposal bound to the finding, analysis, graph revision, and target identity. It recomputes the promotion rather than trusting outcome.Promotion, so a tampered or stale outcome cannot mint proposals. Only evidence cited by both the suggestion and a qualifying candidate claim is carried onto the proposal.

func RuleFindings

func RuleFindings(evaluation Evaluation, createdAt time.Time) []state.Finding

RuleFindings turns the active rule signals of an evaluated window into findings, one per rule revision. An active rule is operator-approved or operator-activated, so its match is a finding without agentic investigation. Shadow and built-in novelty signals never produce rule findings.

func Validate

func Validate(packet Packet, response Response) error

Validate applies the grounded validation required for promotion: in addition to ValidateClassification, every candidate claim must cite at least one returned fact, and every fact it cites must be accompanied by one of that fact's own evidence handles. Signals alone and resource attributes alone cannot ground a candidate.

Remediation suggestions are checked in both modes: each must target one supplied, affected entity, be unique per (intent, target), and share an eligible selected signal, a fact implicating the target, and that fact's evidence with one candidate claim.

func ValidateClassification

func ValidateClassification(packet Packet, response Response) error

ValidateClassification verifies that a model response uses the closed vocabularies, stays within response bounds, and references only IDs supplied in packet. A candidate claim must cite a signal the assessment selected. It is the check that triggers the single repair turn; promotion applies the stricter grounding in Validate.

Types

type AnalysisConfig

type AnalysisConfig struct {
	Name          string `json:"name"`
	Compact       bool   `json:"compact"`
	RetrievalMode string `json:"retrievalMode,omitempty"`
}

AnalysisConfig selects how one analysis is run. Compact sends only resources touched by the changes or anchored by signals in the initial request and leaves the rest to MCP retrieval.

type AnalysisOutcome

type AnalysisOutcome struct {
	Config          AnalysisConfig  `json:"config"`
	Validation      string          `json:"validation"`
	ValidationError string          `json:"validationError,omitempty"`
	ModelResults    []ModelResult   `json:"-"`
	Retrievals      []ContextResult `json:"retrievals,omitempty"`
	InitialPacket   Packet          `json:"-"`
	EffectivePacket Packet          `json:"-"`
	Response        Response        `json:"response"`
	Promotion       Promotion       `json:"promotion"`
}

AnalysisOutcome is the auditable record of one analysis. InitialPacket is what the model first received; EffectivePacket adds every retrieved context result and is the packet validation and promotion are judged against.

func AnalyzeCandidate

func AnalyzeCandidate(ctx context.Context, client Client, full Packet, config AnalysisConfig) (AnalysisOutcome, error)

AnalyzeCandidate is AnalyzeCandidateWithTools without an MCP session. It only succeeds for packets that need no model request.

func AnalyzeCandidateWithTools

func AnalyzeCandidateWithTools(ctx context.Context, client Client, full Packet, config AnalysisConfig, session *mcp.ClientSession) (AnalysisOutcome, error)

AnalyzeCandidateWithTools runs one investigation of full over session.

Baseline and signal-free packets return ValidationNotApplicable without calling the model. Otherwise the model investigates until it returns a final response, and the outcome is decided in this order:

  1. A candidate that relied on any truncated retrieval is rejected with candidate_context_truncated. The model may infer absence of a control only from an untruncated view, and the host cannot tell which claims depended on the missing part.
  2. A response that fails ValidateClassification gets exactly one tool-free repair turn. The repair is limited to an allowlist of the signal, fact, and evidence IDs in the effective packet (the initial packet plus every MCP result), exactly the IDs validation accepts. The repaired response is validated from scratch, and the truncation rule is applied again.
  3. A response that is still invalid is rejected with candidate_validation_failed.
  4. Otherwise validation is ValidationAccepted and Promote decides.

Errors are returned only for transport, MCP, or decoding failures; policy rejections are recorded on the outcome.

func (AnalysisOutcome) Latency

func (outcome AnalysisOutcome) Latency() int64

Latency returns total model latency across every turn, in milliseconds.

func (AnalysisOutcome) Usage

func (outcome AnalysisOutcome) Usage() Usage

Usage sums token usage across every model turn, including the repair turn.

type AnalysisRun

type AnalysisRun struct {
	Outcome  AnalysisOutcome
	Attempts int
	Errors   []string
}

AnalysisRun is an Analyzer result. Errors holds failed attempts that preceded the returned outcome.

type AnalysisToken

type AnalysisToken struct {
	AnalysisID    string `json:"analysisId"`
	GraphRevision uint64 `json:"graphRevision"`
}

AnalysisToken pins retrieval to one analyzed packet and graph revision. A query carrying any other token is rejected, so the model cannot read a later or different graph state than the one it is being judged against.

type Analyzer

type Analyzer interface {
	Analyze(context.Context, Packet, *ContextProvider) (AnalysisRun, error)
}

Analyzer investigates one packet that has at least one signal. Policy rejections belong on the returned outcome; an error means the analysis could not be completed and stops the service.

type AnalyzerFunc

type AnalyzerFunc func(context.Context, Packet, *ContextProvider) (AnalysisRun, error)

AnalyzerFunc adapts a function to Analyzer.

func (AnalyzerFunc) Analyze

func (analyze AnalyzerFunc) Analyze(ctx context.Context, packet Packet, provider *ContextProvider) (AnalysisRun, error)

Analyze calls analyze.

type Assessment

type Assessment struct {
	Decision               string                   `json:"decision"`
	Category               string                   `json:"category"`
	Severity               string                   `json:"severity"`
	ModelUncertainty       string                   `json:"modelUncertainty"`
	Summary                string                   `json:"summary"`
	AffectedEntityIDs      []string                 `json:"affectedEntityIds"`
	Claims                 []Claim                  `json:"claims"`
	Uncertainties          []string                 `json:"uncertainties"`
	SignalIDs              []string                 `json:"signalIds"`
	RemediationSuggestions []remediation.Suggestion `json:"remediationSuggestions"`
}

Assessment is the model's classification of one packet. Every ID it cites must have been supplied in the effective packet; see Validate.

type BehaviorBaseline

type BehaviorBaseline struct {
	ID               string    `json:"id"`
	SubjectID        string    `json:"subjectId"`
	ObjectID         string    `json:"objectId"`
	Kind             string    `json:"kind"`
	Operation        string    `json:"operation,omitempty"`
	Outcome          string    `json:"outcome,omitempty"`
	Coverage         string    `json:"coverage,omitempty"`
	FirstObservedAt  time.Time `json:"firstObservedAt"`
	LastObservedAt   time.Time `json:"lastObservedAt"`
	ObservationCount uint64    `json:"observationCount"`
	WindowCount      uint64    `json:"windowCount"`
}

BehaviorBaseline aggregates observations of one (subject, object, kind, operation, outcome, coverage) combination. WindowCount is the number of observed snapshots that contained it, which separates steady behavior from a single burst.

type Change

type Change struct {
	Sequence      uint64              `json:"sequence"`
	Operation     string              `json:"operation"`
	AssertionType string              `json:"assertionType"`
	AssertionID   string              `json:"assertionId"`
	Entity        state.EntityLocator `json:"entity"`
}

Change is one non-telemetry assertion added or retracted in the trigger window.

type ChangeReader

type ChangeReader interface {
	ReadContributionChanges(context.Context, uint64, int) ([]state.ContributionChangeEvent, error)
	ReadGraphCheckpoint(context.Context) (state.GraphCheckpoint, error)
}

ChangeReader reads the contribution change outbox and a coherent graph checkpoint. *state.Store implements it.

type ChangeWindow

type ChangeWindow struct {
	Events         []state.ContributionChangeEvent
	Checkpoint     state.GraphCheckpoint
	RecoveredGap   bool
	PreviousCursor uint64
	NextCursor     uint64
}

ChangeWindow is one of: a contiguous batch of events ending exactly at Checkpoint.ThroughSequence; an empty window when nothing changed; or a rebase (RecoveredGap) with no events. NextCursor is the sequence a consumer records after handling the window.

func ReadChangeWindow

func ReadChangeWindow(ctx context.Context, reader ChangeReader, afterSequence uint64, limit int) (ChangeWindow, error)

ReadChangeWindow either returns one contiguous batch and its coherent current checkpoint, or explicitly rebases the cursor to a checkpoint after a gap.

The checkpoint is read first, and events past it are discarded, so the batch never describes changes the checkpoint does not contain. The window is a rebase when:

  • there are no readable events after afterSequence but the checkpoint is ahead, meaning the outbox no longer holds them;
  • the events are not contiguous from afterSequence+1, meaning some were pruned or are missing; or
  • the batch stops before the checkpoint, typically because limit was reached. Analyzing a prefix against a later checkpoint would attribute later state to earlier changes.

A rebase never infers which changes were missed. Callers analyze nothing for it and treat findings from older revisions as stale.

type Claim

type Claim struct {
	Mode          string   `json:"mode"`
	Text          string   `json:"text"`
	SupportingIDs []string `json:"supportingIds"`
}

Claim is one statement in an assessment. Mode records whether the model presents it as observed, configured, or its own inference; SupportingIDs must reference signals, facts, or evidence handles from the packet.

type Client

type Client struct {
	Endpoint        string
	APIKey          string
	Model           string
	ReasoningEffort string
	Provider        Provider
	// DryRun returns the first request body as a *[RequestPreviewError]
	// instead of sending it.
	DryRun     bool
	HTTPClient *http.Client
	// ValidateInput, if set, inspects every encoded model input before it is
	// sent and aborts the request on error.
	ValidateInput func([]byte) error
	// InvestigationLimits bounds the [Client.Investigate] tool loop; zero uses
	// [DefaultInvestigationToolLimits].
	InvestigationLimits StructuredToolLimits
}

Client calls an OpenAI Responses-compatible endpoint, or Anthropic's Messages API for structured authoring when Provider is ProviderAnthropic. Responses requests are sent with store=false. When ReasoningEffort is set, encrypted reasoning state is requested and replayed across turns.

func (Client) Analyze

func (client Client) Analyze(ctx context.Context, packet []byte) (ModelResult, error)

Analyze sends an encoded packet in a single tool-free turn.

func (Client) GenerateWithTools

func (client Client) GenerateWithTools(ctx context.Context, systemPrompt string, input json.RawMessage, tools []StructuredTool, limits StructuredToolLimits) (StructuredToolOutput, error)

GenerateWithTools runs a bounded, tool-only loop. Every turn must call a tool, and the run ends when the tool marked Final succeeds; its arguments are the result. No response format is requested, so the request prefix stays identical across turns. Budget violations (oversized arguments or results, unknown tools, an exhausted call budget) are returned to the model as tool errors rather than failing the request. Final calls do not consume MaxCalls, and the last turn forces the Final tool.

func (Client) Investigate

func (client Client) Investigate(ctx context.Context, packet Packet, session *mcp.ClientSession) (InvestigationResult, error)

Investigate runs the tool loop: each turn may call MCP tools from session, whose results are returned to the model and merged into the effective packet, until the model returns a final structured response. The loop is bounded by Client.InvestigationLimits: the last allowed turn offers no tool, so the model must answer, and calls or results over the budget are refused to the model rather than run or merged. Tool errors are returned to the model, not merged.

func (Client) Repair

func (client Client) Repair(ctx context.Context, packet Packet, previous Response, validationError string, allowedSupportingIDs []string) (ModelResult, error)

Repair asks for one corrected response after previous failed validation. The model sees the effective packet, its own invalid response, the validation error, and the IDs it may cite, and receives no tools.

type ContextLimits

type ContextLimits struct {
	Resources      int
	Relationships  int
	Facets         int
	Telemetry      int
	IncidentEvents int
	Baselines      int
	PathDepth      int
}

ContextLimits bounds each retrieval result. PathDepth is the maximum number of hops a graph-path query traverses.

func DefaultContextLimits

func DefaultContextLimits() ContextLimits

DefaultContextLimits returns the retrieval bounds used by the service.

type ContextProvider

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

ContextProvider answers context queries for one analysis from an immutable copy of the graph, pinned telemetry, and incident context. It never reads live state.

func NewContextProvider

func NewContextProvider(packet Packet, limits ContextLimits) (*ContextProvider, error)

NewContextProvider returns a provider limited to the packet's own resources, with no telemetry.

func NewContextProviderWithSnapshot

func NewContextProviderWithSnapshot(packet Packet, snapshot graph.Snapshot, pinned PinnedTelemetryContext, incident IncidentContext, limits ContextLimits) (*ContextProvider, error)

NewContextProviderWithSnapshot returns a provider over the complete snapshot, so retrieval can reach resources the bounded packet omitted. The telemetry context must carry the packet's token and window.

func NewContextProviderWithTelemetry

func NewContextProviderWithTelemetry(packet Packet, pinned PinnedTelemetryContext, limits ContextLimits) (*ContextProvider, error)

NewContextProviderWithTelemetry returns a provider limited to the packet's own resources plus pinned telemetry.

func (*ContextProvider) Query

func (provider *ContextProvider) Query(query ContextQuery) (ContextResult, error)

Query answers one template around the query anchors. Results are bounded per collection by the provider's limits. Graph-path queries use the supplied predicate allowlist, or every registered predicate except runs-on.

func (*ContextProvider) Token

func (provider *ContextProvider) Token() AnalysisToken

Token returns the analysis token every query to this provider must carry.

type ContextQuery

type ContextQuery struct {
	Token     AnalysisToken `json:"token"`
	Template  string        `json:"template"`
	AnchorIDs []string      `json:"anchorIds"`
	// Predicates is an explicit graph_path allowlist; an empty list uses the safe default.
	Predicates []graph.Predicate `json:"predicates,omitempty"`
}

ContextQuery requests one bounded context template around anchor resources. Anchors must be resources known to the provider.

type ContextReceipt

type ContextReceipt struct {
	Template   string            `json:"template"`
	AnchorIDs  []string          `json:"anchorIds"`
	Predicates []graph.Predicate `json:"predicates,omitempty"`
	Closure    string            `json:"closure"`
	Truncated  map[string]int    `json:"truncated,omitempty"`
}

ContextReceipt records one retrieval on the effective packet so the model, validation, and audit can see which anchors were covered and whether the view was truncated.

type ContextResult

type ContextResult struct {
	Token           AnalysisToken        `json:"token"`
	Template        string               `json:"template"`
	AnchorIDs       []string             `json:"anchorIds"`
	Predicates      []graph.Predicate    `json:"predicates,omitempty"`
	Resources       []Resource           `json:"resources"`
	Relationships   []Relationship       `json:"relationships"`
	Facets          []Facet              `json:"facets"`
	Telemetry       []Telemetry          `json:"telemetry"`
	IncidentEvents  []IncidentEvent      `json:"incidentEvents,omitempty"`
	Baselines       []BehaviorBaseline   `json:"baselines,omitempty"`
	TelemetryWindow *detector.TimeWindow `json:"telemetryWindow,omitempty"`
	Closure         string               `json:"closure"`
	Truncated       map[string]int       `json:"truncated,omitempty"`
}

ContextResult is the bounded answer to a ContextQuery. Truncated counts omitted items per collection, and Closure summarizes whether any were.

type CursorStore

type CursorStore interface {
	ChangeReader
	ReadReasoningCursor(context.Context, string) (state.ReasoningCursor, bool, error)
	AdvanceReasoningCursor(context.Context, state.ReasoningCursor) error
}

CursorStore is the durable state the service needs: the change outbox, graph checkpoints, and a per-consumer cursor. *state.Store implements it.

type Evaluation

type Evaluation struct {
	Window ChangeWindow
	// Signals are built-in novelty signals, the only input to agentic investigation.
	// RuleSignals come from active detection rules and become findings directly.
	// ShadowSignals come from unreviewed resource rules and are recorded only.
	Signals             []detector.InvestigationSignal
	RuleSignals         []detector.InvestigationSignal
	ShadowSignals       []detector.InvestigationSignal
	RulesetID           string
	RulesetDigest       string
	RulesetRevision     uint64
	ResourceRulesDigest string
	// Investigation describes agentic investigation of Signals; it is empty for windows
	// without detection (no events, rebase, baseline, or a detection failure).
	Investigation string
	// Request is the investigation request for a queued or inline-investigated window.
	Request *InvestigationRequest
	// Packet is built only for a window with an investigation-eligible signal.
	Packet       Packet
	Analysis     AnalysisRun
	Rebased      bool
	RebaseReason string
	// DetectionOmitted counts detector inputs and signals left out to stay
	// within the detector's bounds; see [detector.Result.Omitted].
	DetectionOmitted map[string]int
	// DetectionError is set when detection failed for this window. The window
	// carries no signals and is not investigated, but its changes still
	// invalidate stale findings and the cursor moves past it.
	DetectionError string
}

Evaluation is the complete result of processing one change window: the window, detector output and ruleset identity, the packet, the investigation state, and any inline analysis. A rebase evaluation carries only the window and RebaseReason.

type Facet

type Facet struct {
	ID                string                    `json:"id"`
	ResourceID        string                    `json:"resourceId"`
	Kind              string                    `json:"kind"`
	Key               string                    `json:"key,omitempty"`
	Attributes        map[string]string         `json:"attributes,omitempty"`
	SecuritySemantics []graph.SecuritySemantics `json:"securitySemantics,omitempty"`
	EvidenceIDs       []string                  `json:"evidenceIds,omitempty"`
}

Facet is a resolved graph facet with bounded attributes, decoded security semantics, and opaque evidence handles.

type FindingSink

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

FindingSink is the production ResultSink. It turns each recorded Evaluation into finding invalidations and at most one new finding.

func NewFindingSink

func NewFindingSink(store FindingStore, clock func() time.Time) (*FindingSink, error)

NewFindingSink returns a sink writing to store. A nil clock uses time.Now.

func (*FindingSink) RecordInvestigation

func (sink *FindingSink) RecordInvestigation(ctx context.Context, outcome AnalysisOutcome) (string, error)

RecordInvestigation persists the finding promoted by an agentic investigation and returns its ID, or an empty ID when the outcome did not promote a finding.

func (*FindingSink) RecordReasoningEvaluation

func (sink *FindingSink) RecordReasoningEvaluation(ctx context.Context, evaluation Evaluation) error

RecordReasoningEvaluation applies one evaluation in this order:

  1. A rebase invalidates every active finding grounded in a different graph digest, because the missed changes are unknown and any of them could have affected those findings.
  2. Otherwise, active findings from a different revision that name an entity touched by the window's changes are invalidated. Unrelated graph churn leaves findings active.
  3. A promoted, accepted outcome is persisted as an active finding with every hydrated remediation proposal, including a finding with none.

Invalidated findings remain stored for audit and cannot launch remediation. Finding IDs are deterministic, so recording the same evaluation again after a crash before the cursor advanced is idempotent.

type FindingStore

type FindingStore interface {
	PutFinding(context.Context, state.Finding) error
	InvalidateFindings(context.Context, uint64, uint64, []string, time.Time) error
}

FindingStore persists findings and invalidates stale ones. *state.Store implements it.

type IncidentContext

type IncidentContext struct {
	SchemaVersion string             `json:"schemaVersion"`
	IncidentID    string             `json:"incidentId"`
	EvaluationAt  time.Time          `json:"evaluationAt"`
	Baseline      []BehaviorBaseline `json:"baseline"`
	Timeline      []IncidentEvent    `json:"timeline"`
}

IncidentContext is the longitudinal context available to one analysis: a behavior baseline of previously observed communication and an ordered timeline of telemetry observations, each grouped under one incident ID. It is served only through the incident_timeline and behavior_baseline retrieval templates, never in the initial packet.

func NewIncidentContext

func NewIncidentContext(incidentID string, evaluationAt time.Time, baseline []BehaviorBaseline, timeline []IncidentEvent) (IncidentContext, error)

NewIncidentContext validates and canonicalizes incident context. Missing IDs are derived from content, and baselines and timeline events are sorted, so the same observations always produce the same context. Timeline events require evidence because they can ground a candidate claim.

type IncidentEvent

type IncidentEvent struct {
	ID          string            `json:"id"`
	Phase       string            `json:"phase"`
	ObservedAt  time.Time         `json:"observedAt"`
	Kind        string            `json:"kind"`
	SubjectID   string            `json:"subjectId"`
	ObjectID    string            `json:"objectId"`
	Operation   string            `json:"operation,omitempty"`
	Outcome     string            `json:"outcome,omitempty"`
	Coverage    string            `json:"coverage,omitempty"`
	Count       uint64            `json:"count"`
	Properties  map[string]string `json:"properties,omitempty"`
	EvidenceIDs []string          `json:"evidenceIds"`
}

IncidentEvent is one telemetry observation placed on the incident timeline. Phase names the evaluation window that first observed it.

type IncidentHistory

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

IncidentHistory accumulates incident context across evaluation windows of one Service. It is process-local: a restart starts a new history.

Grouping is deliberately coarse. The service uses its consumer ID as the incident ID, so every window it processes belongs to one incident and the model correlates phases by time, endpoints, and outcome rather than by a host-side clustering decision. Each telemetry event ID is added to the timeline once, under the phase that first observed it.

func NewIncidentHistory

func NewIncidentHistory(incidentID string) (*IncidentHistory, error)

NewIncidentHistory returns an empty history for incidentID.

func (*IncidentHistory) Context

func (history *IncidentHistory) Context(evaluationAt time.Time) (IncidentContext, error)

Context returns the current history as a canonical IncidentContext.

func (*IncidentHistory) ObserveBaseline

func (history *IncidentHistory) ObserveBaseline(snapshot graph.Snapshot)

ObserveBaseline folds the snapshot's telemetry into the behavior baseline. Telemetry without a first-seen time or evidence is ignored.

func (*IncidentHistory) ObservePhase

func (history *IncidentHistory) ObservePhase(phase string, snapshot graph.Snapshot)

ObservePhase appends telemetry not yet seen to the timeline under phase. Telemetry without a first-seen time or evidence is ignored.

type InvestigationJobStore

type InvestigationJobStore interface {
	ChangeReader
	FindingStore
	ClaimInvestigationJob(context.Context, string, time.Duration) (state.InvestigationJob, bool, error)
	AdmitInvestigationJob(context.Context, int64, string, state.InvestigationAdmission) (string, error)
	SkipInvestigationJob(context.Context, int64, string, string) error
	RenewInvestigationJob(context.Context, int64, string, time.Duration) (bool, error)
	CompleteInvestigationJob(context.Context, int64, string, json.RawMessage) error
	RetryInvestigationJob(context.Context, int64, string, string, time.Duration, bool) error
	PruneInvestigationJobs(context.Context, time.Time) (int64, error)
}

InvestigationJobStore is the durable investigation queue plus the graph and finding state an investigation reads and writes.

type InvestigationOutcome

type InvestigationOutcome struct {
	AnalysisID         string   `json:"analysisId"`
	HydratedAtSequence uint64   `json:"hydratedAtSequence"`
	Promotion          string   `json:"promotion"`
	Reason             string   `json:"reason"`
	FindingID          string   `json:"findingId,omitempty"`
	SignalIDs          []string `json:"signalIds"`
	Attempts           int      `json:"attempts"`
	Usage              Usage    `json:"usage"`
	LatencyMillis      int64    `json:"latencyMillis"`
}

InvestigationOutcome summarizes a completed job.

type InvestigationQueue

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

InvestigationQueue hands each queued window's request to the investigation worker. Requests that share an anchor coalesce while their batch window is open.

func NewInvestigationQueue

func NewInvestigationQueue(store InvestigationQueueStore, batchWindow time.Duration) (*InvestigationQueue, error)

func (*InvestigationQueue) RecordReasoningEvaluation

func (queue *InvestigationQueue) RecordReasoningEvaluation(ctx context.Context, evaluation Evaluation) error

type InvestigationQueueStore

type InvestigationQueueStore interface {
	EnqueueInvestigationJob(context.Context, state.InvestigationJobRecord, time.Duration, func(state.InvestigationJobRecord) (state.InvestigationJobRecord, bool, error)) (int64, bool, error)
}

InvestigationQueueStore persists investigation requests for the investigation worker.

type InvestigationRequest

type InvestigationRequest struct {
	SchemaVersion  string                         `json:"schemaVersion"`
	FirstSequence  uint64                         `json:"firstSequence"`
	LastSequence   uint64                         `json:"lastSequence"`
	TopologyChange string                         `json:"topologyChange"`
	Signals        []detector.InvestigationSignal `json:"signals"`
	Incident       IncidentContext                `json:"incident"`
	DetectedAt     time.Time                      `json:"detectedAt"`
}

InvestigationRequest is what agentic investigation needs from detection. It is self-contained so a separate worker can investigate it later against a newer graph.

func DecodeInvestigationRequest

func DecodeInvestigationRequest(encoded []byte) (InvestigationRequest, error)

DecodeInvestigationRequest decodes and checks a stored request.

func MergeInvestigationRequests

func MergeInvestigationRequests(existing, next InvestigationRequest) (InvestigationRequest, bool)

MergeInvestigationRequests batches next into existing. It declines when the combined change range exceeds one change-reader batch.

func NewInvestigationRequest

func NewInvestigationRequest(window ChangeWindow, topology string, signals []detector.InvestigationSignal, incident IncidentContext, detectedAt time.Time) (InvestigationRequest, error)

NewInvestigationRequest bounds a window's novelty signals and scopes the incident context to their anchors. It requires at least one eligible signal.

func (InvestigationRequest) Anchors

func (request InvestigationRequest) Anchors() []string

Anchors returns the sorted anchors of every signal in the request.

func (InvestigationRequest) Fingerprint

func (request InvestigationRequest) Fingerprint() string

Fingerprint identifies what the request is about, ignoring time windows and signal IDs, so a recurrence of the same pattern can be deduplicated.

func (InvestigationRequest) Record

Record returns the request's storage form.

func (InvestigationRequest) RetainPresentAnchors

func (request InvestigationRequest) RetainPresentAnchors(checkpoint state.GraphCheckpoint) InvestigationRequest

RetainPresentAnchors drops anchors that are no longer in the checkpoint's graph and signals left with none. A request with no remaining eligible signal is stale.

func (InvestigationRequest) Risk

func (request InvestigationRequest) Risk() detector.Risk

Risk returns the highest signal risk in the request.

func (InvestigationRequest) SampleKey

func (request InvestigationRequest) SampleKey() string

SampleKey identifies this occurrence, so sampling decisions are stable across retries but independent between recurrences of one pattern.

type InvestigationResult

type InvestigationResult struct {
	Response        Response
	ModelResults    []ModelResult
	ContextResults  []ContextResult
	EffectivePacket Packet
}

InvestigationResult is a completed tool-using investigation. EffectivePacket is the input packet merged with every successful MCP result.

type InvestigationRun

type InvestigationRun struct {
	Packet   Packet
	Analysis AnalysisRun
}

type InvestigationWorker

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

InvestigationWorker drains the investigation queue. A model failure retries the job with backoff and never blocks detection.

func NewInvestigationWorker

func NewInvestigationWorker(store InvestigationJobStore, investigator *Investigator, config InvestigationWorkerConfig) (*InvestigationWorker, error)

func (*InvestigationWorker) Process

func (worker *InvestigationWorker) Process(ctx context.Context, job state.InvestigationJob) error

Process handles one claimed job: staleness, sampling, admission, then investigation.

func (*InvestigationWorker) Run

func (worker *InvestigationWorker) Run(ctx context.Context)

Run polls until ctx is cancelled; failures are reported and retried.

type InvestigationWorkerConfig

type InvestigationWorkerConfig struct {
	ID            string
	PollInterval  time.Duration
	LeaseDuration time.Duration
	// MaxAttempts bounds failed investigations of one job before it fails permanently.
	MaxAttempts int
	// JobTimeout bounds one investigation attempt, including every model turn
	// and tool call; zero uses 15 minutes. A timed-out attempt is retried.
	JobTimeout time.Duration
	Sampling   SamplingPolicy
	// Retention prunes finished jobs; zero keeps them.
	Retention   time.Duration
	Clock       func() time.Time
	ReportError func(error)
}

type Investigator

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

Investigator runs agentic investigation of one request against a graph checkpoint.

func NewInvestigator

func NewInvestigator(analyzer Analyzer, packetLimits Limits, contextLimits ContextLimits) (*Investigator, error)

func (*Investigator) Investigate

func (investigator *Investigator) Investigate(ctx context.Context, request InvestigationRequest, events []state.ContributionChangeEvent, checkpoint state.GraphCheckpoint, evaluationTime time.Time) (InvestigationRun, error)

Investigate builds the packet from the request's change events and the given checkpoint, which may be newer than the window that produced the request.

type Limits

type Limits struct {
	Resources     int
	Relationships int
	Facets        int
	Telemetry     int
	Changes       int
}

Limits bounds each collection in an initial packet. Omitted counts are reported in Packet.Truncated. A zero Changes uses the default.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the packet bounds used by the service.

type ModelResult

type ModelResult struct {
	Response  Response
	Raw       []byte
	RequestID string
	Model     string
	Usage     Usage
	Latency   time.Duration
	Trace     ModelTrace
}

ModelResult is one model turn: the parsed response, the raw provider body for audit, and usage and latency.

type ModelToolCall

type ModelToolCall struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ModelToolCall is a tool invocation requested by the model.

type ModelTrace

type ModelTrace struct {
	Stage      string          `json:"stage"`
	ToolCalls  []ModelToolCall `json:"toolCalls,omitempty"`
	Assessment *Assessment     `json:"assessment,omitempty"`
}

ModelTrace records what a turn did: its stage (analysis, investigation, or repair), the tools it requested, or its final assessment.

type Packet

type Packet struct {
	SchemaVersion           string                         `json:"schemaVersion"`
	AnalysisID              string                         `json:"analysisId"`
	TriggerFirstSequence    uint64                         `json:"triggerFirstSequence"`
	TriggerLastSequence     uint64                         `json:"triggerLastSequence"`
	HydratedAtSequence      uint64                         `json:"hydratedAtSequence"`
	Baseline                bool                           `json:"baseline"`
	HydratedGraphRevision   uint64                         `json:"hydratedGraphRevision"`
	EvaluationTime          time.Time                      `json:"evaluationTime"`
	TopologyChange          string                         `json:"topologyChange"`
	AvailableContext        []string                       `json:"availableContext,omitempty"`
	ContextReceipts         []ContextReceipt               `json:"contextReceipts,omitempty"`
	SuggestedContextAnchors []string                       `json:"suggestedContextAnchors,omitempty"`
	TelemetryWindow         *detector.TimeWindow           `json:"telemetryWindow,omitempty"`
	Signals                 []detector.InvestigationSignal `json:"signals,omitempty"`
	Changes                 []Change                       `json:"changes"`
	Resources               []Resource                     `json:"resources"`
	Relationships           []Relationship                 `json:"relationships"`
	Facets                  []Facet                        `json:"facets"`
	Telemetry               []Telemetry                    `json:"telemetry"`
	IncidentEvents          []IncidentEvent                `json:"incidentEvents,omitempty"`
	Baselines               []BehaviorBaseline             `json:"baselines,omitempty"`
	Truncated               map[string]int                 `json:"truncated,omitempty"`
}

Packet is the canonical, model-facing description of one change window.

AnalysisID is the SHA-256 of the packet's canonical encoding without the ID, so the same events, checkpoint, signals, and evaluation time always produce the same ID. Together with HydratedGraphRevision and TelemetryWindow it pins later retrieval to the analyzed state.

Changes come from the trigger window; Resources come from the hydrated checkpoint, and Relationships and Facets are those touching the packet's resources, all bounded by Limits. Telemetry, IncidentEvents, and Baselines are empty in an initial packet and are filled only by MergeContext from retrieval results.

func BuildPacket

func BuildPacket(events []state.ContributionChangeEvent, checkpoint state.GraphCheckpoint, evaluationTime time.Time, limits Limits) (Packet, []byte, error)

BuildPacket builds a baseline packet: the window is treated as the reference state, so it is suppressed rather than analyzed.

func BuildPacketWithPrevious

func BuildPacketWithPrevious(events []state.ContributionChangeEvent, checkpoint state.GraphCheckpoint, previous graph.Snapshot, evaluationTime time.Time, limits Limits) (Packet, []byte, error)

BuildPacketWithPrevious builds a non-baseline packet without signals, which is suppressed before any model request.

func BuildPacketWithSignals

func BuildPacketWithSignals(events []state.ContributionChangeEvent, checkpoint state.GraphCheckpoint, previous *graph.Snapshot, baseline bool, signals []detector.InvestigationSignal, evaluationTime time.Time, limits Limits) (Packet, []byte, error)

BuildPacketWithSignals builds the packet for a window. events must be non-empty and contiguous by sequence. When the checkpoint exceeds the resource limit, resources anchored by a signal are kept first, then resources touched by a change; if they alone exceed the limit, the rest are left out and counted as truncated "requiredResources". It is an error if a signal anchor is absent from the checkpoint. The returned bytes are the canonical encoding including AnalysisID.

func CompactPacket

func CompactPacket(packet Packet) Packet

CompactPacket keeps only resources touched by the packet's changes or anchored by its signals, the relationships between them, and their facets. Everything else must be retrieved through MCP.

func MergeContext

func MergeContext(packet Packet, retrieved ContextResult) Packet

MergeContext adds a retrieval result to packet, deduplicating by ID and recording a ContextReceipt. Later results replace earlier items with the same ID; ordering is by ID so the merged packet is deterministic.

type PinnedTelemetryContext

type PinnedTelemetryContext struct {
	Token           AnalysisToken        `json:"token"`
	TelemetryWindow *detector.TimeWindow `json:"telemetryWindow,omitempty"`
	Telemetry       []Telemetry          `json:"telemetry"`
}

PinnedTelemetryContext is the telemetry available to retrieval for one analysis: events within the packet's telemetry window, already reduced to allowlisted properties and opaque evidence handles.

func PinSnapshotTelemetry

func PinSnapshotTelemetry(packet Packet, snapshot graph.Snapshot, limit int) PinnedTelemetryContext

PinSnapshotTelemetry selects up to limit telemetry events from snapshot that fall inside the packet's telemetry window. Events without a parseable first-seen time are skipped because they cannot be placed in the window.

type Promotion

type Promotion struct {
	Status       string                   `json:"status"`
	Reason       string                   `json:"reason"`
	FindingID    string                   `json:"findingId,omitempty"`
	SignalIDs    []string                 `json:"signalIds,omitempty"`
	Remediations []remediation.Suggestion `json:"remediations,omitempty"`
}

Promotion is the deterministic outcome of the gate between a model response and a finding. FindingID, SignalIDs, and Remediations are set only when Status is PromotionPromoted.

func Promote

func Promote(packet Packet, response Response) Promotion

Promote decides whether a response to packet becomes a finding. It is pure and is re-run by NewRemediationProposals to prove a stored outcome still matches its inputs.

Checks run cheapest and least model-dependent first, so the recorded reason names the earliest policy that excluded the candidate:

  • baseline: a baseline packet is the reference state, not a change.
  • no_investigation_signal: without a detector signal there is nothing the model may promote; this and baseline are suppression, not rejection, because no model request is needed.
  • model_did_not_select_candidate: the model returned no_finding or unsupported.
  • novelty_without_security_consequence: new communication alone is not a security finding; the model must name a more specific consequence.
  • candidate_validation_failed: after dropping remediation suggestions that do not validate on their own, the response fails grounded validation (every candidate claim cites a selected signal, a returned fact, and evidence linked to that fact).
  • no_eligible_candidate_selected: none of the selected signals is medium-or-higher risk. Low-risk telemetry novelty can inform an investigation but never promote one.

Invalid suggestions are dropped before validation so that one bad suggestion cannot discard an otherwise grounded finding.

type Provider

type Provider string

Provider selects the model API dialect.

const (
	ProviderOpenAI    Provider = "openai"
	ProviderAnthropic Provider = "anthropic"
)

Supported model API dialects. OpenAI is the default.

type Relationship

type Relationship struct {
	ID                string                    `json:"id"`
	SubjectID         string                    `json:"subjectId"`
	Predicate         graph.Predicate           `json:"predicate"`
	ObjectID          string                    `json:"objectId"`
	SecuritySemantics []graph.SecuritySemantics `json:"securitySemantics,omitempty"`
	EvidenceIDs       []string                  `json:"evidenceIds,omitempty"`
}

Relationship is a resolved graph relationship with its decoded security semantics and opaque evidence handles.

type RequestPreviewError

type RequestPreviewError struct {
	Body []byte
}

RequestPreviewError carries the request body captured by a Client with DryRun set. It never contains HTTP headers or credentials.

func (*RequestPreviewError) Error

func (preview *RequestPreviewError) Error() string

Error implements error.

type Resource

type Resource struct {
	ID         string              `json:"id"`
	Kind       string              `json:"kind"`
	Names      []string            `json:"names,omitempty"`
	Attributes map[string]string   `json:"attributes,omitempty"`
	Identity   graph.IdentityClaim `json:"identity,omitempty"`
}

Resource is a graph resource as shown to the model, with bounded descriptive attributes and names. Names and attributes are untrusted evidence, not authoritative classifications.

type Response

type Response struct {
	Assessment Assessment `json:"assessment"`
}

Response is the strict structured output requested from the model.

func DropInvalidRemediations

func DropInvalidRemediations(packet Packet, response Response) Response

DropInvalidRemediations removes remediation suggestions that would make an otherwise valid response invalid, keeping the rest in order. Suggestions are tried one at a time against the accumulated set, so a duplicate or ungrounded suggestion is dropped without discarding the finding. If the response is invalid even without suggestions, it is returned with none.

type ResultSink

type ResultSink interface {
	RecordReasoningEvaluation(context.Context, Evaluation) error
}

ResultSink records an evaluation before the service advances its cursor. It must be idempotent: the cursor and the sink are not committed atomically, so the same evaluation or finding can be recorded more than once.

func ResultSinks

func ResultSinks(sinks ...ResultSink) ResultSink

ResultSinks records an evaluation in each sink in order, stopping at the first error.

type ResultSinkFunc

type ResultSinkFunc func(context.Context, Evaluation) error

ResultSinkFunc adapts a function to ResultSink.

func (ResultSinkFunc) RecordReasoningEvaluation

func (record ResultSinkFunc) RecordReasoningEvaluation(ctx context.Context, evaluation Evaluation) error

RecordReasoningEvaluation calls record.

type SamplingPolicy

type SamplingPolicy struct {
	// SampleRate is the fraction of medium-risk requests investigated, from 0 to 1.
	SampleRate float64
	// MaxPerHour caps investigations started in any trailing hour; zero is unlimited.
	MaxPerHour int
	// DedupWindow skips a request whose fingerprint was investigated within the window; zero disables it.
	DedupWindow time.Duration
	// BudgetDeferral is how long an over-budget high or critical request waits before retrying.
	BudgetDeferral time.Duration
}

SamplingPolicy bounds agentic investigation spend. High and critical requests bypass rate sampling and wait, rather than drop, when the hourly budget is spent.

func DefaultSamplingPolicy

func DefaultSamplingPolicy() SamplingPolicy

func (SamplingPolicy) Sampled

func (policy SamplingPolicy) Sampled(request InvestigationRequest) bool

Sampled reports whether rate sampling keeps a request. The decision is a deterministic function of the request's sample key.

type Service

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

Service is the continuous reasoning consumer. It is not safe for concurrent use: incident history is updated in place by each evaluation.

func NewService

func NewService(store CursorStore, analyzer Analyzer, sink ResultSink, config ServiceConfig) (*Service, error)

NewService validates config and returns the detection service. analyzer is used only by the inline EvaluateWindow methods; Run never calls a model. sink may be nil to discard results.

func (*Service) EvaluateWindow

func (service *Service) EvaluateWindow(ctx context.Context, previous *graph.Snapshot, afterSequence uint64) (Evaluation, error)

EvaluateWindow evaluates the window after afterSequence against previous, the snapshot the cursor was last advanced to, using the service's own incident history, and investigates an eligible window inline with the service's analyzer through the same investigator as the queue worker. It does not record results or move the cursor.

func (*Service) EvaluateWindowWithIncident

func (service *Service) EvaluateWindowWithIncident(ctx context.Context, previous *graph.Snapshot, afterSequence uint64, incident IncidentContext) (Evaluation, error)

EvaluateWindowWithIncident is Service.EvaluateWindow with caller-supplied incident context instead of the service's history. Evals use it so they share every production stage after incident construction.

func (*Service) Run

func (service *Service) Run(ctx context.Context) (err error)

Run consumes the change outbox until ctx is cancelled, then returns nil.

Startup waits for the graph to materialize, then rebases to the current checkpoint if the cursor is missing or behind it. The state API cannot materialize an arbitrary historical snapshot, so changes made while the consumer was down cannot be diffed and are not claimed as analyzed.

Each poll evaluates at most one window. The sink records the evaluation before the cursor advances, so the cursor never claims a window whose results were not stored. Finding persistence and the cursor are not committed atomically: a crash in between leaves the cursor behind, the next start rebases, and deterministic finding IDs keep any re-recorded finding idempotent.

A detection failure confined to one window, such as a CEL runtime error, a packet that cannot be built, or a detector panic, does not stop the loop: the window is recorded with DetectionError and no signals, logged, and the cursor moves past it, so one bad window cannot stop detection. Rule matches in that window are lost, and the error says so.

A store, sink, or cursor error is returned and ends the loop. Run never calls a model: agentic investigation runs in InvestigationWorker, which retries its own failures, so a model outage cannot stop detection. A store error has no safe in-process recovery: retrying would repeat the failure indefinitely, and skipping would silently claim the window was recorded. Because the cursor has not advanced, the next start finds it behind the checkpoint and records an explicit rebase, which invalidates agentic findings from older revisions. The production command treats this error as fatal. A panic is returned as an error with its stack.

type ServiceConfig

type ServiceConfig struct {
	ConsumerID   string
	PollInterval time.Duration
	// ChangeLimit caps events per window, 1-1000. A backlog larger than this
	// rebases instead of being analyzed in pieces; see [ReadChangeWindow].
	ChangeLimit   int
	PacketLimits  Limits
	ContextLimits ContextLimits
	Detection     detector.Detector
	// QueueInvestigations makes Run attach an investigation request to each eligible
	// window for a queue sink; Run never calls a model itself.
	QueueInvestigations bool
	Clock               func() time.Time
}

ServiceConfig configures a Service. Zero fields take the defaults from DefaultServiceConfig; a nil Detection uses the built-in detector with the empty default ruleset.

func DefaultServiceConfig

func DefaultServiceConfig() ServiceConfig

DefaultServiceConfig returns the values NewService substitutes for zero ServiceConfig fields. The agentshield command starts from them.

type SignalSink

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

SignalSink records every signal of an evaluated window with its investigation outcome, so signals stay visible whether or not an agent investigated them.

func NewSignalSink

func NewSignalSink(store SignalStore, retention time.Duration, clock func() time.Time) (*SignalSink, error)

NewSignalSink keeps signals for retention; pruning runs at most hourly.

func (*SignalSink) RecordReasoningEvaluation

func (sink *SignalSink) RecordReasoningEvaluation(ctx context.Context, evaluation Evaluation) error

type SignalStore

type SignalStore interface {
	RecordDetectionSignals(context.Context, []state.DetectionSignal) error
	PruneDetectionSignals(context.Context, time.Time) (int64, error)
}

SignalStore persists detection signals.

type StatusError

type StatusError struct {
	StatusCode int
	Status     string
	Body       string
}

StatusError is a non-2xx response from the model endpoint.

func (*StatusError) Error

func (failure *StatusError) Error() string

Error implements error.

func (*StatusError) Permanent

func (failure *StatusError) Permanent() bool

Permanent reports whether repeating the request cannot succeed: a 4xx other than 408 (timeout) and 429 (rate limit), such as an invalid request or rejected credentials.

type StructuredTool

type StructuredTool struct {
	Name        string
	Description string
	InputSchema map[string]any
	Execute     func(context.Context, json.RawMessage) (json.RawMessage, error)
	// Final ends the run when the call succeeds; its arguments become the run's result.
	// Final calls do not consume MaxCalls.
	Final bool
}

StructuredTool is a host-executed function the model may call during Client.GenerateWithTools. Execute must return valid JSON; its error text is returned to the model, truncated.

type StructuredToolCall

type StructuredToolCall struct {
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
	Result    json.RawMessage `json:"result,omitempty"`
	Error     string          `json:"error,omitempty"`
}

StructuredToolCall records one tool call for audit, with its result or the error returned to the model.

type StructuredToolLimits

type StructuredToolLimits struct {
	MaxTurns            int
	MaxCalls            int
	MaxArgumentBytes    int
	MaxResultBytes      int
	MaxTotalResultBytes int
}

StructuredToolLimits bounds a structured tool loop. MaxTurns is 1-32, MaxCalls 0-32, argument and per-result bytes at most 64 KiB, and total result bytes at most 512 KiB.

func DefaultInvestigationToolLimits

func DefaultInvestigationToolLimits() StructuredToolLimits

DefaultInvestigationToolLimits bounds one investigation: 16 model turns, 32 MCP tool calls, 16 KiB of arguments per call, 256 KiB per tool result, and 1 MiB of tool results in total. Every turn replays the whole conversation, so the total result bound also bounds each request.

type StructuredToolOutput

type StructuredToolOutput struct {
	// FinalTool and FinalArguments identify the successful Final call that ended the run.
	FinalTool      string
	FinalArguments json.RawMessage
	Calls          []StructuredToolCall
}

StructuredToolOutput is the Final call that ended the run and every tool call made, in order.

type Telemetry

type Telemetry struct {
	ID          string            `json:"id"`
	Kind        string            `json:"kind"`
	SubjectID   string            `json:"subjectId"`
	ObjectID    string            `json:"objectId"`
	Operation   string            `json:"operation,omitempty"`
	Outcome     string            `json:"outcome,omitempty"`
	Coverage    string            `json:"coverage,omitempty"`
	Count       uint64            `json:"count"`
	Properties  map[string]string `json:"properties,omitempty"`
	EvidenceIDs []string          `json:"evidenceIds,omitempty"`
}

Telemetry is one retrieved telemetry rollup with allowlisted properties and opaque evidence handles.

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	ReasoningTokens  int `json:"reasoning_tokens,omitempty"`
	TotalTokens      int `json:"total_tokens"`
}

Usage is token usage reported by the model endpoint.

Directories

Path Synopsis
Package mcpserver exposes a reasoning reasoning.ContextProvider as read-only MCP tools for model-driven investigation.
Package mcpserver exposes a reasoning reasoning.ContextProvider as read-only MCP tools for model-driven investigation.
Package modelanalyzer is the production reasoning.Analyzer: it connects a model client to the read-only MCP tools for one pinned analysis and retries failed attempts.
Package modelanalyzer is the production reasoning.Analyzer: it connects a model client to the read-only MCP tools for one pinned analysis and retries failed attempts.

Jump to

Keyboard shortcuts

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