intentpolicy

package
v0.0.0-...-38ed774 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0 modules, 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 intentpolicy assesses recorded tool calls against a fixed intent guardrail. An evaluator infers labels about one call, then CEL contracts over those labels decide permit, clarify, or block. Each call is assessed on its own: no state carries between calls and nothing is enforced or persisted.

Index

Constants

View Source
const (
	LabelEffectClass              = "effect_class"
	LabelCarriesSecret            = "carries_secret"
	LabelExecutesRemoteCodeInline = "executes_remote_code_inline"
	LabelTouchesCredentialStore   = "touches_credential_store"
	LabelTouchesPersistence       = "touches_persistence"
	LabelHistoryRewrite           = "history_rewrite"
	LabelEffectCoverage           = "effect_coverage"
	LabelCarriesPersonalData      = "carries_personal_data"
	LabelDestructiveTarget        = "destructive_target"
	LabelPublishesArtifact        = "publishes_artifact"
)

Label keys exposed to contracts.

View Source
const (
	EffectRead        = "read"
	EffectWriteLocal  = "write_local"
	EffectOutbound    = "outbound"
	EffectDestructive = "destructive"
	EffectExecTask    = "exec_task"
	EffectExecProgram = "exec_program"
)

Effect classes of the effect_class label.

View Source
const (
	TargetNone      = "none"
	TargetScratch   = "scratch"
	TargetWorkspace = "workspace"
	TargetShared    = "shared"
	TargetUnknown   = "unknown"
)

Values of the destructive_target label.

View Source
const (
	CoverageUnderstood          = "understood"
	CoveragePartiallyUnderstood = "partially_understood"
	CoverageUnknown             = "unknown"
)

Values of the effect_coverage label.

View Source
const (
	// SourceUpload marks messages of a transcript uploaded on the analysis page.
	SourceUpload = "intent-policies-upload"

	// SourceImport marks messages written by the local eval-set import.
	SourceImport = "intent-policies-import"

	// MaxTranscriptBytes caps one transcript. The largest eval-set transcripts
	// are a few MB; 20 MB leaves room for long real sessions.
	MaxTranscriptBytes = 20 << 20 // 20 MiB
)
View Source
const (
	OpIs                = "is"
	OpIsNot             = "is not"
	OpIncludes          = "includes"
	OpIncludesOtherThan = "includes anything other than"
)

Condition operators.

View Source
const ErrorMissingLabel = "evaluator did not answer: "

ErrorMissingLabel prefixes the outcome error of a contract that reads a label the evaluator did not answer.

View Source
const Framing = `` /* 852-byte string literal not displayed */

Framing is the untrusted-data instruction shared by both evaluators.

View Source
const (
	// GeminiModel is the non-lite flash of the Gemini generation the risk
	// judges run, for stronger labels on a staff-only replay path.
	GeminiModel = "google/gemini-3.5-flash"
)
View Source
const GuardrailID = "intent-baseline"

GuardrailID identifies the built-in intent guardrail.

View Source
const GuardrailVersion = "2026-11-24.1"

GuardrailVersion changes whenever statements, questions, or contracts change.

View Source
const JevModel = "jev-1.13"

JevModel pins the System One model so labels stay comparable across runs.

View Source
const (
	// MaxActions caps one session analysis, matching the guardrail replay cap.
	MaxActions = 200
)

Variables

View Source
var ErrEmptyTranscript = errors.New("transcript has no messages")

ErrEmptyTranscript means the transcript holds no conversational messages.

Functions

func CompileJevRequest

func CompileJevRequest(in LabelInput) (*classifier.Request, error)

CompileJevRequest compiles one call's label questions into a classifier batch.

func GeminiSchema

func GeminiSchema(qs []LabelQuestion) map[string]any

GeminiSchema mirrors the label set: one property per label.

func GeminiSystemPrompt

func GeminiSystemPrompt(qs []LabelQuestion) string

GeminiSystemPrompt renders the framing and every label question.

func RenderState

func RenderState(in LabelInput) ([]byte, error)

RenderState renders the byte-identical JSON state both evaluators receive.

func StoreTranscript

func StoreTranscript(ctx context.Context, db *pgxpool.Pool, writer *chat.ChatMessageWriter, p StoreParams, t Transcript, now time.Time) (uuid.UUID, error)

StoreTranscript writes the transcript as a new chat through the standard chat message writer and returns its id.

Types

type Action

type Action struct {
	// ChatID is the session the call belongs to.
	ChatID uuid.UUID

	// MessageID is the assistant message that carried the call.
	MessageID uuid.UUID

	// Seq is the carrying message's sequence number.
	Seq int64

	// Generation is the carrying message's chat generation.
	Generation int32

	// ToolCallID is the provider-assigned call id.
	ToolCallID string

	// Tool identifies the invoked tool.
	Tool ToolRef

	// Arguments is the argument payload exactly as recorded.
	Arguments json.RawMessage

	// Cwd is the session working directory, for resolving relative paths.
	Cwd string

	// OccurredAt is when the carrying message was recorded.
	OccurredAt time.Time
}

Action is one recorded tool call.

func ExtractActions

func ExtractActions(chatID uuid.UUID, cwd string, rows []MessageRow) ([]Action, error)

ExtractActions returns every tool call of the assistant messages, in message order and then call order. Malformed tool_calls JSON is reported, not skipped.

func Window

func Window(actions []Action, offset, limit int) []Action

Window returns the calls from offset, at most limit of them (limit <= 0 means no limit), never reaching past MaxActions. Callers analyze a long session in windows to report progress.

type Analysis

type Analysis struct {
	// Guardrail is the guardrail applied.
	Guardrail Guardrail

	// Descriptor identifies the evaluator.
	Descriptor Descriptor

	// Assessments holds one entry per judged call, in session order.
	Assessments []Assessment

	// Totals summarizes the assessments.
	Totals Totals

	// LimitHit reports that the session had more than MaxActions calls.
	LimitHit bool
}

Analysis is the assessment of a session's tool calls.

func Analyze

func Analyze(ctx context.Context, g Guardrail, engine *Engine, evaluator Evaluator, actions []Action, offset, limit int) (Analysis, error)

Analyze assesses the session's Window(offset, limit) with bounded concurrency; totals and LimitHit describe the whole session. Evaluator failures become fail-closed assessments rather than errors.

type Assessment

type Assessment struct {
	// Action is the assessed call.
	Action Action

	// Labels is what the evaluator inferred.
	Labels LabelSet

	// Decision is the combined contract decision.
	Decision Decision

	// DecidedBy lists the contracts that produced Decision.
	DecidedBy []string

	// Outcomes holds one entry per contract, in guardrail order.
	Outcomes []ContractOutcome

	// EvaluatorError is set on any evaluator error, including partial failures.
	EvaluatorError string

	// Usage is the evaluator cost for this call.
	Usage Usage

	// Descriptor identifies the evaluator.
	Descriptor Descriptor
}

Assessment is the full result for one call.

type Condition

type Condition struct {
	// Join links the clause to the previous one: "", "and", or "or". Clauses
	// joined by "or" form a group and groups are joined by "and", so
	// A or B and C reads as (A or B) and C.
	Join string

	// Label is the label key the clause reads.
	Label string

	// Op compares the label to Values.
	Op string

	// Values are the label values compared: "true" for a yes/no label, else
	// option keys. Several values read as "any of".
	Values []string

	// Pattern is the regular expression a shell command must match.
	Pattern string
}

Condition is one clause of a contract's firing condition. A label clause sets Label; a tool clause sets Pattern, matched against the shell command.

type Contract

type Contract struct {
	// ID is a stable identifier.
	ID string

	// Name is a short display name.
	Name string

	// Statement is the grounding statement this contract enforces.
	Statement string

	// Outcome is the decision the contract returns when it fires.
	Outcome Decision

	// Conditions describe when the contract fires, for display. Expression is
	// what runs; TestContractConditionsMatchExpressions keeps them in step.
	Conditions []Condition

	// Expression evaluates to PERMIT, CLARIFY, BLOCK, or ABSTAIN.
	Expression string
}

Contract is one CEL rule over labels and tool metadata.

type ContractOutcome

type ContractOutcome struct {
	// ContractID identifies the contract.
	ContractID string

	// Result is the contract's decision, or empty when it errored.
	Result Decision

	// Error is the evaluation error, when any.
	Error string

	// Inputs maps each label or tool path the contract reads to its value.
	Inputs map[string]any
}

ContractOutcome is one contract's result for one call.

type Decision

type Decision string

Decision is the outcome of contract evaluation.

const (
	// DecisionPermit allows the call.
	DecisionPermit Decision = "permit"

	// DecisionClarify asks a person before the call proceeds.
	DecisionClarify Decision = "clarify"

	// DecisionBlock stops the call.
	DecisionBlock Decision = "block"
)

func Combine

func Combine(outcomes []ContractOutcome) (Decision, []string)

Combine applies the fixed precedence over contract outcomes.

type Descriptor

type Descriptor struct {
	// Evaluator is the evaluator kind (jev or gemini).
	Evaluator string

	// Provider is the inference transport.
	Provider string

	// Model is the configured model id.
	Model string

	// PromptVersion identifies the question-to-prompt compilation rules.
	PromptVersion string
}

Descriptor identifies the evaluator that produced labels.

type Engine

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

Engine evaluates a guardrail's contracts.

func NewEngine

func NewEngine(g Guardrail) (*Engine, error)

NewEngine compiles every contract of the guardrail.

func (*Engine) Evaluate

func (e *Engine) Evaluate(action Action, labels LabelSet) (Decision, []string, []ContractOutcome)

Evaluate runs every contract against the call and its labels and applies precedence: any BLOCK or contract error blocks, then any CLARIFY, then any PERMIT, else the default PERMIT.

type Evaluator

type Evaluator interface {
	// Label answers the questions for one call. A partial LabelSet may be
	// returned alongside an error.
	Label(ctx context.Context, in LabelInput) (LabelSet, Usage, error)

	// Descriptor identifies the provider, model, and prompt version.
	Descriptor() Descriptor
}

Evaluator infers labels for one call.

type GeminiEvaluator

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

GeminiEvaluator labels calls with a Gemini model under a strict JSON schema.

func NewGeminiEvaluator

func NewGeminiEvaluator(client openrouter.CompletionClient, orgID, projectID, userID string) *GeminiEvaluator

NewGeminiEvaluator binds the completion client to the caller's tenant for key resolution and usage attribution.

func (*GeminiEvaluator) Descriptor

func (e *GeminiEvaluator) Descriptor() Descriptor

Descriptor identifies the Gemini evaluator.

func (*GeminiEvaluator) Label

Label runs one structured completion and maps it to labels.

type Guardrail

type Guardrail struct {
	// ID identifies the guardrail.
	ID string

	// Version changes whenever statements, questions, or contracts change.
	Version string

	// Statements ground the evaluator.
	Statements []string

	// Questions are the labels inferred for every call.
	Questions []LabelQuestion

	// Contracts decide over the labels.
	Contracts []Contract
}

Guardrail is the versioned set of statements, questions, and contracts.

func DefaultGuardrail

func DefaultGuardrail() Guardrail

DefaultGuardrail returns a copy of the built-in guardrail.

type JevEvaluator

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

JevEvaluator labels calls with a classifier.Classifier (Jev in production).

func NewJevEvaluator

func NewJevEvaluator(c classifier.Classifier) *JevEvaluator

NewJevEvaluator wraps a classifier configured for JevModel.

func (*JevEvaluator) Descriptor

func (e *JevEvaluator) Descriptor() Descriptor

Descriptor identifies the Jev evaluator, or reports it disabled when no key is configured.

func (*JevEvaluator) Label

func (e *JevEvaluator) Label(ctx context.Context, in LabelInput) (LabelSet, Usage, error)

Label runs one classifier call and folds its answers into labels.

type Kind

type Kind string

Kind is the shape of a label question.

const (
	// KindNoul is a yes/no question answered with a probability.
	KindNoul Kind = "noul"

	// KindMultiNoul is a set of independent yes/no members exposed as a list.
	KindMultiNoul Kind = "multi_noul"

	// KindChoice selects one option, optionally ordinal.
	KindChoice Kind = "choice"
)

type LabelInput

type LabelInput struct {
	// Action is the call under evaluation.
	Action Action

	// Grounding is the guardrail statements.
	Grounding []string

	// Questions are the labels to infer.
	Questions []LabelQuestion
}

LabelInput is everything an evaluator may see for one call.

type LabelQuestion

type LabelQuestion struct {
	// Key is the label name exposed to contracts as label.<key>.
	Key string

	// Kind is the question shape.
	Kind Kind

	// Instructions states the question for the evaluator.
	Instructions string

	// Options lists the values of a choice or multi-noul question.
	Options []Option
}

LabelQuestion is one label the evaluator answers about a call.

type LabelSet

type LabelSet map[string]LabelValue

LabelSet maps label keys to values. A missing key means the evaluator failed to answer that label.

func FoldJevAnswers

func FoldJevAnswers(qs []LabelQuestion, answers map[classifier.QuestionKey]*classifier.Answer) LabelSet

FoldJevAnswers maps classifier answers back to labels. A label whose answers are incomplete is omitted so the contracts reading it fail closed.

func ParseGeminiLabels

func ParseGeminiLabels(qs []LabelQuestion, raw []byte) (LabelSet, error)

ParseGeminiLabels validates the structured response. Labels with invalid values are omitted and reported so the contracts reading them fail closed.

type LabelValue

type LabelValue struct {
	// Value is a bool, string, or []string depending on the question kind.
	Value any

	// Rank is the ordinal of a choice value; -1 when categorical or uncertain.
	Rank int

	// Probability is the evaluator's probability for the selected value.
	Probability float64

	// Distribution holds per-option probabilities for choice and multi-noul labels.
	Distribution map[string]float64

	// Rationale is the evaluator's explanation, when it gives one.
	Rationale string
}

LabelValue is one inferred label.

type MessageRow

type MessageRow struct {
	// ID is the message id.
	ID uuid.UUID

	// Seq is the message sequence number.
	Seq int64

	// Generation is the message's chat generation.
	Generation int32

	// Role is the stored role.
	Role string

	// ToolCalls is the stored tool_calls JSON.
	ToolCalls []byte

	// CreatedAt is when the message was recorded.
	CreatedAt time.Time
}

MessageRow is the subset of a stored chat message needed to extract calls.

type Option

type Option struct {
	// Key is the value exposed to contracts.
	Key string

	// Description grounds the value for the evaluator.
	Description string

	// Ordinal orders the option for rank; higher is better understood.
	Ordinal int

	// Uncertain marks values whose rank is reported as -1.
	Uncertain bool
}

Option is one value of a choice or multi-noul question.

type StoreParams

type StoreParams struct {
	// ChatID is the chat to create; uuid.Nil generates one.
	ChatID uuid.UUID

	// ProjectID owns the chat.
	ProjectID uuid.UUID

	// OrganizationID owns the project.
	OrganizationID string

	// UserID is the Speakeasy user recorded as the chat author.
	UserID string

	// Title is the chat title.
	Title string

	// Source is stamped on every message.
	Source string
}

StoreParams identifies where a parsed transcript is written.

type ToolRef

type ToolRef struct {
	// Name is the raw tool name as recorded.
	Name string

	// MCPServer is the MCP server parsed from Name; empty for native tools.
	MCPServer string

	// MCPFunction is the MCP function parsed from Name; empty for native tools.
	MCPFunction string
}

ToolRef identifies the invoked tool.

type Totals

type Totals struct {
	// Calls is the number of tool calls in the session.
	Calls int

	// Judged is the number of calls assessed.
	Judged int

	// Blocked counts block decisions, including evaluator failures.
	Blocked int

	// Clarified counts clarify decisions.
	Clarified int

	// Permitted counts permit decisions.
	Permitted int

	// CostUSD sums evaluator cost.
	CostUSD float64

	// LatencyMs sums evaluator latency.
	LatencyMs int64
}

Totals summarizes one analysis.

type Transcript

type Transcript struct {
	// Format is the detected encoding.
	Format TranscriptFormat

	// Cwd is the recorded working directory, when present.
	Cwd string

	// Messages are in conversation order.
	Messages []TranscriptMessage

	// InvalidLines counts JSONL lines that were not valid JSON.
	InvalidLines int
}

Transcript is a parsed session.

func ParseTranscript

func ParseTranscript(raw []byte) (Transcript, error)

ParseTranscript detects the format and flattens the transcript into storable messages. Sidechain (subagent) records are skipped.

type TranscriptFormat

type TranscriptFormat string

TranscriptFormat names a supported transcript encoding.

const (
	// FormatMessages is a JSON document of Anthropic-style messages.
	FormatMessages TranscriptFormat = "messages"

	// FormatClaudeCode is Claude Code session JSONL.
	FormatClaudeCode TranscriptFormat = "claude-code"

	// FormatPi is Pi session JSONL.
	FormatPi TranscriptFormat = "pi"
)

type TranscriptMessage

type TranscriptMessage struct {
	// Role is user, assistant, or tool.
	Role string

	// Content is the message text or tool result text.
	Content string

	// ToolCalls holds an assistant message's calls.
	ToolCalls []TranscriptToolCall

	// ToolCallID links a tool result to its call.
	ToolCallID string

	// Timestamp is the recorded time, when the format carries one.
	Timestamp *time.Time
}

TranscriptMessage is one message ready to store.

type TranscriptToolCall

type TranscriptToolCall struct {
	// ID is the provider call id.
	ID string

	// Name is the raw tool name.
	Name string

	// Arguments is the argument object as JSON.
	Arguments json.RawMessage
}

TranscriptToolCall is one tool invocation in an assistant message.

type Usage

type Usage struct {
	// InputTokens is the provider-reported prompt token count.
	InputTokens int64

	// OutputTokens is the provider-reported completion token count.
	OutputTokens int64

	// CostUSD is the provider-reported cost; zero when unreported.
	CostUSD float64

	// LatencyMs is the wall-clock duration of the evaluator call.
	LatencyMs int64
}

Usage is the cost of one evaluator call.

Jump to

Keyboard shortcuts

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