verification

package
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package verification defines result assurance independently of execution state.

Index

Constants

View Source
const (
	PrefixResult      id.Prefix = "vresult"
	PrefixCommitEvent id.Prefix = "vcommit"
)
View Source
const (
	PrefixContract id.Prefix = "vcontract"
	PrefixReport   id.Prefix = "vreport"
)
View Source
const (
	PrefixJob      id.Prefix = "vjob"
	PrefixJobClaim id.Prefix = "vclaim"
	MaxJobLease              = time.Hour
)
View Source
const MaxArtifactExportDuration = 30 * time.Second

MaxArtifactExportDuration bounds one attempt, including screening and delivery.

View Source
const MaxResultReadDuration = 5 * time.Second

MaxResultReadDuration bounds a read, including host authorization and screening. Host ports must honor context cancellation; the reader starts no background work.

View Source
const PrefixCall id.Prefix = "vcall"

PrefixCall identifies a durable evaluator dispatch.

View Source
const PrefixCaptureIntent id.Prefix = "vintent"

PrefixCaptureIntent identifies immutable pre-generation capture policy.

View Source
const PrefixExport id.Prefix = "vexport"

PrefixExport identifies a host-reserved artifact export operation.

Variables

View Source
var (
	ErrJobBudgetExceeded = cortex.ErrVerificationJobBudget
	ErrCallUncertain     = cortex.ErrVerificationCallUncertain
)

Error aliases preserve the shared Cortex sentinel identities.

View Source
var ErrCommitUnavailable = cortex.ErrResultCommitUnavailable

ErrCommitUnavailable means the backend cannot provide an atomic result commit.

View Source
var ErrExportUncertain = errors.New("cortex: artifact export outcome uncertain")

ErrExportUncertain means delivery may have occurred. Reconcile the same request.

View Source
var ErrResultAccessDenied = cortex.ErrResultAccessDenied

ErrResultAccessDenied means current content permission was refused.

Functions

func ReportObservationRefs

func ReportObservationRefs(r Report) ([]evidence.Ref, error)

ReportObservationRefs returns detached output evidence bound by the report digest. These refs are produced during evaluation, never added to its original input binding. Callers must hydrate them before treating the report as usable.

func ValidateReportForContract

func ValidateReportForContract(c Contract, r Report) error

ValidateReportForContract rejects outcomes from unknown criteria or verifier revisions. Partial reports are allowed; Aggregate handles missing checks.

func ValidateSandboxTestPlan

func ValidateSandboxTestPlan(plan SandboxTestPlan, m EvaluationManifest) error

ValidateSandboxTestPlan checks exact protected inputs and reserved job identities.

func ValidateSources

func ValidateSources(sources []Source) error

ValidateSources checks bounded, unique resource provenance.

Types

type ArtifactExportAuthorizer

type ArtifactExportAuthorizer interface {
	AuthorizeArtifactExport(context.Context, ArtifactExportRequest) error
}

ArtifactExportAuthorizer checks current actor, exact approval, source grants, destination permission and destination revision on every attempt, including retries.

type ArtifactExportFence

type ArtifactExportFence interface {
	WithArtifactExportFence(context.Context, ArtifactExportRequest, Binding, func(Binding) error) error
}

ArtifactExportFence holds grant, approval, destination, policy, evidence and run revision guards through the synchronous callback. All relevant writers must participate, including deletion and other processes. Remote services require conditional operations or a qualified observation window; there is no default.

type ArtifactExportReceipt

type ArtifactExportReceipt struct {
	SchemaVersion int    `json:"schema_version"`
	ID            id.ID  `json:"id"`
	RequestDigest string `json:"request_digest"`
	SHA256        string `json:"sha256"`
	Bytes         int64  `json:"bytes"`
}

ArtifactExportReceipt identifies a durable delivery, never a reusable grant.

func (ArtifactExportReceipt) Validate

Validate binds a delivery receipt to its exact request.

type ArtifactExportRequest

type ArtifactExportRequest struct {
	SchemaVersion       int                  `json:"schema_version"`
	ID                  id.ID                `json:"id"`
	Result              ResultContentRequest `json:"result"`
	Artifact            evidence.Ref         `json:"artifact"`
	Actor               string               `json:"actor"`
	ApprovalRef         string               `json:"approval_ref"`
	Destination         string               `json:"destination"`
	DestinationRevision string               `json:"destination_revision"`
}

ArtifactExportRequest pins the artifact, current approval and logical target. Destination is a host-registered identity, never a path or URL to resolve here. The host must durably reserve ID before dispatch and authenticate Actor.

func (ArtifactExportRequest) Freeze

Freeze validates and detaches one exact export request.

type ArtifactExportScreenRequest

type ArtifactExportScreenRequest struct {
	Request ArtifactExportRequest
	Binding Binding
	Data    []byte
}

ArtifactExportScreenRequest contains private bytes and trusted identity.

type ArtifactExportScreenResult

type ArtifactExportScreenResult struct {
	Approved bool
	SHA256   string
}

ArtifactExportScreenResult approves only the exact digest; rewriting is not export.

type ArtifactExportScreener

type ArtifactExportScreener interface {
	ScreenArtifactExport(context.Context, ArtifactExportScreenRequest) (ArtifactExportScreenResult, error)
}

ArtifactExportScreener applies current content policy to the complete bytes. Binary content requires a capable media-specific checker. Errors deny export.

type ArtifactExportSink

type ArtifactExportSink interface {
	ExportArtifact(context.Context, ArtifactExportRequest, []byte) (ArtifactExportReceipt, error)
}

ArtifactExportSink durably binds an operation ID to its full request before writing. Identical retries must verify the same delivery; changed requests must conflict across destinations. It must enforce destination path policy, honor cancellation and retain recovery evidence. No non-idempotent fallback.

type ArtifactExporter

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

ArtifactExporter is a separate host command; sandbox execution cannot invoke it.

func NewArtifactExporter

func NewArtifactExporter(c ArtifactExporterConfig) (*ArtifactExporter, error)

NewArtifactExporter refuses missing authority, screening, storage or delivery.

func (*ArtifactExporter) Export

Export rechecks approval, result freshness and exact screened bytes under the export fence. Any failure after delivery starts is uncertain, even cancellation. Retry only this same request against the sink's durable operation reservation.

type ArtifactExporterConfig

type ArtifactExporterConfig struct {
	Store         ResultContentStore
	Repository    evidence.Repository
	Authorizer    ArtifactExportAuthorizer
	Fence         ArtifactExportFence
	Screener      ArtifactExportScreener
	Sink          ArtifactExportSink
	Clock         Clock
	MaxConcurrent int
}

ArtifactExporterConfig requires explicit current authority and an idempotent sink. MaxConcurrent bounds admission from one to 64. All ports must honor cancellation.

type Binding

type Binding struct {
	Scope          cortex.Scope    `json:"scope"`
	RunID          id.AgentRunID   `json:"run_id"`
	ContractDigest string          `json:"contract_digest"`
	Candidate      evidence.Ref    `json:"candidate"`
	Evidence       []evidence.Ref  `json:"evidence,omitempty"`
	Context        ContextSnapshot `json:"context"`
}

Binding identifies the exact execution, candidate and context being checked. All evidence uses the exact scope; a parent scope cannot authorize a report.

func (Binding) Digest

func (b Binding) Digest() (string, error)

Digest binds every reference in order, including identity and source timing.

func (Binding) Validate

func (b Binding) Validate() error

Validate checks a binding structurally. A trusted host must still recheck resource access and compare current revisions before committing a result.

type BindingAuthorizer

type BindingAuthorizer interface {
	AuthorizeVerification(context.Context, Binding) error
}

BindingAuthorizer checks current principal, source and artifact grants and every revision in the supplied binding. A changed revision must deny access.

type CallCompletion

type CallCompletion struct {
	CallID       id.ID           `json:"call_id"`
	Usage        EvaluationUsage `json:"usage"`
	ReportID     id.ID           `json:"report_id,omitempty"`
	ReportDigest string          `json:"report_digest,omitempty"`
	Failure      string          `json:"failure,omitempty"`
}

CallCompletion retains usage and report identity without duplicating report bytes.

type CallRequest

type CallRequest struct {
	ID               id.ID  `json:"id"`
	Verifier         string `json:"verifier"`
	VerifierRevision string `json:"verifier_revision"`
	MaxTokens        int64  `json:"max_tokens"`
	MaxUSDMicros     int64  `json:"max_usd_micros"`
}

CallRequest pins one verifier group and its conservative usage allowance. The job fixes its binding, pricing revision and full acceptance contract.

func (CallRequest) Validate

func (r CallRequest) Validate() error

Validate checks dispatch identity and bounds, not host price provenance.

type CallResult

type CallResult struct {
	CallID  id.ID
	Usage   EvaluationUsage
	Report  *Report
	Failure string
}

CallResult supplies an authenticated evaluator result or an explicit failure. Only a current job owner may settle, including recovery with a retained receipt.

func (CallResult) Freeze

func (r CallResult) Freeze() (CallResult, CallCompletion, error)

Freeze validates and detaches completion input before storage transactions.

type CallStore

type CallStore interface {
	BeginVerificationCall(context.Context, JobLease, CallRequest) (Job, error)
	CompleteVerificationCall(context.Context, JobLease, CallResult) (Job, error)
}

CallStore atomically records dispatch and settles reports for budgeted jobs. A successful Begin is permission for one invocation only. Errors and repeated requests grant no dispatch permission, even when the prior write may have committed. Hosts must verify allowance and receipt provenance before using these trusted APIs.

type CaptureIntent

type CaptureIntent struct {
	Transcript         *evidence.Ref `json:"transcript,omitempty"`
	MaxTranscriptBytes int64         `json:"max_transcript_bytes,omitempty"`
	SchemaVersion      int           `json:"schema_version"`
	ID                 id.ID         `json:"id"`
	Template           JobRequest    `json:"template"`
	ResultID           id.ID         `json:"result_id"`
	MaxCandidateBytes  int64         `json:"max_candidate_bytes"`
	Digest             string        `json:"digest"`
}

CaptureIntent pins the job and result identities before generation. Template uses the run's registration revision and an empty-content candidate reference (zero bytes and Digest(nil)). Schema 2 also reserves a transcript outside the template. Capture substitutes the completed revision and content hashes/byte counts, then appends the transcript reference. All other policy stays immutable. Candidate.CreatedAt records when the host reserved that artifact identity. The host must reserve EvaluationBudget separately from generation allowance.

func SealCaptureIntent

func SealCaptureIntent(intent CaptureIntent) (CaptureIntent, error)

SealCaptureIntent validates and detaches a trusted host's capture template.

func (CaptureIntent) JobFor

func (i CaptureIntent) JobFor(revision int64, output string, transcript ...[]byte) (JobRequest, error)

JobFor derives the exact request from a later saved run revision and output. Schema 2 requires the canonical transcript. Storage must validate run identity and accounting under its transaction. The intent remains unchanged.

func (CaptureIntent) Validate

func (i CaptureIntent) Validate() error

Validate rejects altered or unsupported policy without resealing it.

type CaptureIntentStore

type CaptureIntentStore interface {
	CreateCaptureIntent(context.Context, CaptureIntent) error
	GetCaptureIntent(context.Context, id.ID) (CaptureIntent, error)
	GetRunCaptureIntent(context.Context, id.AgentRunID) (CaptureIntent, error)
	CaptureFromIntent(context.Context, id.ID) (Job, error)
}

CaptureIntentStore persists a host's intent before dispatch and recovers it after the run finishes. Each exact-scope run, job and result identity has one immutable intent. Reads are historical metadata and need host authorization. Registering an intent alone does not install an execution or publication gate.

type CaptureStore

type CaptureStore interface {
	CaptureVerificationJob(context.Context, JobRequest) (Job, error)
}

CaptureStore atomically copies a completed run's saved output into candidate evidence, enqueues its verification job and marks the run pending. It never accepts candidate bytes from the caller. The requested reference must match the exact stored output. Supporting evidence and the contract must exist.

This is trusted storage, not authorization. The host must authorize the run read, evidence write (including sensitivity and retention) and job binding. Same-request retries return the historical job without recreating evidence removed since capture. They do not grant access or permission to publish. Implementations require a real transaction and must preserve tombstones.

type CheckRequest

type CheckRequest struct {
	Criterion Criterion
	Binding   Binding
	Deadline  time.Time
}

CheckRequest contains a single registered criterion and captured inputs.

type CheckResult

type CheckResult struct {
	StateObservations []StateObservation
	ObservationRefs   []evidence.Ref
	Status            Status
	Score             *float64
	EvidenceIDs       []id.ID
	Human             *HumanVerdict
	Reason            string
}

CheckResult contains evaluator output without caller-controlled timestamps, report identity or binding. The host supplies those after evaluation.

type Clock

type Clock interface{ Now() time.Time }

Clock supplies trusted observation time. Hosts normally return time.Now; tests can inject a deterministic clock without trusting model timestamps.

type CommitFence

type CommitFence interface {
	WithCommitFence(context.Context, Binding, func(Binding) error) error
}

CommitFence holds the host's authorization and revision guards while commit runs. It must capture current state from authoritative sources, call commit exactly once and synchronously, and keep the guards until commit returns. All relevant grant and local revision mutations must participate in the same guards, including mutations from other processes. A read followed by an unlocked callback does not implement this contract. There is no default fence.

External mutable state needs a version-conditional operation or an explicitly bounded observation window. This interface cannot create atomicity across independent services. A host unable to meet its contract must return an error.

type CommitOutbox

type CommitOutbox struct {
	EventID       id.ID         `json:"event_id"`
	Type          string        `json:"type"`
	RunID         id.AgentRunID `json:"run_id"`
	ResultID      id.ID         `json:"result_id"`
	BindingDigest string        `json:"binding_digest"`
}

CommitOutbox is a durable metadata-only publication intent. Delivery still requires host authorization. EventID is stable across retries; this is not a public replay cursor and does not assign a public stream sequence.

type CommitReceipt

type CommitReceipt struct {
	SchemaVersion int           `json:"schema_version"`
	Request       CommitRequest `json:"request"`
	RequestDigest string        `json:"request_digest"`
	RunRevision   int64         `json:"run_revision"`
	ReportDigests []string      `json:"report_digests"`
	ObservedAt    time.Time     `json:"observed_at"`
	Outbox        CommitOutbox  `json:"outbox"`
	Digest        string        `json:"digest"`
}

CommitReceipt records a historical validation and its atomic outbox entry. ObservedAt is the validation time, not a guarantee of continuing freshness. Digest proves integrity only. Trust receipts loaded from your own store.

func SealCommitReceipt

func SealCommitReceipt(r CommitReceipt) (CommitReceipt, error)

SealCommitReceipt validates and detaches a storage-produced receipt.

func (CommitReceipt) Validate

func (r CommitReceipt) Validate() error

Validate rejects a changed receipt without resealing it.

type CommitRequest

type CommitRequest struct {
	SchemaVersion       int       `json:"schema_version"`
	ResultID            id.ID     `json:"result_id"`
	ExpectedRunRevision int64     `json:"expected_run_revision"`
	ContractID          id.ID     `json:"contract_id"`
	ReportIDs           []id.ID   `json:"report_ids"`
	Current             Binding   `json:"current"`
	JobLease            *JobLease `json:"job_lease,omitempty"`
}

CommitRequest is trusted host input. You must fence current authorization and resource revisions throughout this operation. Storage checks saved bindings; it cannot discover changes in external services or authorize public delivery. Report order is significant for idempotency. Candidate text is never accepted here.

func (CommitRequest) Freeze

func (r CommitRequest) Freeze() (CommitRequest, string, error)

Freeze validates, bounds and detaches the request before a transaction starts.

type CommitStore

type CommitStore interface {
	CommitVerifiedResult(context.Context, CommitRequest) (CommitReceipt, error)
	GetCommittedResult(context.Context, id.ID) (CommitReceipt, error)
}

CommitStore is optional and does not widen the legacy composite store. Same-request retries return the original historical receipt even after expiry. Callers must reauthorize every later read or delivery through their host policy.

type Committer

type Committer interface {
	Commit(context.Context, CommitRequest) (CommitReceipt, error)
}

Committer authorizes a result under a host fence before calling atomic storage. It does not deliver public content or expose unauthenticated historical reads. An error can follow a durable commit, for example if the host loses its final acknowledgement. Reconcile with the same request and ResultID; never mint a new ID to hide an ambiguous outcome.

func NewCommitter

func NewCommitter(storage CommitStore, fence CommitFence, authorizer BindingAuthorizer) (Committer, error)

NewCommitter requires explicit storage, fencing and current grant checks. The authorizer runs inside the fence, including on idempotent retries.

type ContextSnapshot

type ContextSnapshot struct {
	ExecutionTranscript *evidence.Ref  `json:"execution_transcript,omitempty"`
	ExecutionInputs     *evidence.Ref  `json:"execution_inputs,omitempty"`
	PrincipalRef        string         `json:"principal_ref"`
	AuthorityRevision   string         `json:"authority_revision"`
	PreparedDigest      string         `json:"prepared_digest"`
	PolicyRevision      string         `json:"policy_revision"`
	EnvironmentRevision string         `json:"environment_revision"`
	DatasetRevision     string         `json:"dataset_revision"`
	Sources             []Source       `json:"sources,omitempty"`
	Tools               []ToolRevision `json:"tools,omitempty"`
}

ContextSnapshot contains host-attested identity and revision references. AuthorityRevision must change when grants are revoked. Verifiers cannot establish current authorization by inspecting this snapshot alone.

type Contract

type Contract struct {
	SchemaVersion int          `json:"schema_version"`
	ID            id.ID        `json:"id"`
	Scope         cortex.Scope `json:"scope"`
	Revision      string       `json:"revision"`
	Digest        string       `json:"digest"`
	Objective     string       `json:"objective"`
	Constraints   []string     `json:"constraints,omitempty"`
	Criteria      []Criterion  `json:"criteria"`
}

Contract binds an objective and ordered criteria to a scope and revision. A new revision requires a new ID. Digest excludes only its own field.

func SealContract

func SealContract(c Contract) (Contract, error)

SealContract detaches a host-authored contract and seals its canonical JSON. Criterion order is significant and is never sorted away.

func (Contract) Validate

func (c Contract) Validate() error

Validate rejects a changed or unsupported contract rather than resealing it.

type Criterion

type Criterion struct {
	ID               string        `json:"id"`
	Kind             Kind          `json:"kind"`
	Required         bool          `json:"required"`
	Verifier         string        `json:"verifier"`
	VerifierRevision string        `json:"verifier_revision"`
	Parameters       Parameters    `json:"parameters"`
	MaxAge           time.Duration `json:"max_age_ns"`
	// MaxSourceAge limits source observation age; zero leaves that policy to the host.
	MaxSourceAge time.Duration `json:"max_source_age_ns"`
	MinEvidence  int           `json:"min_evidence"`
}

Criterion is one ordered acceptance check. Every required check must pass.

type CriterionDecision

type CriterionDecision struct {
	CriterionID string `json:"criterion_id"`
	Required    bool   `json:"required"`
	Status      Status `json:"status"`
}

CriterionDecision retains contract ordering and explains missing checks.

type Decision

type Decision struct {
	Status   Status              `json:"status"`
	Criteria []CriterionDecision `json:"criteria"`
}

Decision is a derived verdict, not a persisted authorization to publish.

func Aggregate

func Aggregate(contract Contract, reports []Report, at time.Time) Decision

Aggregate requires all required criteria for the same immutable binding. The caller must separately check that binding against current authorized state. Conflicting reports cannot be resolved by selecting a favorable one.

type EvaluationAdapter

EvaluationAdapter supplies qualified evaluator access and authenticated usage. Estimate must use trusted pricing and bounds without billable provider work. Evaluate must enforce the allowance and context deadline, retain a recoverable result under the call ID, and never run original agent generation or tool effects. Reconcile reads that original outcome without billable work or another evaluator invocation. Adapters must reauthorize actual resource reads. A missing or still-running result returns ErrCallUncertain. Returning an error never authorizes a report or refund, even if the result also contains data. A definitive evaluator failure uses CallResult.Failure with a nil error.

type EvaluationAllowance

type EvaluationAllowance struct {
	MaxTokens       int64
	MaxUSDMicros    int64
	PricingRevision string
}

EvaluationAllowance is a trusted upper bound for one verifier group. PricingRevision must match the job, or be empty in explicit token-only mode.

type EvaluationBudget

type EvaluationBudget struct {
	MaxCalls        int    `json:"max_calls"`
	MaxTokens       int64  `json:"max_tokens"`
	MaxUSDMicros    int64  `json:"max_usd_micros"`
	TokenOnly       bool   `json:"token_only"`
	PricingRevision string `json:"pricing_revision,omitempty"`
}

EvaluationBudget caps dispatch charges within one job. Zero token allowance permits only calls with a zero token bound. TokenOnly explicitly disables a money ceiling; otherwise the host must supply a pinned pricing revision.

func (EvaluationBudget) Admit

Admit checks a host-computed upper bound before an external call starts. Actual usage above the bound is retained and prevents later overspending; the adapter, not this ledger, must enforce provider limits on the active call.

func (EvaluationBudget) Validate

func (b EvaluationBudget) Validate() error

Validate rejects missing or contradictory accounting policy.

type EvaluationCall

type EvaluationCall struct {
	Request      CallRequest     `json:"request"`
	Generation   int64           `json:"generation"`
	CriterionIDs []string        `json:"criterion_ids"`
	StartedAt    time.Time       `json:"started_at"`
	CompletedAt  time.Time       `json:"completed_at,omitempty"`
	Completion   *CallCompletion `json:"completion,omitempty"`
}

EvaluationCall is recorded before dispatch. No completion means the provider may have executed; another worker must reconcile rather than issue the call again.

type EvaluationDebit

type EvaluationDebit struct {
	Calls     int   `json:"calls"`
	Tokens    int64 `json:"tokens"`
	USDMicros int64 `json:"usd_micros"`
}

EvaluationDebit includes all dispatched calls, including unresolved outcomes.

func DebitCalls

func DebitCalls(calls []EvaluationCall) EvaluationDebit

DebitCalls conservatively charges unresolved usage and preserves overruns.

type EvaluationDispatch

type EvaluationDispatch struct {
	Input EvaluationInput
	Call  EvaluationCall
}

EvaluationDispatch carries the persisted call identity and original allowance. Adapters use Call.Request.ID as the stable provider operation key.

type EvaluationInput

type EvaluationInput struct {
	JobID   id.ID
	Request Request
	Budget  EvaluationBudget
}

EvaluationInput pins the captured candidate and host accounting policy. Request.Deadline remains the job deadline across recovery; each operation's context also respects the caller deadline. Without renewal its deadline includes lease expiry; with renewal a watchdog cancels at the last acknowledged expiry.

type EvaluationManifest

type EvaluationManifest struct {
	SchemaVersion      int          `json:"schema_version"`
	Revision           string       `json:"revision"`
	Binding            Binding      `json:"binding"`
	Criterion          Criterion    `json:"criterion"`
	TestBundle         evidence.Ref `json:"test_bundle"`
	FixtureDataset     evidence.Ref `json:"fixture_dataset"`
	ResultSchema       evidence.Ref `json:"result_schema"`
	SupervisorRevision string       `json:"supervisor_revision"`
	RequiredChecks     []string     `json:"required_checks"`
	StateProbes        []Source     `json:"state_probes,omitempty"`
	Digest             string       `json:"digest"`
}

EvaluationManifest pins host-selected grading material to one captured check. Sealing is not registration, execution authorization or proof of isolation.

func SealEvaluationManifest

func SealEvaluationManifest(m EvaluationManifest) (EvaluationManifest, error)

SealEvaluationManifest detaches and seals a host-selected grading manifest.

func (EvaluationManifest) Validate

func (m EvaluationManifest) Validate() error

Validate detects unsupported or changed grading manifests.

func (EvaluationManifest) ValidateRequest

func (m EvaluationManifest) ValidateRequest(req TestRequest, now time.Time) error

ValidateRequest binds a test request and trusted observation time to this manifest. The deadline must fit inside every artifact's retention interval. Callers must independently recheck current authority, source state and runtime qualification.

type EvaluationRegistry

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

EvaluationRegistry holds host-registered manifests for captured executions. It is not an authorization service or a durable registration store. Registered manifests are immutable; changes require a new registry. Reads are concurrent.

func NewEvaluationRegistry

func NewEvaluationRegistry(manifests []EvaluationManifest) (*EvaluationRegistry, error)

NewEvaluationRegistry freezes up to 256 already sealed manifests, with a combined encoding limit of sixteen MiB. It rejects ambiguous registrations.

func (*EvaluationRegistry) Resolve

Resolve selects an exact registered execution/check in the context's scope. It returns a detached copy and checks evidence timing. A caller must still authorize current access, qualify the runner and supervise grading externally.

type EvaluationUsage

type EvaluationUsage struct {
	Tokens      int64  `json:"tokens"`
	USDMicros   int64  `json:"usd_micros"`
	TokensKnown bool   `json:"tokens_known"`
	MoneyKnown  bool   `json:"money_known"`
	Receipt     string `json:"receipt,omitempty"`
}

EvaluationUsage is a host-attributed usage observation. Unknown dimensions retain their full dispatch allowance. Known zero is valid with a receipt. Receipt identifies trusted adapter evidence; model text is not a receipt.

type ExecutionInputs

type ExecutionInputs struct {
	ContextSelection *cognitive.ContextRecord `json:"context_selection,omitempty"`
	OriginalHistory  []llm.Message            `json:"original_history,omitempty"`
	SchemaVersion    int                      `json:"schema_version"`
	RunID            id.AgentRunID            `json:"run_id"`
	AgentID          id.AgentID               `json:"agent_id"`
	SessionID        id.SessionID             `json:"session_id"`
	PreparedDigest   string                   `json:"prepared_digest"`
	Input            string                   `json:"input"`
	History          []llm.Message            `json:"history,omitempty"`
	Model            string                   `json:"model"`
	ModelRevision    string                   `json:"model_revision"`
	Tools            []ToolRevision           `json:"tools,omitempty"`
}

ExecutionInputs captures the scanned task and initial conversation before any generation. Store its canonical encoding as private evidence, not run metadata. ModelRevision and tool revisions are host pins, not provider attestations.

func DecodeExecutionInputs

func DecodeExecutionInputs(data []byte) (ExecutionInputs, error)

DecodeExecutionInputs accepts only the canonical versioned encoding. This rejects ambiguous duplicate keys, unknown fields and lossy UTF-8 conversions.

func (ExecutionInputs) Encode

func (v ExecutionInputs) Encode() ([]byte, error)

Encode validates and serializes an immutable input artifact of at most one MiB.

type ExecutionTranscript

type ExecutionTranscript struct {
	SchemaVersion int             `json:"schema_version"`
	RunID         id.AgentRunID   `json:"run_id"`
	InputsDigest  string          `json:"inputs_digest"`
	Messages      []llm.Message   `json:"messages"`
	Tools         []ToolResult    `json:"tools,omitempty"`
	Usage         execution.Usage `json:"usage"`
}

ExecutionTranscript preserves this run's checked model/tool conversation. Initial task/history are linked by InputsDigest. This is private evidence, not public conversation history or a crash-atomic external effect receipt.

func DecodeExecutionTranscript

func DecodeExecutionTranscript(data []byte) (ExecutionTranscript, error)

DecodeExecutionTranscript rejects noncanonical, ambiguous or future encodings.

func (ExecutionTranscript) Encode

func (v ExecutionTranscript) Encode() ([]byte, error)

Encode validates a complete conversation and returns at most one MiB of canonical JSON. Every requested call has one response and one host outcome.

func (ExecutionTranscript) ValidateFor

func (v ExecutionTranscript) ValidateFor(inputs ExecutionInputs, output string, usage execution.Usage) error

ValidateFor checks a transcript against captured input, output and accounting. Unknown requested tools may appear only as locally denied, uncharged calls.

type Executor

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

Executor advances one verifier group under an existing lease. It neither claims work nor commits/publishes final results. An error may follow durable dispatch or settlement; inspect the saved job before deciding what to do next.

func NewExecutor

func NewExecutor(config ExecutorConfig) (*Executor, error)

NewExecutor validates the mandatory host services.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, request ExecutorRequest) (Job, error)

Execute dispatches fresh work or reconciles an already recorded call.

type ExecutorConfig

type ExecutorConfig struct {
	LeaseRenewal *LeaseRenewalPolicy
	Store        ExecutorStore
	Adapter      EvaluationAdapter
	Authorizer   BindingAuthorizer
	Clock        Clock
}

ExecutorConfig requires durable storage and explicit trusted host services.

type ExecutorRequest

type ExecutorRequest struct {
	Lease            JobLease
	Verifier         string
	VerifierRevision string
}

ExecutorRequest selects one exact contract-defined verifier group.

type ExecutorStore

type ExecutorStore interface {
	GetVerificationJob(context.Context, id.ID) (Job, error)
	GetContract(context.Context, id.ID) (Contract, error)
	BeginVerificationCall(context.Context, JobLease, CallRequest) (Job, error)
	CompleteVerificationCall(context.Context, JobLease, CallResult) (Job, error)
}

ExecutorStore is the durable subset used by the evaluator executor.

type HumanRequest

type HumanRequest struct{ CheckRequest }

HumanRequest selects a review policy for an authenticated human verdict.

type HumanReviewer

type HumanReviewer interface {
	Review(context.Context, HumanRequest) (CheckResult, error)
}

HumanReviewer resolves an authenticated review bound to exact evidence.

type HumanVerdict

type HumanVerdict struct {
	Actor            string    `json:"actor"`
	DecisionRevision string    `json:"decision_revision"`
	EvidenceDigest   string    `json:"evidence_digest"`
	ExpiresAt        time.Time `json:"expires_at"`
}

HumanVerdict records an authenticated host review of exact evidence. EvidenceDigest is the complete Binding.Digest, not merely candidate bytes.

type Job

type Job struct {
	SchemaVersion int              `json:"schema_version"`
	Request       JobRequest       `json:"request"`
	RequestDigest string           `json:"request_digest"`
	RunRevision   int64            `json:"run_revision"`
	Revision      int64            `json:"revision"`
	Generation    int64            `json:"generation"`
	Attempts      int              `json:"attempts"`
	ClaimIDs      []id.ID          `json:"claim_ids,omitempty"`
	State         JobState         `json:"state"`
	Lease         *JobLease        `json:"lease,omitempty"`
	ReportIDs     []id.ID          `json:"report_ids,omitempty"`
	Calls         []EvaluationCall `json:"calls,omitempty"`
	ResultID      id.ID            `json:"result_id,omitempty"`
	CreatedAt     time.Time        `json:"created_at"`
	UpdatedAt     time.Time        `json:"updated_at"`
	Digest        string           `json:"digest"`
}

Job persists accepted reports across worker restarts. A digest detects stored corruption, not authenticity; this is trusted storage metadata.

func SealJob

func SealJob(j Job) (Job, error)

SealJob validates and detaches a storage-produced job snapshot.

func (Job) CheckLease

func (j Job) CheckLease(lease JobLease, now time.Time) error

CheckLease checks ownership against this saved snapshot. Callers must validate the snapshot and use trusted current time. ExpiresAt in the supplied token is not authoritative, and this check does not lock or refresh storage.

func (Job) Validate

func (j Job) Validate() error

Validate rejects changed snapshots without resealing them.

type JobClaim

type JobClaim struct {
	JobID    id.ID
	ClaimID  id.ID
	Owner    string
	Duration time.Duration
}

JobClaim requests one bounded ownership generation.

type JobLease

type JobLease struct {
	JobID      id.ID     `json:"job_id"`
	ClaimID    id.ID     `json:"claim_id"`
	Owner      string    `json:"owner"`
	Generation int64     `json:"generation"`
	ExpiresAt  time.Time `json:"expires_at"`
}

JobLease is an ownership token. Expiry comes from storage, never the worker. ClaimID makes a lost claim acknowledgement recoverable without another attempt.

func (JobLease) Validate

func (l JobLease) Validate() error

Validate checks a token's shape; storage must check live ownership and expiry.

type JobListRequest

type JobListRequest struct {
	RunID id.AgentRunID
	After id.ID
	Limit int
}

JobListRequest pages exact-scope jobs by ID, optionally restricted to a run.

type JobRequest

type JobRequest struct {
	SchemaVersion       int               `json:"schema_version"`
	ID                  id.ID             `json:"id"`
	ExpectedRunRevision int64             `json:"expected_run_revision"`
	ContractID          id.ID             `json:"contract_id"`
	Binding             Binding           `json:"binding"`
	Deadline            time.Time         `json:"deadline"`
	MaxAttempts         int               `json:"max_attempts"`
	EvaluationBudget    *EvaluationBudget `json:"evaluation_budget,omitempty"`
}

JobRequest pins the captured candidate and contract. Scheduling never invokes an agent or tool. A new verification attempt uses a new ID and run revision.

func (JobRequest) Freeze

func (r JobRequest) Freeze() (JobRequest, string, error)

Freeze validates and detaches an immutable job request.

type JobState

type JobState string

JobState separates verification work from generation and public delivery.

const (
	JobQueued       JobState = "queued"
	JobRunning      JobState = "running"
	JobReady        JobState = "ready"
	JobCommitted    JobState = "committed"
	JobFailed       JobState = "failed"
	JobInconclusive JobState = "inconclusive"
	JobCancelled    JobState = "cancelled"
)

type JobStore

type JobStore interface {
	EnqueueVerificationJob(context.Context, JobRequest) (Job, error)
	GetVerificationJob(context.Context, id.ID) (Job, error)
	ListVerificationJobs(context.Context, JobListRequest) ([]Job, error)
	ClaimVerificationJob(context.Context, JobClaim) (Job, error)
	RenewVerificationJob(context.Context, JobLease, time.Duration) (Job, error)
	SaveVerificationJobReport(context.Context, JobLease, Report) (Job, error)
	ExpireVerificationJob(context.Context, id.ID) (Job, error)
	CancelVerificationJob(context.Context, id.ID) (Job, error)
}

JobStore persists evaluation work without rerunning generation or tools. These are trusted host operations. Workers must use the lease-aware report method and include their lease when committing a result.

type Kind

type Kind string

Kind identifies the host-registered check required by a criterion.

const (
	KindSchema   Kind = "schema"
	KindTest     Kind = "test"
	KindState    Kind = "state"
	KindSemantic Kind = "semantic"
	KindHuman    Kind = "human"
	KindPolicy   Kind = "policy"
)

type LeaseRenewalPolicy

type LeaseRenewalPolicy struct {
	Duration time.Duration
	Interval time.Duration
}

LeaseRenewalPolicy keeps evaluator callbacks owned within the job deadline. Interval must be at most half Duration. Host ports must honor cancellation and support concurrent authorization, reads and renewal during callbacks.

type LeaseRenewer

type LeaseRenewer interface {
	RenewVerificationJob(context.Context, JobLease, time.Duration) (Job, error)
}

LeaseRenewer is optional unless automatic evaluator renewal is configured. Renewal must atomically preserve the live claim and ownership generation.

type ListRequest

type ListRequest struct {
	RunID id.AgentRunID
	After id.ID
	Limit int
}

ListRequest identifies a single run in the exact caller scope. Limit must be 1..256. After is an exclusive report ID cursor, ordered lexicographically.

type Outcome

type Outcome struct {
	StateObservations []StateObservation `json:"state_observations,omitempty"`
	ObservationRefs   []evidence.Ref     `json:"observation_refs,omitempty"`
	CriterionID       string             `json:"criterion_id"`
	Verifier          string             `json:"verifier"`
	VerifierRevision  string             `json:"verifier_revision"`
	Status            Status             `json:"status"`
	Score             *float64           `json:"score,omitempty"`
	EvidenceIDs       []id.ID            `json:"evidence_ids,omitempty"`
	Human             *HumanVerdict      `json:"human,omitempty"`
	Reason            string             `json:"reason,omitempty"`
}

Outcome describes one check. Scores are optional diagnostics in [0,1]. Status is the authoritative verdict; scores never turn failures into passes.

type Parameters

type Parameters struct {
	ManifestRevision string `json:"manifest_revision"`
}

Parameters references a host-registered, immutable check manifest. The manifest defines the kind-specific schema, test bundle, state probe or rubric. It never carries commands or callbacks supplied by candidate content.

type PublishedResult

type PublishedResult struct {
	SchemaVersion      int                      `json:"schema_version"`
	RunID              id.AgentRunID            `json:"run_id"`
	ResultID           id.ID                    `json:"result_id"`
	RunRevision        int64                    `json:"run_revision"`
	Content            string                   `json:"content"`
	PublicationStatus  safety.PublicationStatus `json:"publication_status"`
	ContentChanged     bool                     `json:"content_changed"`
	VerificationStatus Status                   `json:"verification_status"`
	VerifiedAt         time.Time                `json:"verified_at"`
	CheckedAt          time.Time                `json:"checked_at"`
}

PublishedResult contains public content and minimal assurance metadata. VerificationStatus and VerifiedAt describe the original committed candidate. When ContentChanged is true, the returned text has not itself been verified. CheckedAt is an observation time, not a grant or freshness lease for later use.

type Registration

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

Registration is a host-created, kind-specific evaluator binding. Its private dispatch function cannot be supplied through a serialized Request.

func RegisterHuman

func RegisterHuman(name, revision, manifest string, checker HumanReviewer) Registration

RegisterHuman binds a review adapter to its immutable policy revision.

func RegisterSchema

func RegisterSchema(name, revision, manifest string, checker SchemaChecker) Registration

RegisterSchema binds a schema evaluator to its immutable implementation and manifest.

func RegisterState

func RegisterState(name, revision, manifest string, checker StateChecker) Registration

RegisterState binds a state observer to its immutable implementation and manifest.

func RegisterTests

func RegisterTests(name, revision, manifest string, checker TestEvaluator) Registration

RegisterTests binds a test evaluator to its immutable implementation and manifest.

type Report

type Report struct {
	SchemaVersion int       `json:"schema_version"`
	ID            id.ID     `json:"id"`
	Digest        string    `json:"digest"`
	Binding       Binding   `json:"binding"`
	CheckedAt     time.Time `json:"checked_at"`
	ExpiresAt     time.Time `json:"expires_at"`
	Outcomes      []Outcome `json:"outcomes"`
}

Report is an immutable, host-stamped observation. SealReport computes integrity, not authenticity. Only trusted verifier adapters may create reports.

func SealReport

func SealReport(r Report) (Report, error)

SealReport validates and detaches a report before computing its digest.

func (Report) Validate

func (r Report) Validate() error

Validate rejects tampering without updating the recorded digest.

type Request

type Request struct {
	Contract         Contract  `json:"contract"`
	Binding          Binding   `json:"binding"`
	Deadline         time.Time `json:"deadline"`
	Verifier         string    `json:"verifier"`
	VerifierRevision string    `json:"verifier_revision"`
}

Request contains host-captured inputs only. It cannot register evaluators or execute callbacks. Each verifier returns only its registered criteria.

type ResultContentAuthorizer

type ResultContentAuthorizer interface {
	AuthorizeResultContent(context.Context, ResultContentRequest) error
}

ResultContentAuthorizer checks the current reader's exact scope and content grant. Metadata replay or historical verification authority cannot satisfy it.

type ResultContentFailure

type ResultContentFailure struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

ResultContentFailure is the shared public diagnostic vocabulary for content reads.

func DescribeResultContentFailure

func DescribeResultContentFailure(err error) ResultContentFailure

DescribeResultContentFailure never includes storage, checker or host diagnostics.

type ResultContentRequest

type ResultContentRequest struct {
	SchemaVersion int           `json:"schema_version"`
	RunID         id.AgentRunID `json:"run_id"`
	ResultID      id.ID         `json:"result_id"`
}

ResultContentRequest selects a committed result without exposing private receipts.

func ParseResultContentRequest

func ParseResultContentRequest(runID, resultID string) (ResultContentRequest, error)

ParseResultContentRequest validates transport IDs without echoing private input.

func (ResultContentRequest) Validate

func (r ResultContentRequest) Validate() error

Validate rejects missing identities and unsupported schemas.

type ResultContentResponse

type ResultContentResponse struct {
	PublishedResult
	RunRevision string `json:"run_revision"`
}

ResultContentResponse preserves revision precision in JSON and generated schemas. The outer decimal string replaces PublishedResult.RunRevision on the wire.

func NewResultContentResponse

func NewResultContentResponse(result PublishedResult) ResultContentResponse

NewResultContentResponse projects a guarded result into its transport envelope.

type ResultContentStore

type ResultContentStore interface {
	ResultSnapshotStore
	GetCommittedResult(context.Context, id.ID) (CommitReceipt, error)
}

ResultContentStore supplies trusted historical identity and fresh saved material.

type ResultPublicationRequest

type ResultPublicationRequest struct {
	Request     ResultContentRequest
	RunRevision int64
	Binding     Binding
	Content     string
}

ResultPublicationRequest is private input for the host's current publication policy. The reader detaches Binding before passing it to the publisher.

type ResultPublisher

type ResultPublisher interface {
	PublishResult(context.Context, ResultPublicationRequest) (safety.PublicationDecision, error)
}

ResultPublisher screens the entire answer using current host publication policy. Only approved, flagged or redacted decisions are accepted. Changed text must explicitly be redacted; this port cannot assert verification of the projection.

type ResultReadRequest

type ResultReadRequest struct {
	SchemaVersion int           `json:"schema_version"`
	RunID         id.AgentRunID `json:"run_id"`
	ResultID      id.ID         `json:"result_id"`
	ReceiptDigest string        `json:"receipt_digest"`
}

ResultReadRequest pins a historical receipt to its exact run. A valid digest is an integrity binding, never an access credential.

func (ResultReadRequest) Validate

func (r ResultReadRequest) Validate() error

Validate rejects unbound reads before storage is consulted.

type ResultReader

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

ResultReader serves a screened projection of a currently valid committed result.

func NewResultReader

func NewResultReader(config ResultReaderConfig) (*ResultReader, error)

NewResultReader refuses absent or typed-nil host ports. There is no permissive default.

func (*ResultReader) Read

Read authorizes before storage and under the host fence. Screening runs outside database transactions; a second snapshot rejects evidence deletion or changes during screening. No raw receipt, report, binding or provider error is returned.

type ResultReaderConfig

type ResultReaderConfig struct {
	Store      ResultContentStore
	Authorizer ResultContentAuthorizer
	Fence      CommitFence
	Publisher  ResultPublisher
	Clock      Clock
}

ResultReaderConfig requires explicit content authority, revision fencing and publication screening. The fence must also cover relevant grant and policy writers through the synchronous callback. Remote state needs the observation window or conditional operations described by CommitFence.

type ResultSnapshot

type ResultSnapshot struct {
	SchemaVersion int           `json:"schema_version"`
	Receipt       CommitReceipt `json:"receipt"`
	Contract      Contract      `json:"contract"`
	Reports       []Report      `json:"reports"`
	ObservedAt    time.Time     `json:"observed_at"`
	Output        string        `json:"-"`
}

ResultSnapshot contains private, stored result material from one transaction. Output is intentionally excluded from JSON. This is not a public response: hosts must check current grants and source revisions and apply publication policy before exposing content. Reports allow time-based revalidation after I/O.

func (ResultSnapshot) Validate

func (s ResultSnapshot) Validate(request ResultReadRequest, at time.Time) error

Validate checks identity, bytes and freshness at the supplied trusted time. It cannot establish current authority or discover external source changes.

type ResultSnapshotStore

type ResultSnapshotStore interface {
	ReadResultSnapshot(context.Context, ResultReadRequest) (ResultSnapshot, error)
}

ResultSnapshotStore is optional trusted storage, not a public content reader. It rechecks the current passed run, immutable receipt, saved evidence and report freshness under one run transaction. No remote callbacks run under database locks. External authorization and publication remain the host's responsibility.

type SandboxAssessment

type SandboxAssessment struct {
	ManifestDigest     string
	SupervisorRevision string
	CandidateDigest    string
	GraderDigest       string
	Checks             []SupervisedCheck
	ObservationRefs    []evidence.Ref
}

SandboxAssessment binds external observations to both exact jobs. The trusted supervisor must retain authenticated evidence, independently corroborate tests that execute candidate code, and never interpret workload text as instructions.

type SandboxAuthenticity

type SandboxAuthenticity interface {
	VerifyReceipt(context.Context, sandbox.Receipt, sandbox.Job) error
	VerifyResult(context.Context, sandbox.Result, sandbox.Job) error
}

SandboxAuthenticity checks pinned broker signatures, not candidate assertions. Implementations must authenticate the expected broker and complete job binding.

type SandboxObservation

type SandboxObservation struct {
	Manifest           EvaluationManifest
	Candidate          sandbox.Job
	Grader             sandbox.Job
	CandidateArtifacts []evidence.Ref
	GraderArtifacts    []evidence.Ref
}

SandboxObservation contains completed job identities and captured references. Stdout and stderr are deliberately absent. They cannot supply verdicts.

type SandboxSupervisor

type SandboxSupervisor interface {
	Assess(context.Context, SandboxObservation) (SandboxAssessment, error)
}

SandboxSupervisor obtains authoritative observations outside both workloads. It receives no effect tools or production credentials through this interface. Implementations must reconcile retries by manifest and job digests, retaining the original observations so a repeated request cannot change its assessment.

type SandboxTestConfig

type SandboxTestConfig struct {
	Registry      *EvaluationRegistry
	Plans         []SandboxTestPlan
	Runner        sandbox.Runner
	Repository    evidence.Repository
	Authenticity  SandboxAuthenticity
	Supervisor    SandboxSupervisor
	Authorizer    BindingAuthorizer
	Clock         Clock
	MaxConcurrent int
	PollInterval  time.Duration
}

SandboxTestConfig requires explicit host authority and authenticated runner services. Registration does not qualify a deployment. Ports must honor context cancellation; the caller owns total evaluator resource/cost accounting. MaxConcurrent bounds in-flight evaluations and must be between one and 64.

type SandboxTestPlan

type SandboxTestPlan struct {
	ManifestDigest string
	Candidate      sandbox.Job
	Grader         sandbox.Job
}

SandboxTestPlan is host configuration for one registered manifest. Grader is a sealed template with protected inputs; the verified candidate export is appended at /inputs/candidate-export before the grader job is sealed again. IDs and keys must be reserved durably by the host before registration.

type SandboxTestVerifier

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

SandboxTestVerifier runs registered candidate/grader jobs and asks an external supervisor for their outcome. It never publishes or exports to production.

func NewSandboxTestVerifier

func NewSandboxTestVerifier(config SandboxTestConfig) (*SandboxTestVerifier, error)

NewSandboxTestVerifier freezes registered execution plans.

func (*SandboxTestVerifier) EvaluateTests

func (v *SandboxTestVerifier) EvaluateTests(ctx context.Context, req TestRequest) (CheckResult, error)

EvaluateTests dispatches only the reserved jobs. Ambiguous dispatch returns ErrCallUncertain; it never allocates replacement identities or falls back to a host process. Reconciliation and durable phase recovery belong to the host.

type SchemaChecker

type SchemaChecker interface {
	CheckSchema(context.Context, SchemaRequest) (CheckResult, error)
}

SchemaChecker validates captured content against a registered schema.

type SchemaRequest

type SchemaRequest struct{ CheckRequest }

SchemaRequest selects an immutable host schema manifest.

type Source

type Source struct {
	Resource    string    `json:"resource"`
	Revision    string    `json:"revision"`
	Digest      string    `json:"digest"`
	RetrievedAt time.Time `json:"retrieved_at"`
}

Source records a captured resource revision and its host observation time.

func (Source) Equal

func (s Source) Equal(other Source) bool

Equal compares captured provenance independently of clock representations.

func (Source) Validate

func (s Source) Validate() error

Validate checks a source reference without establishing its authenticity or present availability. The host supplies the captured revision and timestamp.

type StateChecker

type StateChecker interface {
	CheckState(context.Context, StateRequest) (CheckResult, error)
}

StateChecker observes authorized state without repeating the original task.

type StateManifest

type StateManifest struct {
	SchemaVersion        int           `json:"schema_version"`
	Binding              Binding       `json:"binding"`
	Criterion            Criterion     `json:"criterion"`
	Probes               []Source      `json:"probes"`
	MaxObservationWindow time.Duration `json:"max_observation_window_ns"`
	Digest               string        `json:"digest"`
}

StateManifest selects captured sources for read-only current-state checks. Its revision must match the exact criterion. Sealing grants no authority.

func SealStateManifest

func SealStateManifest(m StateManifest) (StateManifest, error)

SealStateManifest freezes a captured external-state policy.

func (StateManifest) Validate

func (m StateManifest) Validate() error

Validate checks the exact captured manifest without registering it.

type StateObservation

type StateObservation struct {
	BindingDigest  string    `json:"binding_digest"`
	ManifestDigest string    `json:"manifest_digest"`
	Source         Source    `json:"source"`
	StartedAt      time.Time `json:"started_at"`
	FinishedAt     time.Time `json:"finished_at"`
	ExpiresAt      time.Time `json:"expires_at"`
}

StateObservation records an authenticated host read of a captured resource. BindingDigest and ManifestDigest bind it to one registered check. ExpiresAt is assigned by StateVerifier, never by the resource being observed.

type StateObserver

type StateObserver interface {
	ObserveState(context.Context, StateProbeRequest) (StateObservation, error)
}

StateObserver reads authoritative external state without task effects. It must honor cancellation and return authenticated revision/digest and read timing. It must not accept a candidate's description of state as an observation.

type StateProbeRequest

type StateProbeRequest struct {
	Binding        Binding
	ManifestDigest string
	Source         Source
}

StateProbeRequest contains only the registered resource and its exact context. Observers must authenticate the source and scope using current host grants.

type StateRequest

type StateRequest struct{ CheckRequest }

StateRequest selects an authorized external-state observation manifest.

type StateVerifier

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

StateVerifier checks registered external resources in the captured context. Observation does not lock an external service or authorize publication.

func NewStateVerifier

func NewStateVerifier(c StateVerifierConfig) (*StateVerifier, error)

NewStateVerifier registers host policies without performing external reads.

func (*StateVerifier) CheckState

func (v *StateVerifier) CheckState(ctx context.Context, req StateRequest) (CheckResult, error)

CheckState records fresh read windows and compares authorized observations to captured revisions. It never repeats the task or updates a changed resource.

type StateVerifierConfig

type StateVerifierConfig struct {
	Manifests     []StateManifest
	Observer      StateObserver
	Authorizer    BindingAuthorizer
	Clock         Clock
	MaxConcurrent int
}

StateVerifierConfig registers immutable manifests and explicit host ports. MaxConcurrent bounds admission between one and 64. Ports must honor deadlines.

type Status

type Status string

Status records the outcome of explicit result checks, never model confidence.

const (
	StatusUnchecked    Status = "unchecked"
	StatusPending      Status = "pending"
	StatusPassed       Status = "passed"
	StatusFailed       Status = "failed"
	StatusInconclusive Status = "inconclusive"
	StatusStale        Status = "stale"
)

func CheckFreshness

func CheckFreshness(report Report, current Binding, at time.Time) Status

CheckFreshness checks integrity, expiry and a trusted current binding. Passed here means the binding is current, not that the checks passed. Access revocation must be reflected by the host's current authority revision or denied before this function is called. It performs no external I/O.

func (Status) Normalized

func (s Status) Normalized() Status

Normalized treats historical records with no checks as unchecked. Unknown values survive round trips but do not become passed.

type Store

type Store interface {
	CreateContract(context.Context, Contract) error
	GetContract(context.Context, id.ID) (Contract, error)
	SaveReport(context.Context, Report) error
	GetReport(context.Context, id.ID) (Report, error)
	ListReports(context.Context, ListRequest) ([]Report, error)
}

Store is an optional capability for immutable contracts and reports. Reads and writes require exact context scope, never inherited scope. Reusing an ID is idempotent only for identical content. Report writes validate the saved contract and its digest. A report's digest is integrity, not evaluator trust; only authenticated host verifier paths may call SaveReport.

type SupervisedCheck

type SupervisedCheck struct {
	Name   string
	Status Status
}

SupervisedCheck is an external supervisor's observation of one required check.

type TestEvaluator

type TestEvaluator interface {
	EvaluateTests(context.Context, TestRequest) (CheckResult, error)
}

TestEvaluator evaluates a captured artifact in a separately qualified runner. Registration alone does not establish sandbox isolation.

type TestRequest

type TestRequest struct{ CheckRequest }

TestRequest selects an immutable host test manifest, never candidate commands.

type ToolOutcome

type ToolOutcome string

ToolOutcome is a host-recorded result, never inferred from tool response text.

const (
	ToolCompleted ToolOutcome = "completed"
	ToolFailed    ToolOutcome = "failed"
	ToolDenied    ToolOutcome = "denied"
)

Terminal outcomes distinguish successful responses from failures and denials.

type ToolResult

type ToolResult struct {
	CallID  string      `json:"call_id"`
	Outcome ToolOutcome `json:"outcome"`
	Source  ToolSource  `json:"source"`
}

ToolResult attaches trusted outcome metadata to a conversation tool-call ID. The checked content and arguments live in ExecutionTranscript.Messages.

type ToolRevision

type ToolRevision struct {
	Name     string `json:"name"`
	Revision string `json:"revision"`
}

ToolRevision pins a tool implementation used by the captured execution.

type ToolSource

type ToolSource string

ToolSource identifies who supplied a result. External results are assertions by an authorized caller, not independent proof of an external effect.

const (
	ToolLocal    ToolSource = "local"
	ToolExternal ToolSource = "external"
)

type Verifier

type Verifier interface {
	Verify(context.Context, Request) (Report, error)
}

Verifier evaluates a captured candidate without rerunning the original task. Implementations must reauthorize resource reads and host-stamp report times.

func NewVerifier

func NewVerifier(registrations []Registration, authorizer BindingAuthorizer, clock Clock) (Verifier, error)

NewVerifier freezes typed registrations and enforces host identity and timing. Semantic and policy adapters may implement Verifier directly, subject to the same report validation and current-binding checks at the commit boundary.

Jump to

Keyboard shortcuts

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