optimization

package module
v1.10.3 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 30 Imported by: 0

README

Cortex optimization foundations

This module provides scoped experiment storage, metered model controllers, a host-started worker, artifact lifecycle coordination and usage recovery. You supply the host authority, model bindings and trial/evaluation handler. The complete optimization loop and application integrations are still being built.

Usage accounting

Construct NewLedgerMeter with your optimization repository, host authorizer and identity resolver. Each operation checks the caller's optimization.start grant for the experiment, resolves its original requester and checks that requester's current grant. Scope and cancellation survive identity resolution. Credentials stay in the host context.

Use Reserve to hold a conservative debit. It does not permit an external call. Call BeginCall at the provider boundary with the same reservation and a SHA-256 digest of the actual frozen request. Your trusted adapter must compute this binding; do not accept a digest supplied by an agent as proof of request content. The store commits the debit, dispatch marker and audit event together. Invoke the provider only after BeginCall succeeds and while the call context remains live.

Once a dispatch marker exists, the same call cannot receive another dispatch permission. An identical retry returns ErrUnknownAttempt; changed request content returns ErrConflict. A lost commit acknowledgment may mean the marker was saved. Reconcile the original operation before deciding whether a new attempt is allowed. A marker records that the operation may have started, not that the provider received it or completed it.

Use Settle for an authoritative receipt or an explicit uncertainty observation. Verify receipt provenance in your adapter. Unknown usage retains the reserved upper bound. A later authoritative receipt can reconcile that debit, and retrying the same receipt cannot refund it twice. Reported overruns remain in the ledger and stop subsequent dispatch, including calls with an earlier reservation.

The ledger enforces the current worker lease and experiment state inside each transaction. A cancelled or expired worker cannot bypass those checks by keeping an old meter instance. Cancellation after a dispatch commit returns an error and leaves the conservative debit in place.

Model calls

Use NewMeteredClient around your llm.Client, then supply it through engine.WithLLM. You provide the ledger meter, a conservative UsageEstimator and a configuration bound to the exact scope, experiment, attempt, operation and model revision. The estimator sees a detached copy of the actual request. It must include input tokens, the output cap and any frozen pricing in its bound. Give each logical call a durable key that survives retries.

The wrapper hashes the full request with that binding and whether the call is streaming. It commits dispatch before invoking your provider. Requests for a different scope or model, missing output caps and oversized request JSON fail before dispatch. Byte limits bound accepted JSON, not the provider's allocations. You still need to pin the provider's routing to the configured model revision.

Supply a ModelUsageReporter when your provider can establish authoritative usage. It receives accounting facts and request identity without prompt or output content. Verify the provider receipt and frozen pricing there. Without a reporter, token counts remain uncertain: the ledger retains the reservation and records any observed overrun. Invalid receipts, inconsistent counts and underreporting cannot release the debit. Reporting must not perform unmetered charged work.

Streaming closes and settles once at EOF or failure. Always close a stream you abandon. Closing cancels a blocked read, provided your provider honors context cancellation, and usage available during close is included in accounting. A settlement error remains an error when Cortex consumes the stream; it cannot be mistaken for EOF. Settlement uses the original caller context, so caller cancellation may leave the durable dispatch debit awaiting later reconciliation.

The wrapper is available for model and judge calls. The controller factory below uses it directly. Judge integration and tool accounting remain open.

NewTokenPricing supplies the Pricing port for a fixed model and price revision. You provide approved input and output rates in USD micro-units per million tokens, plus a fixed request charge. Each token category rounds upward independently. Arithmetic is exact, and a quote that exceeds the ledger's integer range fails. Explicit zero rates are supported. Quotes remain estimates, including zero quotes.

Use rates that bound every charge your provider can incur for that request. If token rates and a fixed fee cannot cover its billing model, supply another Pricing implementation. This adapter does not fetch prices or count tokens.

Artifact lifecycle

See artifact lifecycle for retained reads, deletion receipts and recovery scans. Artifact recovery and metering share the identity-resolution helper so both preserve the caller's scope, cancellation and deadline.

Request estimation

NewRequestEstimator computes a reservation from the actual request, including its messages, tools and positive output cap. Supply a local InputTokenCounter that covers the exact model revision, tokenizer and provider framing. Its Bounded flag is a host assertion that the result is an upper bound. An approximate token count or unknown model revision cannot authorize dispatch. The module does not bundle a provider tokenizer or use a generic characters-per-token heuristic.

The estimator checks scope, detaches the input, rejects negative or overflowing bounds, adds the output cap and quotes frozen pricing. Token-only experiments omit pricing. For priced experiments, the quote must identify the experiment's pricing revision and cover every billable category. Counting cannot make an unmetered charged request.

Controller and worker wiring

Construct these pieces in your host:

  1. Build NewControllerFactory with the repository, authorizer, identity resolver, model bindings and explicit input/output limits. Each ModelBinding supplies a provider, model revision, token counter, optional pricing and receipt reporter.
  2. Pass that factory to NewControllerPhaseHandler. It handles proposal, composition and reflection. Supply NewTrialPhaseHandler with your environment factory and evaluator for baseline, probe, validation and decision work. A missing handler returns ErrUnavailable for those phases.
  3. Build NewUsageRecovery with an authoritative receipt lookup provider, then supply it with the handler and host CallerIdentity to NewOptimizer.
  4. Use Create with a host-frozen ExperimentBundle, then Start. The host owns evaluator freezing before creation. Run Work with an exact scoped context, or call WorkOnce to execute one phase step. Cancel the context on shutdown.

The model controller resolves immutable controller content and exact model bindings. It checks the baseline, round, edit policy and frozen lessons. Discovery trials, evaluations and candidates must match stored records. Artifacts from every execution attempt must remain eligible. Held-out evidence is refused before a model call. Returned JSON is strict and bounded, and accepted edits pass the existing edit-policy validator. Controller versions with tools return ErrUnavailable until a metered tool executor exists.

The worker claims one experiment at a time per instance, renews its lease and rechecks current authority during execution. Different instances receive unique owners. Pause, Resume and Cancel use revision checks; resume preserves the original phase and deadline. Persisted pause or cancellation invalidates the lease immediately, and the next heartbeat cancels active work. Handlers and providers must honor context cancellation and perform their own environment cleanup. A budget error commits budget_exhausted. Other execution errors leave durable state for recovery and return to the host supervisor.

Candidate versions and phase advancement commit together. Reflection queues lesson publications in the same transaction as completion or review. The worker does not publish to Fabriq or activate a winner. Those adapters remain separate.

Controller comparison scheduling

For a frozen controller comparison, wrap your child OptimizerConfig with NewImprovementPhaseHandler, then use that handler in the parent optimizer's config. The wrapper creates a separate child worker so the parent can keep renewing its lease while a child executes. Work polls top-level experiments; the parent schedules its children through WorkOnce.

Use CreateImprovementExperiment with an ImprovementEvaluator to qualify the parent and child plans before saving the draft. The scheduler creates children from those exact templates in stream order. Each child finishes discovery and saves its private reflection before the next child starts. Later tasks inherit only earlier reflections from their own controller arm.

Once every private reflection is recorded, the parent opens validation and freezes one allocation with each child's selected execution version. Retries and takeovers reuse that allocation. The parent reaches its decision phase only after both arms have captured all assigned validation outcomes. Unknown controller answers stop work, even if a late receipt has settled their cost. Paused children stay paused; an exhausted child exhausts the parent.

Set ImprovementEvaluator to an adapter implementing ControllerEvaluator to advance the parent through comparison. The Sentinel adapter reloads the original child captures and compares the selected execution versions across their frozen plans. The parent then rechecks the stored decision and enters StateReviewRequired. Finishing the comparison does not publish private discovery lessons or activate a controller.

ReadControllerEvidence and BuildControllerComparison assemble selected child captures into frozen plan groups. ValidateControllerDecisionEvidence checks their original experiment, execution and evaluation identities, then applies the same case arithmetic and selection rules used for execution-harness decisions. The store accepts controller decisions through CommitTransition and checks child artifact retention again before review. The parent worker rechecks every child's authority after comparison and validates the report before returning its transition. Missing scores produce an inconclusive decision.

Late receipts and takeover

UsageRecovery.Recover checks the caller and original requester's current optimization.usage.reconcile grant before and after receipt retrieval. Your UsageReceiptProvider must verify provenance and return the exact durable request digest, experiment, attempt, call key, receipt and authoritative usage. It looks up an existing operation; it cannot execute another one. Supply an actor obtained from host authentication, never from model output.

Recovery uses Transaction.ReconcileUsage without an execution lease. It works after cancellation or lease expiry, uses the reservation revision to fence races, and cannot change experiment state or execution authority. Repeating an identical receipt cannot refund twice. Unknown evidence retains the conservative debit.

Before takeover or resumption, the worker scans bounded reservation pages and reconciles unresolved dispatches, with a thirty-second lookup deadline per receipt. A reservation bound to a persisted trial attempt is retained for environment inspection by the trial handler. Its full debit remains until settlement. Other unresolved calls require verified receipt recovery before another phase runs. Accounting recovery does not recover a lost model response: a saved dispatch marker still returns ErrUnknownAttempt if the controller would repeat the call. Such cases need host reconciliation of the original output before the phase can advance.

Trial execution

Use NewTrialPhaseHandler for sequential, parallel and task-local experiments. You supply an EnvironmentFactory, Evaluator, repository, authorization ports and a TrialAllowance covering the entire trial. Your environment must enforce that allowance across model calls, tools and retrieval, along with the frozen step, output and time limits. A priced allowance must match the experiment's pricing revision. Capability flags are host guarantees. They don't qualify a sandbox.

Each worker step persists one boundary before advancing:

  1. Schedule the frozen case and repetition, then create its attempt.
  2. Open the environment idempotently and commit its receipt.
  3. Reserve usage and persist a dispatch marker before execution.
  4. Capture the result and confirmed containment receipt in one transition.
  5. Settle captured usage, score the stored output and commit the evaluation.

Every attempt gets a stable, separate session ID and the optimization execution purpose. After a lost response, the handler reconnects and inspects that same attempt. It never dispatches over an existing marker. An ambiguous inspection or stop keeps the attempt unresolved and its budget charged. Cancellation triggers bounded cleanup, and artifacts from earlier attempts must remain eligible before scoring or selection.

Probe scheduling covers accepted proposals and composed candidates within the frozen round and candidate limits. The finalist is chosen from complete discovery scores, with ties retaining the baseline. Validation pins that choice in a durable allocation and records exposure before executing the held-out cases. Sentinel supplies the paired statistics; Cortex checks the frozen selection thresholds and stored evidence before committing a decision for reflection and review.

You can run trials in sequential or parallel mode. Parallel mode admits at most Limits.Concurrency operations per step, counts unresolved attempts against that limit, and uses the same durable budget ledger. Calls overlap only after each has its own dispatch marker. The worker commits successful sibling results before returning a batch error, so you can resume uncertain work without replaying a completed call. Cancellation or lost authority leaves the batch recoverable.

You can bind the Sentinel implementation from github.com/xraph/cortex/sentinel/optimization; see its adapter guide.

Task-local refinement

Call OptimizeTask(ctx, TaskSpec{...}) with a frozen ExperimentBundle containing one discovery task, its baseline and controller versions, evaluation plan and host-approved budget. Supply the same trusted evaluator through OptimizerConfig.TaskEvaluator and TrialConfig.Evaluator. Cortex qualifies the plan before persisting work and again at each trial phase. Every criterion must explicitly support scoring without an expected answer.

TaskSpec.Isolation records the guarantees you require from each environment. The opened environment must satisfy every promised guarantee, including read-only access when requested. Omitted round and repetition counts default to one. The total timeout covers evaluator qualification and execution, and a shorter caller deadline is persisted as the experiment's absolute deadline. Caller cancellation attempts an authorized durable cancellation; failed cleanup is returned with the original error. Recursive calls from optimization trials, controllers and judges are refused.

The result returns a completed capture's output and artifacts, the decision and all trial outcomes, including failures and blocked probes. Selection preserves the baseline on a tie. Comparative cost gates require known execution charges at the frozen pricing revision and a positive baseline cost. Judge charges remain in the budget ledger separately. A selected task result is exploratory or contrastive evidence and cannot activate a global harness version.

Use GetTaskResult to retrieve a completed result after reconnecting. It rechecks current authority, retained artifacts and frozen lessons without executing the task again. Interrupted calls return the experiment ID when creation succeeded; your worker can reconcile unresolved attempts within the original deadline.

Artifact adoption is explicit. Bind WithArtifactAdopter and freeze an AdoptionPolicy in the task before calling AdoptArtifacts with the selected decision, trial, artifact subset, destination and idempotency key. Both the caller and original requester need the current adoption grant. A nil policy forbids adoption.

Your host adapter must enforce destination permissions and the pinned policy, read the exact artifact content, and atomically persist the key, request digest and receipt with its effects. An identical retry must reconcile the original commit; changed content under that key must conflict. Cortex validates the receipt and never retries host effects automatically. The integration tests use a receipt-producing host fixture; you still need a qualified destination adapter.

Production activation compatibility

Bind NewEngineCompatibility to the same production engine you pass to WithActiveEngine. You supply its deployed runtime revision and a host Compatibility implementation for current policy and external dependencies:

checker, err := optimization.NewEngineCompatibility(optimization.EngineCompatibilityConfig{
	Engine:         productionEngine,
	Host:           hostCompatibility,
	RuntimeVersion: deploymentRevision,
})
if err != nil {
	return err
}
config.Compatibility = checker
optimizer, err := optimization.NewOptimizer(config, optimization.WithActiveEngine(productionEngine))

The checker verifies the immutable version digest and scope, then checks host policy, current model/tool bindings and stored source records. Model and selected tool revisions must be pinned. Selected tools must still have executable implementations and matching schemas. Source records are read in one current store snapshot; a store without that capability returns unavailable. Approved prompt and tool-description edits retain their original source identity.

Activation, rollback, RunActive and RunActiveOrchestration check compatibility after reading artifact content, so a source edit during that read cannot authorize a stale version. Changed sources or runtime bindings require revalidation or deactivation. Deactivation remains available for a stale route. A checker bound to a different engine from RunActive is rejected during optimizer construction.

These are point-in-time checks and make no model or tool calls. Your host still owns current grants, policy, remote provider routing and external knowledge revisions. It must return incompatible when it cannot establish those bindings.

Controller comparison creation

Use CreateImprovementExperiment with an ImprovementSpec containing your frozen parent bundle. Set OptimizerConfig.ImprovementEvaluator to the Sentinel adapter that owns those plans. Creation qualifies each distinct plan, checks permission to create the parent and every child, and repeats those checks after external qualification. It returns a saved draft. Workers start separately.

You can persist an ImprovementPlan with two pinned controller versions and ordered pairs of complete child templates. A child's ParentExperiment binds its arm and sequence. Creating a child requires the current parent lease, and both controller arms consume the parent's aggregate token and money budget. Late receipts update the original reservations, including after cancellation.

Wrap your child handler with NewImprovementPhaseHandler and supply the Sentinel adapter as OptimizerConfig.ImprovementEvaluator. The parent schedules the frozen child stream, isolates discovery lessons by controller arm and allocates paired validation once. Its decision phase compares the selected child captures across their frozen plans, rechecks child authority and persists a controller decision. Missing scores produce an inconclusive result. Comparison makes no model calls.

The parent advances through comparison to review without another controller call. Ordinary trial phase handlers return ErrUnavailable for comparison parents.

Reviewed controller adoption

Set ActivationRequest.Kind to HarnessImprovement to adopt a reviewed controller recommendation. Use that kind for rollback and deactivation too. Controller routes have their own generation and history for each scope, agent and channel. An omitted kind retains execution-route behavior, including existing persisted activations. GetActivation and ListActivationHistory read execution routes; their ForKind variants accept an explicit kind. RunActive never resolves a controller route.

Supply OptimizerConfig.ControllerCompatibility separately from execution compatibility. NewControllerCompatibility checks the same ControllerFactory used by your worker, including the frozen model revision and supported tools. Its host checker must verify current policy and external provider routing. Checks make no model calls. Adoption and resolution also recheck parent and child grants, retained child artifacts and the original decision evidence.

Use ResolveActiveController when preparing new work. Put the returned selection.Activation.Version into bundle.Experiment.Spec.Controller before calling Create. The returned selection is detached; a later route change does not rewrite an existing experiment. Hosts authorize resolution with optimization.resolve_controller on controller_activation and on the source parent and child experiments. Activation, rollback and deactivation keep their existing actions and use the controller_activation resource kind.

Approved orchestration preset contracts

Use SealOrchestrationPreset to freeze each approved team with its shared token, step, tool-call and fan-out ceilings. Prepare every participant with explicit budgets first, including any aggregator or judge. Guidance names the existing, unlocked participant sections the host permits editing. The preset digest binds that allowlist, the prepared team and its ceilings.

Place the sealed catalog in EditPolicy.OrchestrationPresets and select its initial entry through HarnessVersion.Orchestration. A proposal with EditOrchestrationPreset and a preset name in Target selects another entry. The catalog stays fixed in the policy digest. Team policies reject agent-level edit fields, and every preset must retain the version's exact scope and include its owning agent. Normal agent versions keep their existing digest format.

Use EditParticipantGuidance with Participant, the section ID in Target, and its replacement body in Text. Only sections declared in that preset's Guidance allowlist can change. A preset selection and its guidance edits can share one proposal. Selecting a preset clears the previous selection's overrides. Restoring an original body removes its override and restores its content identity.

Every candidate is rebuilt from the original approved preset. Sealing checks the declared overrides against that result, so a derived snapshot cannot carry undeclared tool, sampling, budget or scope changes. The policy catalog stays fixed.

TrialPhaseHandler dispatches teams through the optional OrchestrationTrialEnvironment. The adapter receives the selected frozen team, a stable orchestration ID for the attempt, the trial purpose and provenance, and a shared policy bounded by the approved preset. The configured trial token allowance must cover that preset. The runtime creates isolated child sessions; the host remains responsible for isolating the environment and external effects. Unsupported adapters and monetary team trials fail before a charged call begins.

CaptureOrchestration reads a terminal team from the host's runtime store. It retains the original team ID, closed account, every reservation and available terminal child capture. Missing captures on a failed team remain explicit. The helper makes no execution or resume calls. Pass a store whose scope, isolation and usage-receipt authentication the host has already established.

OrchestrationChildUsage and OrchestrationUsage read original settlements. Reserved capacity is never measured usage. Missing dimensions stay unknown; overflow saturates the aggregate and marks that dimension unknown while keeping the original receipts. Current token-only teams do not claim known monetary cost. Sentinel receives the original team output and child run, step, tool, reservation and settlement references. Partial execution cannot produce a complete evaluation.

Recovery uses the same environment receipt and original captured team. It does not dispatch another team after a call has been recorded. Store writes bind the capture to the frozen version and reject reused parent or child run identities. Retention and task-result reads include child artifacts from prior attempts.

Use RunActiveOrchestration for a reviewed team activation:

result, err := optimizer.RunActiveOrchestration(ctx, optimization.ActiveOrchestrationRequest{
	AgentID: ownerID,
	Channel: "default",
	Input:   "Review this change",
})

You bind the same production engine through WithActiveEngine and EngineCompatibility. The checker reads the original orchestration config and all participant sources in one current snapshot, including participants whose guidance was derived from an approved preset.

The invocation pins its activation at entry, then checks retained evidence, compatibility and current route and experiment grants. A later deactivation blocks the next invocation. Production children use normal execution purpose, fresh sessions and the reviewed version's provenance. Shared limits and each participant's digest come from the approved preset; callers cannot override them. The caller's deadline can shorten the frozen participant deadlines. An expired preset requires a fresh version.

RunActive remains the agent execution path and returns ErrUnavailable for team versions. Current presets support token ceilings. Monetary team ceilings and messaging tools require further runtime support.

Operator resource reads

Use the optimizer's read methods when you expose experiments through an API or review UI. ListExperiments, ListCandidates, ListTrials, GetComparison, ListVersions, ListLessons, ListPublications and ListActivations return a ResourcePage with items, next_cursor and complete. Pages default to 25 records and reject limits above 100. complete describes pagination, not the experiment's execution state.

GetCandidate and GetTrial require the parent experiment ID as well as the resource ID. Reads check the current caller and resource grants in the exact scope. A denied item fails the page without returning a partial result. An empty configured scope returns an empty array and complete: true.

Use ListEvents for reconnects. Its opaque cursor binds the exact scope and experiment, and continues after the last returned event sequence. Keep that cursor separate from the repository's internal sequence cursor.

These methods read existing records. They do not run models, evaluate trials or activate versions. Evaluation, trial and optimization-controller execution contexts cannot use the operator read path to access private evidence. The existing Get and List methods use the same checks; List retains its original response type and uses the operator page limits.

Pass api.WithOptimization(optimizer) when you construct the REST API. Read routes live under /v1/optimization: experiments, their candidates, trials, comparison and events, plus versions, lessons, publications and activation history. The host must supply the optimizer's authenticated caller and current authorizer. Responses disable HTTP caching and use fixed public failure codes.

For the Forge dashboard, use extension.WithOptimization(optimizer) or set contract.Deps.Optimization. The extension option takes precedence and works with either ordering of WithDashboard. These read intents require cortex.optimization.read as well as the optimizer's host grants. Broader Cortex read, manage and run permissions do not grant optimization access. Both transports share the types and parsing in optimization/operator; neither starts a worker. The host still owns worker scopes and shutdown.

Lifecycle command recovery

Use StartCommand, CancelCommand and ResumeCommand for operator requests. Each takes a CommandRequest with the experiment ID, expected revision and a caller-supplied idempotency key. Keep that key when retrying a lost response. Keys are bound to the action, revision and authenticated actor within the exact scope and experiment; changed content returns a conflict. They are hashed before persistence and kept separate from worker and legacy host transition keys.

Start queues a draft; Resume queues a paused experiment. Neither runs a model or worker in the request. An identical retry returns the experiment's current state without another transition or event, even after a later cancellation. Current grants still apply to retries. After resolving the original requester, the service checks the operator's identity and grant again before committing.

The existing Start, Cancel, Pause and Resume methods retain their generated keys for host callers. Both command paths refuse evaluation, optimization trial and optimization controller execution contexts.

REST lifecycle commands use POST /v1/optimization/experiments/:id/start, /cancel and /resume. Send expected_revision in JSON and exactly one Idempotency-Key header. The URL determines the experiment; a body id cannot redirect the command. A body idempotency_key cannot supply a missing header.

Dashboard intents are optimization.experiments.start, .cancel and .resume. Send id and expected_revision in the payload and keep the key in the command envelope. These intents require cortex.optimization.run, the optimizer's current host grants and a durable Deps.Audit recorder. They bypass Forge's generic response cache so every retry reaches the optimizer's durable receipt and current authorization checks. Successful responses invalidate experiment, trial, comparison and event queries.

If the command commits but its audit outcome cannot be saved, the dashboard returns an unavailable error with command_attempted: true. Retry the same key and payload after audit recovery. The optimizer returns current state without repeating the transition. Missing audit configuration fails before a mutation.

The shared operator.Commands adapter also provides Activate, Rollback and Deactivate. Pass the envelope key separately from ActivateInput, RollbackInput or ActivationRouteInput. The adapter derives a stable activation ID from the exact scope and key. It does not derive identity from the payload or action, so reusing a key for another reviewer, route, action or expected generation fails against the stored receipt. Raw keys are not persisted.

Activation responses are immutable command receipts. Read activation history to find the current generation after a retry; an older receipt does not mean its version is still active. Activation and rollback recheck current grants, retained evidence and compatibility on retries. Deactivation still works when old evidence is unavailable. Private trial, evaluation and controller execution contexts cannot change or resolve production routes, and a reviewer identity change during activation admission fails before commit.

REST exposes POST /v1/optimization/activations/activate, /rollback and /deactivate, with the key in Idempotency-Key. Send agent_id, reason and expected_generation; zero means that no route generation exists yet. Omit channel to use default and kind to use an execution route. Activate also requires version_id, version_digest and decision_id. Rollback requires the historical activation's target_id.

The corresponding dashboard intents are optimization.activations.activate, .rollback and .deactivate. Each requires cortex.optimization.activate and the host's current resource grants. Other Cortex permissions do not grant activation. These commands use the same durable audit and envelope-key handling as lifecycle commands. Successful receipts invalidate activation history, versions, experiment detail, capabilities and events so the review view refreshes current state.

Approved creation catalogs

Use NewApprovedCatalog when your host registers approved agents, evaluation plans, controller versions and environment presets. Each CatalogChoice names its exact scope, kind, immutable ContentRef and display metadata. Registration copies the choices and rejects duplicate source revisions. Prompt bodies, private evaluation cases, credentials and executable policy stay out of catalog entries.

Supply an Authorize callback that checks the current caller's source access. For evaluation choices, resolve your Cortex scope to Sentinel and check the mapped evaluation grant. Return optimization.ErrPolicyDenied to exclude a choice from discovery. Other errors fail the read, so an outage cannot look like an empty catalog. The callback receives a detached choice and scoped context.

Your Prepare callback freezes the selected revisions into an ExperimentBundle. It owns policy, compatible combinations, source snapshots and host bounds. It must use the target experiment ID, scope and requester, honor cancellation and avoid running trials or starting background work. Leaving it unset supports a read-only catalog; preparation then returns unavailable.

Pass the same registry to OptimizerConfig.Catalog and OptimizerConfig.CreationCatalog. Operator callers use ListCatalog to discover choices and CreateCommand to save a draft. Creation checks every registered revision again. An identical retry recovers its original frozen draft under current permissions, without calling Prepare a second time.

Catalog queries accept an optional kind (agent, evaluation, controller or environment), limit and cursor. Pages default to 25 items and cap at 100. Transport cursors bind scope, caller and kind; they grant no access. A registry cursor also binds the currently visible registrations. If those registrations or grants change, restart pagination after the returned conflict. Missing catalog configuration is unavailable; an installed catalog with no permitted choices returns an empty, complete page. No total is inferred from pagination.

REST exposes GET /v1/optimization/catalog. The dashboard query is optimization.catalog, with the independent cortex.optimization.read grant. Both accept the shared catalog input and recheck source permissions on each request. REST responses use no-store.

Documentation

Overview

Package optimization manages versioned harness experiments through Cortex's execution engine. Evaluation, isolation and lesson storage are host adapters.

Index

Constants

View Source
const (
	PrefixHarness    id.Prefix = "harn"
	PrefixVersion    id.Prefix = "hrev"
	PrefixExperiment id.Prefix = "oexp"
	PrefixCandidate  id.Prefix = "ocan"
	PrefixTrial      id.Prefix = "otrl"
	PrefixDecision   id.Prefix = "odec"
	PrefixLesson     id.Prefix = "oles"
	PrefixEvent      id.Prefix = "oevt"
	PrefixActivation id.Prefix = "oact"
	PrefixAttempt    id.Prefix = "oatt"
	PrefixValidation id.Prefix = "oval"
)

Entity prefixes belong to this module and do not extend the root registry.

Variables

View Source
var (
	ErrInactiveActivation = errors.New("cortex: optimization: activation is disabled")
	ErrInvalidSpec        = errors.New("cortex: optimization: invalid specification")
	ErrPolicyDenied       = errors.New("cortex: optimization: edit denied by policy")
	ErrConflict           = errors.New("cortex: optimization: conflicting revision or content")
	ErrNoEnvironment      = errors.New("cortex: optimization: no trial environment")
	ErrUnavailable        = errors.New("cortex: optimization: capability unavailable")
	ErrBudgetExceeded     = errors.New("cortex: optimization: budget exceeded")
	ErrUnknownAttempt     = errors.New("cortex: optimization: attempt outcome unknown")
	ErrStaleVersion       = errors.New("cortex: optimization: stale version")
	ErrIncompleteEvidence = errors.New("cortex: optimization: incomplete evidence")
	ErrNotFound           = errors.New("cortex: optimization: resource not found")
)

Stable errors let adapters distinguish refusal, conflict and unavailable evidence.

Functions

func ActivationChannel

func ActivationChannel(channel string) (string, error)

ActivationChannel resolves the default and validates a bounded channel name.

func CanonicalVersion

func CanonicalVersion(version HarnessVersion) ([]byte, error)

CanonicalVersion encodes behavior, policy and provenance without row identities, timestamps or display names. The prepared digest binds its original wire bytes.

func CriterionFailureKey

func CriterionFailureKey(caseID string, repetition int, criterionID string) string

CriterionFailureKey identifies the required criterion that failed in one trial. A byte-length prefix preserves case IDs and criterion IDs containing separators.

func DiscoveryLessonsDigest

func DiscoveryLessonsDigest(value DiscoveryLessons) (string, error)

DiscoveryLessonsDigest binds content to its source controller, task and timestamp.

func ExecutionCompleted

func ExecutionCompleted(record ExecutionRecord) bool

ExecutionCompleted distinguishes fully completed captures from partial team results. This describes execution completeness, not answer correctness.

func ExecutionRunIDs

func ExecutionRunIDs(record ExecutionRecord) []id.ID

ExecutionRunIDs includes the team and every original reserved child identity.

func LessonDigest

func LessonDigest(lesson Lesson) (string, error)

LessonDigest identifies the complete immutable publication payload.

func ParseID

func ParseID(value string, prefix id.Prefix) (id.ID, error)

ParseID validates both TypeID syntax and the expected entity kind.

func ResolveIdentity

func ResolveIdentity(ctx context.Context, resolver IdentityResolver, actor IdentityRef, scope cortex.Scope) (context.Context, context.CancelFunc, error)

ResolveIdentity rebuilds current host identity within the caller's exact scope without extending cancellation or deadline. It does not authorize an action; callers must check both the caller and resolved identity with their Authorizer. The returned cleanup function must be called when the operation finishes.

func ScopeKey

func ScopeKey(scope cortex.Scope) (string, error)

ScopeKey returns an unambiguous exact key supported by every Cortex backend.

func TrialEvidenceReady

func TrialEvidenceReady(trial Trial) bool

TrialEvidenceReady reports whether a terminal trial has the evidence needed for selection. Failed trials remain outcomes; missing evaluations do not.

func ValidOpaqueKey

func ValidOpaqueKey(value string) bool

ValidOpaqueKey bounds external job, report and accounting keys used in cursors. It preserves spelling while rejecting whitespace ambiguity and control bytes.

func ValidateActivationEvidence

func ValidateActivationEvidence(change ActivationChange, experiment Experiment, decision Decision, version HarnessVersion) error

ValidateActivationEvidence binds an activation to its immutable recommendation. Current authorization, retained artifacts and source compatibility belong to the service; satisfying this check alone does not enable active execution.

func ValidateControllerDecisionEvidence

func ValidateControllerDecisionEvidence(parent Experiment, allocation ValidationAllocation, decision Decision, children []ControllerEvidence) error

ValidateControllerDecisionEvidence checks a controller recommendation against original child captures. Statistical intervals remain the evaluator's responsibility.

func ValidateCreationBundle

func ValidateCreationBundle(selection CreationSelection, bundle ExperimentBundle) error

ValidateCreationBundle verifies the provider honored explicit public choices. Catalog-specific bounds and source revisions remain the catalog's authority.

func ValidateDecisionEvidence

func ValidateDecisionEvidence(experiment Experiment, decision Decision, evidence []DecisionEvidence) error

ValidateDecisionEvidence checks stored identities and arithmetic before publication. The service must obtain the comparison from its trusted evaluator and separately check artifact availability, current authorization and runtime qualification. Bootstrap statistics remain the evaluator's responsibility.

func ValidateExecutionVersion

func ValidateExecutionVersion(record ExecutionRecord, version HarnessVersion) error

ValidateExecutionVersion binds a sealed capture to its exact prepared version.

func ValidateLessonDraft

func ValidateLessonDraft(lesson Lesson) error

ValidateLessonDraft checks bounded reflection content before storage resolves evidence.

func ValidateSpec

func ValidateSpec(spec ExperimentSpec) error

ValidateSpec checks immutable references, task separation and finite bounds. It does not establish external dependency readiness or grant authorization.

func ValidateTaskDecision

func ValidateTaskDecision(experiment Experiment, decision Decision, evidence []DecisionEvidence) error

ValidateTaskDecision rejects fabricated selection, scores or missing outcomes.

func ValidateTrialCapabilities

func ValidateTrialCapabilities(c IsolationCapabilities, reproducible bool) error

ValidateTrialCapabilities refuses environments without required host guarantees.

Types

type Action

type Action string

Action names the host permission required at an operation boundary.

const (
	ActionRetain            Action = "optimization.retain"
	ActionRead              Action = "optimization.read"
	ActionCreate            Action = "optimization.create"
	ActionStart             Action = "optimization.start"
	ActionCancel            Action = "optimization.cancel"
	ActionResume            Action = "optimization.resume"
	ActionReconcileUsage    Action = "optimization.usage.reconcile"
	ActionRunActive         Action = "optimization.run_active"
	ActionDeactivate        Action = "optimization.deactivate"
	ActionActivate          Action = "optimization.activate"
	ActionResolveController Action = "optimization.resolve_controller"
	ActionRollback          Action = "optimization.rollback"
	ActionPublishLesson     Action = "optimization.lesson.publish"
	ActionRevokeLesson      Action = "optimization.lesson.revoke"
	ActionRetryPublication  Action = "optimization.lesson.retry"
	ActionReadArtifact      Action = "optimization.artifact.read"
	ActionAdoptArtifacts    Action = "optimization.artifact.adopt"
	ActionDelete            Action = "optimization.delete"
)

type Activation

type Activation struct {
	Kind               HarnessKind  `json:"kind,omitempty"`
	Deactivated        bool         `json:"deactivated,omitempty"`
	Reason             string       `json:"reason,omitempty"`
	RollbackTo         id.ID        `json:"rollback_to,omitempty"`
	ID                 id.ID        `json:"id"`
	Scope              cortex.Scope `json:"scope"`
	AgentID            id.AgentID   `json:"agent_id"`
	Channel            string       `json:"channel"`
	Version            VersionRef   `json:"version"`
	Generation         int64        `json:"generation"`
	ExpectedGeneration int64        `json:"expected_generation"`
	Actor              IdentityRef  `json:"actor"`
	PolicyDigest       string       `json:"policy_digest"`
	DecisionID         id.ID        `json:"decision_id"`
	CreatedAt          time.Time    `json:"created_at"`
}

Activation is an append-only generation for an exact scope, agent and channel.

type ActivationChange

type ActivationChange struct {
	Kind               HarnessKind `json:"kind,omitempty"`
	Reason             string      `json:"reason,omitempty"`
	ID                 id.ID       `json:"id"`
	AgentID            id.AgentID  `json:"agent_id"`
	Channel            string      `json:"channel"`
	Version            VersionRef  `json:"version"`
	ExpectedGeneration int64       `json:"expected_generation"`
	Actor              IdentityRef `json:"actor"`
	PolicyDigest       string      `json:"policy_digest"`
	DecisionID         id.ID       `json:"decision_id"`
	RollbackTo         id.ID       `json:"rollback_to,omitempty"`
}

ActivationChange records an explicit review command. The ID is its retry key; scope and creation time come from the transaction, and generation is assigned by the store. The service must recheck current grants and evidence availability.

type ActivationQuery

type ActivationQuery struct {
	PageQuery
	AgentID id.AgentID  `json:"agent_id"`
	Channel string      `json:"channel,omitempty"`
	Kind    HarnessKind `json:"kind,omitempty"`
}

ActivationQuery selects an owner's independent execution or controller route.

type ActivationRequest

type ActivationRequest struct {
	Kind               HarnessKind `json:"kind,omitempty"`
	ID                 id.ID       `json:"id"`
	AgentID            id.AgentID  `json:"agent_id"`
	Channel            string      `json:"channel"`
	Version            VersionRef  `json:"version"`
	DecisionID         id.ID       `json:"decision_id"`
	ExpectedGeneration int64       `json:"expected_generation"`
	Reason             string      `json:"reason"`
}

ActivationRequest identifies a reviewed version and the expected route generation.

type ActiveControllerRequest

type ActiveControllerRequest struct {
	AgentID id.AgentID `json:"agent_id"`
	Channel string     `json:"channel"`
}

ActiveControllerRequest identifies the reviewed route used to start new work.

type ActiveOrchestrationRequest

type ActiveOrchestrationRequest struct {
	AgentID id.AgentID `json:"agent_id"`
	Channel string     `json:"channel"`
	Input   string     `json:"input"`
}

ActiveOrchestrationRequest carries input for an explicitly reviewed team route. Shared capacity and participant settings come from its frozen approved preset.

type ActiveRunRequest

type ActiveRunRequest struct {
	AgentID   id.AgentID   `json:"agent_id"`
	Channel   string       `json:"channel"`
	Input     string       `json:"input"`
	SessionID id.SessionID `json:"session_id,omitempty"`
}

ActiveRunRequest carries normal production input for an explicitly active route. The caller cannot override its prepared configuration or execution purpose.

type ApprovedCatalog

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

ApprovedCatalog shares a detached registration between listing and creation. Rebuild it to publish new registrations. Pagination detects changed visible revisions instead of mixing old and new catalog content across pages.

func NewApprovedCatalog

func NewApprovedCatalog(config ApprovedCatalogConfig) (*ApprovedCatalog, error)

NewApprovedCatalog validates and freezes up to ten thousand host choices.

func (*ApprovedCatalog) Authorize

func (c *ApprovedCatalog) Authorize(ctx context.Context, selection CreationSelection) error

Authorize checks all selected revisions, including mapped evaluation access.

func (*ApprovedCatalog) AuthorizeChoice

func (c *ApprovedCatalog) AuthorizeChoice(ctx context.Context, choice CatalogChoice) error

AuthorizeChoice requires an exact registered revision in the context scope.

func (*ApprovedCatalog) List

List reads currently authorized registrations. A source outage is an error, while an ordinary source permission denial removes that choice from discovery.

func (*ApprovedCatalog) Prepare

Prepare delegates freezing only after authorizing registered source revisions.

type ApprovedCatalogConfig

type ApprovedCatalogConfig struct {
	Choices   []CatalogChoice
	Authorize func(context.Context, CatalogChoice) error
	Prepare   func(context.Context, CreationTarget) (ExperimentBundle, error)
}

ApprovedCatalogConfig registers immutable choices with current host access. Authorize checks each source's grants using the supplied context. Prepare is optional for read-only catalogs; it freezes host policy and executable content for an authorized selection and must not run trials or start background work.

type Artifact

type Artifact struct {
	Ref       ArtifactRef `json:"ref"`
	Data      []byte      `json:"data"`
	CreatedAt time.Time   `json:"created_at"`
	ExpiresAt time.Time   `json:"expires_at"`
}

Artifact carries bytes and the requested retention policy to an authorized store.

func (Artifact) Validate

func (artifact Artifact) Validate() error

Validate checks immutable content and a finite retention interval. Whether the artifact is currently retained and authorized requires a fresh provider read.

type ArtifactAdopter

type ArtifactAdopter interface {
	AdoptArtifacts(context.Context, ArtifactAdoption) (ArtifactAdoptionReceipt, error)
}

ArtifactAdopter enforces current destination grants and the pinned host policy. It must read exact artifact content, persist key/digest/receipt atomically with its effects, reconcile retries, and report unknown outcomes without replay.

type ArtifactAdoption

type ArtifactAdoption struct {
	Request       ArtifactAdoptionRequest `json:"request"`
	Actor         IdentityRef             `json:"actor"`
	Scope         cortex.Scope            `json:"scope"`
	RequestDigest string                  `json:"request_digest"`
}

ArtifactAdoption binds the authorized caller and exact scope to host effects.

type ArtifactAdoptionReceipt

type ArtifactAdoptionReceipt struct {
	ID            string     `json:"id"`
	RequestDigest string     `json:"request_digest"`
	Evidence      ContentRef `json:"evidence"`
	AdoptedAt     time.Time  `json:"adopted_at"`
}

ArtifactAdoptionReceipt is the host's durable commit evidence, not a trial run.

type ArtifactAdoptionRequest

type ArtifactAdoptionRequest struct {
	Key          string        `json:"key"`
	ExperimentID id.ID         `json:"experiment_id"`
	DecisionID   id.ID         `json:"decision_id"`
	TrialID      id.ID         `json:"trial_id"`
	Destination  ContentRef    `json:"destination"`
	Policy       ContentRef    `json:"policy"`
	Artifacts    []ArtifactRef `json:"artifacts"`
}

ArtifactAdoptionRequest explicitly names a destination and selected artifacts. Key is a durable host idempotency key; changed content must conflict on retry.

type ArtifactDeletion

type ArtifactDeletion struct {
	Ref       ArtifactRef `json:"ref"`
	RequestID string      `json:"request_id"`
	Actor     IdentityRef `json:"actor"`
	Reason    string      `json:"reason"`
}

ArtifactDeletion permanently withdraws one protected reference. The service checks current delete authority before requesting or completing deletion.

type ArtifactReader

type ArtifactReader interface {
	Get(context.Context, ArtifactRef) (Artifact, error)
}

ArtifactReader must enforce current host grants and exact scope on every read. Implementations must bound allocations before fetching content. The verifier checks returned bytes, but cannot control allocations inside an injected reader.

type ArtifactRef

type ArtifactRef struct {
	ExperimentID id.ID        `json:"experiment_id"`
	Scope        cortex.Scope `json:"scope"`
	Digest       string       `json:"digest"`
	MediaType    string       `json:"media_type"`
	Size         int64        `json:"size"`
	AccessPolicy string       `json:"access_policy"`
	Kind         string       `json:"kind"`
}

ArtifactRef identifies protected content without embedding it in event payloads.

func ExecutionArtifactRefs

func ExecutionArtifactRefs(record ExecutionRecord) []ArtifactRef

ExecutionArtifactRefs includes captured child artifacts and parent evidence.

func TrialArtifactRefs

func TrialArtifactRefs(trial Trial) []ArtifactRef

TrialArtifactRefs includes evidence from every attempt, including superseded executions.

func (ArtifactRef) BindingDigest

func (ref ArtifactRef) BindingDigest() (string, error)

BindingDigest binds content identity to its scope, media type, kind and policy. Equal byte digests alone do not make two protected references interchangeable.

func (ArtifactRef) Validate

func (ref ArtifactRef) Validate() error

Validate checks the complete protected identity, without claiming availability.

type ArtifactRegistration

type ArtifactRegistration struct {
	Ref       ArtifactRef `json:"ref"`
	CreatedAt time.Time   `json:"created_at"`
	ExpiresAt time.Time   `json:"expires_at"`
	Actor     IdentityRef `json:"actor"`
	Lease     WorkLease   `json:"lease"`
}

ArtifactRegistration records already verified content under the worker lease. Services must verify provider content before registering it. No bytes or access credentials belong in this transaction.

type ArtifactRetention

type ArtifactRetention struct {
	Ref           ArtifactRef       `json:"ref"`
	CreatedAt     time.Time         `json:"created_at"`
	ExpiresAt     time.Time         `json:"expires_at"`
	RegisteredAt  time.Time         `json:"registered_at"`
	RegisteredBy  IdentityRef       `json:"registered_by"`
	Revision      int64             `json:"revision"`
	Deletion      *ArtifactDeletion `json:"deletion,omitempty"`
	InvalidatedAt time.Time         `json:"invalidated_at"`
	DeletedAt     time.Time         `json:"deleted_at"`
}

ArtifactRetention preserves immutable identity and deletion progress. Revision one is registered, two is ineligible pending deletion, and three is deleted.

type ArtifactStore

type ArtifactStore interface {
	ArtifactReader
	Put(context.Context, Artifact) (ArtifactRef, error)
	Delete(context.Context, ArtifactRef) error
}

ArtifactStore persists content-addressed bytes under explicit access policy.

type ArtifactVerifier

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

ArtifactVerifier checks freshly retrieved evidence before a service decision. Verification is a point-in-time observation, not a retention lease or an atomic decision fence. Services must also coordinate deletion with persisted eligibility.

func NewArtifactVerifier

func NewArtifactVerifier(reader ArtifactReader, maxBytes int64, now func() time.Time) (*ArtifactVerifier, error)

NewArtifactVerifier requires an authorized reader, a byte limit and a clock.

func (*ArtifactVerifier) Verify

func (v *ArtifactVerifier) Verify(ctx context.Context, experimentID id.ID, ref ArtifactRef) (Artifact, error)

Verify returns detached content only when its complete reference, experiment, digest and retention interval match. Provider refusals remain inspectable while also marking the required evidence incomplete.

type Attempt

type Attempt struct {
	ID            id.ID               `json:"id"`
	State         TrialState          `json:"state"`
	Revision      int64               `json:"revision"`
	Receipt       *EnvironmentReceipt `json:"receipt,omitempty"`
	Fence         Fence               `json:"fence"`
	Stop          *StopReceipt        `json:"stop,omitempty"`
	Replaces      id.ID               `json:"replaces,omitempty"`
	RetryApproval *ContentRef         `json:"retry_approval,omitempty"`
	Execution     *ExecutionRecord    `json:"execution,omitempty"`
	StartedAt     time.Time           `json:"started_at"`
	CompletedAt   time.Time           `json:"completed_at"`
	Usage         Usage               `json:"usage"`
	Error         string              `json:"error,omitempty"`
}

Attempt preserves every external dispatch and its durable environment receipt.

type AttemptStatus

type AttemptStatus struct {
	AttemptID  id.ID            `json:"attempt_id"`
	State      TrialState       `json:"state"`
	Execution  *ExecutionRecord `json:"execution,omitempty"`
	ObservedAt time.Time        `json:"observed_at"`
}

AttemptStatus recovers the original result without dispatching another call.

type Authorizer

type Authorizer interface {
	Authorize(context.Context, Action, Resource) error
}

Authorizer evaluates current grants without trusting serialized model output.

type Budget

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

Budget separates token-only execution from a priced monetary ceiling.

type CallMeter

type CallMeter interface {
	Meter
	BeginCall(context.Context, UsageReservation, string) (Reservation, error)
}

CallMeter reserves usage and records dispatch before an external operation. Only a successfully committed BeginCall permits a new provider invocation. Reserve alone does not grant dispatch permission.

type CallerIdentity

type CallerIdentity interface {
	Current(context.Context) (IdentityRef, error)
}

CallerIdentity attributes commands to the authenticated host caller.

type Candidate

type Candidate struct {
	ID               id.ID           `json:"id"`
	ExperimentID     id.ID           `json:"experiment_id"`
	Parents          []id.ID         `json:"parents"`
	Origin           CandidateOrigin `json:"origin"`
	Round            int             `json:"round"`
	Proposal         Proposal        `json:"proposal"`
	PredictedEffects []string        `json:"predicted_effects"`
	Version          VersionRef      `json:"version"`
	Accepted         bool            `json:"accepted"`
	Rejection        string          `json:"rejection,omitempty"`
	CreatedAt        time.Time       `json:"created_at"`
}

Candidate retains rejected proposals as well as executable frozen versions.

type CandidateOrigin

type CandidateOrigin string

CandidateOrigin distinguishes proposed instructions from executed composition.

const (
	OriginGeneral  CandidateOrigin = "general"
	OriginDomain   CandidateOrigin = "domain"
	OriginComposed CandidateOrigin = "composed"
)

type Capability

type Capability string

Capability names a separately checked host integration.

const (
	CapabilityStorage           Capability = "storage"
	CapabilityDurableStorage    Capability = "durable_storage"
	CapabilityWorker            Capability = "worker"
	CapabilityController        Capability = "controller"
	CapabilityEnvironment       Capability = "trial_environment"
	CapabilityEvaluation        Capability = "evaluation"
	CapabilityAccounting        Capability = "accounting"
	CapabilityScopeMapping      Capability = "scope_mapping"
	CapabilityLessons           Capability = "lessons"
	CapabilityPublication       Capability = "publication"
	CapabilityProductionRouting Capability = "production_routing"
	CapabilityControllerRouting Capability = "controller_routing"
)

func CapabilityNames

func CapabilityNames() []Capability

CapabilityNames returns the bounded readiness vocabulary in display order.

type CapabilityProbe

type CapabilityProbe interface {
	Inspect(context.Context, CapabilityTarget) (HostCapabilities, error)
}

CapabilityProbe inspects installed workers, mapped providers and environment guarantees without starting work or writing remote state. Implementations must honor cancellation and current host grants. Checks apply only to Target.

type CapabilitySnapshot

type CapabilitySnapshot struct {
	HostCapabilities
	Permissions        map[Action]bool `json:"permissions"`
	EditableDimensions []EditKind      `json:"editable_dimensions"`
	TrialsReady        bool            `json:"trials_ready"`
	ObservedAt         time.Time       `json:"observed_at"`
}

CapabilitySnapshot separates readiness from current permission. TrialsReady concerns the selected frozen experiment's prerequisites, not its lifecycle, remaining budget or a promise that a later command will be authorized.

type CapabilityTarget

type CapabilityTarget struct {
	Scope        cortex.Scope `json:"scope"`
	ExperimentID id.ID        `json:"experiment_id,omitempty"`
	AgentID      id.AgentID   `json:"agent_id,omitempty"`
	Mode         Mode         `json:"mode,omitempty"`
	Baseline     VersionRef   `json:"baseline"`
	Controller   VersionRef   `json:"controller"`
	Evaluation   ContentRef   `json:"evaluation"`
}

CapabilityTarget binds host checks to the exact frozen experiment. A nil ExperimentID requests scope-level diagnostics and cannot establish trial readiness.

type CaseDelta

type CaseDelta struct {
	CaseID      string             `json:"case_id"`
	CaseDigest  string             `json:"case_digest"`
	Repetitions int                `json:"repetitions"`
	Delta       float64            `json:"delta"`
	Criteria    map[string]float64 `json:"criteria"`
}

CaseDelta averages repetitions within a case before statistical resampling.

type CatalogChoice

type CatalogChoice struct {
	Scope       cortex.Scope `json:"scope"`
	Kind        CatalogKind  `json:"kind"`
	Ref         ContentRef   `json:"ref"`
	Name        string       `json:"name"`
	Description string       `json:"description,omitempty"`
}

CatalogChoice contains display metadata and an immutable reference. Prompt bodies, evaluation cases, credentials and executable policy stay with the host.

type CatalogKind

type CatalogKind string

CatalogKind names one class of host-approved creation choices.

const (
	CatalogAgent       CatalogKind = "agent"
	CatalogEvaluation  CatalogKind = "evaluation"
	CatalogController  CatalogKind = "controller"
	CatalogEnvironment CatalogKind = "environment"
)

type CatalogProvider

type CatalogProvider interface {
	List(context.Context, CatalogTarget) (CatalogResult, error)
	AuthorizeChoice(context.Context, CatalogChoice) error
}

CatalogProvider lists approved references under current source permissions. List must filter unauthorized choices and return source failures as errors. AuthorizeChoice rechecks mapped source access, including Sentinel permissions. Both methods must honor context cancellation. Cursors must retain stable source revisions; changed registrations must not silently continue an older page.

type CatalogQuery

type CatalogQuery struct {
	PageQuery
	Kind CatalogKind `json:"kind,omitempty"`
}

CatalogQuery selects a bounded catalog page. An empty Kind includes all kinds.

type CatalogResult

type CatalogResult struct {
	Target CatalogTarget       `json:"target"`
	Page   Page[CatalogChoice] `json:"page"`
}

CatalogResult identifies the source request that produced its page.

type CatalogTarget

type CatalogTarget struct {
	Scope  cortex.Scope `json:"scope"`
	Actor  IdentityRef  `json:"actor"`
	Kind   CatalogKind  `json:"kind,omitempty"`
	Limit  int          `json:"limit"`
	Cursor string       `json:"cursor,omitempty"`
}

CatalogTarget binds a source read to the current exact scope and caller. Cursor belongs to the source; the operator service wraps it for transport.

type ClaimRequest

type ClaimRequest struct {
	ExperimentID id.ID         `json:"experiment_id"`
	Owner        string        `json:"owner"`
	Duration     time.Duration `json:"duration"`
}

ClaimRequest names one queued or expired experiment and the claiming worker.

type CommandRequest

type CommandRequest struct {
	ExperimentID     id.ID  `json:"experiment_id"`
	ExpectedRevision int64  `json:"expected_revision"`
	IdempotencyKey   string `json:"idempotency_key"`
}

CommandRequest identifies a lifecycle command independently of a connection. Reuse a key only with the same action, revision and authenticated actor for this experiment. Retries return its current state without another transition.

type Comparison

type Comparison struct {
	Plans                []ContentRef       `json:"plans,omitempty"`
	BaselineIDs          []string           `json:"baseline_ids"`
	CandidateIDs         []string           `json:"candidate_ids"`
	PlanDigest           string             `json:"plan_digest"`
	Cases                []CaseDelta        `json:"cases"`
	MeanDelta            float64            `json:"mean_delta"`
	LowerBound           float64            `json:"lower_bound"`
	UpperBound           float64            `json:"upper_bound"`
	Confidence           float64            `json:"confidence"`
	BootstrapSeed        uint64             `json:"bootstrap_seed"`
	BootstrapSamples     int                `json:"bootstrap_samples"`
	RequiredFailures     []string           `json:"required_failures"`
	ProtectedRegressions map[string]float64 `json:"protected_regressions"`
	CostRatio            *float64           `json:"cost_ratio,omitempty"`
	LatencyRatio         *float64           `json:"latency_ratio,omitempty"`
	Complete             bool               `json:"complete"`
	MissingReasons       []string           `json:"missing_reasons"`
}

Comparison reports evidence completeness separately from selection policy.

func BuildControllerInconclusive

func BuildControllerInconclusive(parent Experiment, allocation ValidationAllocation, children []ControllerEvidence) (*Comparison, error)

BuildControllerInconclusive preserves terminal failures without inventing scores. A nil result means every selected execution has a complete evaluation and the statistical evaluator must perform the comparison.

type ComparisonDetail

type ComparisonDetail struct {
	RetainedBaseline *RetainedBaseline        `json:"retained_baseline,omitempty"`
	ExperimentID     id.ID                    `json:"experiment_id"`
	Revision         int64                    `json:"revision"`
	Decision         *Decision                `json:"decision,omitempty"`
	Evaluations      ResourcePage[Evaluation] `json:"evaluations"`
}

ComparisonDetail keeps the immutable decision and a bounded page of original evaluation records. A missing decision means comparison has not been recorded.

type ComparisonRequest

type ComparisonRequest struct {
	Plan         EvaluationPlan `json:"plan"`
	BaselineIDs  []string       `json:"baseline_ids"`
	CandidateIDs []string       `json:"candidate_ids"`
	Objective    Objective      `json:"objective"`
}

ComparisonRequest pairs exact evidence IDs under the frozen objective.

type Compatibility

type Compatibility interface {
	Check(context.Context, HarnessVersion) (CompatibilityReport, error)
}

Compatibility checks current source, tool and host policy revisions. Hosts must return incompatible when any required revision cannot be established.

type CompatibilityReport

type CompatibilityReport struct {
	Version      VersionRef `json:"version"`
	PolicyDigest string     `json:"policy_digest"`
	Compatible   bool       `json:"compatible"`
}

CompatibilityReport binds a point-in-time observation to an exact version.

type CompositionInput

type CompositionInput struct {
	ProposalInput
	Candidates []Candidate `json:"candidates"`
}

CompositionInput combines executed candidates without inheriting their scores.

type ContentRef

type ContentRef struct {
	Ref      string `json:"ref"`
	Revision string `json:"revision"`
	Digest   string `json:"digest"`
}

ContentRef identifies a frozen external resource without carrying credentials.

func (ContentRef) Validate

func (ref ContentRef) Validate() error

Validate checks the complete identity of a frozen external resource.

type Controller

type Controller interface {
	Propose(context.Context, ProposalInput) ([]Proposal, error)
	Compose(context.Context, CompositionInput) (Proposal, error)
	Reflect(context.Context, ReflectionInput) ([]LessonDraft, error)
}

Controller proposes bounded edits and reflects only on eligible discovery data.

type ControllerComparisonGroup

type ControllerComparisonGroup struct {
	Plan         EvaluationPlan `json:"plan"`
	BaselineIDs  []string       `json:"baseline_ids"`
	CandidateIDs []string       `json:"candidate_ids"`
}

ControllerComparisonGroup preserves one frozen plan and the original job IDs.

type ControllerComparisonRequest

type ControllerComparisonRequest struct {
	ExperimentID id.ID                       `json:"experiment_id"`
	AllocationID id.ID                       `json:"allocation_id"`
	SpecDigest   string                      `json:"spec_digest"`
	Objective    Objective                   `json:"objective"`
	Groups       []ControllerComparisonGroup `json:"groups"`
}

ControllerComparisonRequest identifies a parent allocation and its scored groups.

func BuildControllerComparison

func BuildControllerComparison(parent Experiment, allocation ValidationAllocation, children []ControllerEvidence) (ControllerComparisonRequest, error)

BuildControllerComparison validates the frozen roster without rewriting child experiment IDs, execution versions or evaluation plans to resemble the parent.

type ControllerCompatibility

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

ControllerCompatibility verifies frozen controller bindings without model calls.

func NewControllerCompatibility

func NewControllerCompatibility(config ControllerCompatibilityConfig) (*ControllerCompatibility, error)

NewControllerCompatibility creates a checker for reviewed controller routes.

func (*ControllerCompatibility) Check

Check verifies scope, immutable content, supported tools and registered model revision before consulting the host's current policy and provider bindings.

type ControllerCompatibilityConfig

type ControllerCompatibilityConfig struct {
	Controllers *ControllerFactory
	Host        Compatibility
}

ControllerCompatibilityConfig binds activation to the same factory that executes controllers. Host checks current policy and external provider routes.

type ControllerEvaluator

type ControllerEvaluator interface {
	CompareControllers(context.Context, ControllerComparisonRequest) (Comparison, error)
}

ControllerEvaluator compares the selected executions of frozen controller arms. The adapter must reload authoritative evidence before computing statistics.

type ControllerEvidence

type ControllerEvidence struct {
	Experiment Experiment         `json:"experiment"`
	Trials     []DecisionEvidence `json:"trials"`
}

ControllerEvidence retains a child's actual identity and selected validation trials.

func ReadControllerEvidence

func ReadControllerEvidence(ctx context.Context, repo Repository, parent Experiment, allocation ValidationAllocation) ([]ControllerEvidence, error)

ReadControllerEvidence loads the selected child trials in the caller's scope. Callers must check current host authority for the parent and every child.

type ControllerFactory

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

ControllerFactory binds frozen controller versions to metered model calls. Tool-using controller versions are refused until a metered tool executor is supplied.

func NewControllerFactory

func NewControllerFactory(repo Repository, auth Authorizer, resolver IdentityResolver, bindings []ModelBinding, limits ControllerLimits) (*ControllerFactory, error)

NewControllerFactory installs explicit model bindings without network discovery.

func (*ControllerFactory) ForWork

func (f *ControllerFactory) ForWork(ctx context.Context, item WorkItem) (Controller, error)

ForWork resolves the frozen controller and refuses unsupported model revisions.

type ControllerLimits

type ControllerLimits struct{ MaxInputBytes, MaxResponseBytes, MaxOutputTokens, MaxProposals, MaxLessons int }

ControllerLimits bounds JSON input, output and decoded result counts.

type ControllerPhaseHandler

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

ControllerPhaseHandler executes proposal, composition and reflection through the metered controller. Other phases use the host's trial/evaluation handler.

func NewControllerPhaseHandler

func NewControllerPhaseHandler(repo Repository, models *ControllerFactory, trials PhaseHandler, domain string) (*ControllerPhaseHandler, error)

NewControllerPhaseHandler composes controller phases with existing trial work. A nil trial handler explicitly reports unavailable for non-controller phases.

func (*ControllerPhaseHandler) Execute

Execute returns a transition whose resources the worker commits atomically.

type ControllerSelection

type ControllerSelection struct {
	Activation Activation     `json:"activation"`
	Version    HarnessVersion `json:"version"`
}

ControllerSelection pins a reviewed activation and its immutable controller. Use Activation.Version in a new experiment before creation; running experiments keep their frozen controller when the route changes.

type ControllerSpec

type ControllerSpec struct {
	Model         string           `json:"model"`
	ModelRevision string           `json:"model_revision"`
	Sections      []prompt.Section `json:"sections"`
	Tools         []string         `json:"tools"`
	Temperature   float64          `json:"temperature"`
}

ControllerSpec freezes the model, instructions and tool names of an improver.

type CreationCatalog

type CreationCatalog interface {
	Authorize(context.Context, CreationSelection) error
	Prepare(context.Context, CreationTarget) (ExperimentBundle, error)
}

CreationCatalog authorizes selected revisions independently of preparation. Authorize must enforce current access to every selected source, including mapped evaluation access. Prepare returns immutable host-approved content and enforces host bounds. It must not execute trials or start background work.

type CreationCommand

type CreationCommand struct {
	Key       string
	Actor     IdentityRef
	Selection CreationSelection
	Bundle    ExperimentBundle
}

CreationCommand atomically persists a host-frozen draft and its input receipt.

type CreationReceipt

type CreationReceipt struct {
	Key          string            `json:"key"`
	Scope        cortex.Scope      `json:"scope"`
	Actor        IdentityRef       `json:"actor"`
	Selection    CreationSelection `json:"selection"`
	InputDigest  string            `json:"input_digest"`
	SpecDigest   string            `json:"spec_digest"`
	ExperimentID id.ID             `json:"experiment_id"`
	CreatedAt    time.Time         `json:"created_at"`
}

CreationReceipt retains the accepted request independently of mutable progress. Key is a digest namespace, never the caller's raw transport key.

func SealCreationReceipt

func SealCreationReceipt(receipt CreationReceipt) (CreationReceipt, error)

SealCreationReceipt validates identity and computes the canonical request digest.

type CreationRequest

type CreationRequest struct {
	Selection      CreationSelection `json:"selection"`
	IdempotencyKey string            `json:"idempotency_key"`
}

CreationRequest binds transport idempotency to public catalog choices.

type CreationSelection

type CreationSelection struct {
	Agent       ContentRef       `json:"agent"`
	Evaluation  ContentRef       `json:"evaluation"`
	Controller  ContentRef       `json:"controller"`
	Environment ContentRef       `json:"environment"`
	Mode        Mode             `json:"mode,omitempty"`
	Limits      *Limits          `json:"limits,omitempty"`
	Budget      *Budget          `json:"budget,omitempty"`
	Objective   *Objective       `json:"objective,omitempty"`
	TaskSplits  map[string]Split `json:"task_splits,omitempty"`
}

CreationSelection contains public catalog references and requested bounds. Prepared snapshots, rubrics, policies and caller identities are host-owned. Omitted bounds use the selected catalog revision's defaults.

type CreationTarget

type CreationTarget struct {
	Scope        cortex.Scope
	Actor        IdentityRef
	ExperimentID id.ID
	Selection    CreationSelection
}

CreationTarget assigns identity before host preparation so nested plans can bind their parent. Catalog implementations must freeze exactly Selection.

type CriterionDefinition

type CriterionDefinition struct {
	RequiresExpected *bool  `json:"requires_expected,omitempty"`
	ID               string `json:"id"`
	Required         bool   `json:"required"`
}

CriterionDefinition freezes the expected result roster and required gates.

type CriterionValue

type CriterionValue struct {
	ID       string   `json:"id"`
	Score    *float64 `json:"score,omitempty"`
	Required bool     `json:"required"`
	Passed   bool     `json:"passed"`
	Error    string   `json:"error,omitempty"`
}

CriterionValue keeps scorer failure separate from a valid zero score.

type DeactivationChange

type DeactivationChange struct {
	DeactivationRequest
	Actor IdentityRef `json:"actor"`
}

DeactivationChange carries a service-authenticated actor to the transaction.

type DeactivationRequest

type DeactivationRequest struct {
	Kind               HarnessKind `json:"kind,omitempty"`
	ID                 id.ID       `json:"id"`
	AgentID            id.AgentID  `json:"agent_id"`
	Channel            string      `json:"channel"`
	ExpectedGeneration int64       `json:"expected_generation"`
	Reason             string      `json:"reason"`
}

DeactivationRequest disables a route without removing its history.

type Decision

type Decision struct {
	TaskSelection *TaskSelection  `json:"task_selection,omitempty"`
	AllocationID  id.ID           `json:"allocation_id"`
	SpecDigest    string          `json:"spec_digest"`
	ID            id.ID           `json:"id"`
	ExperimentID  id.ID           `json:"experiment_id"`
	Baseline      VersionRef      `json:"baseline"`
	Candidate     VersionRef      `json:"candidate"`
	SelectionKind string          `json:"selection_kind"`
	Outcome       DecisionOutcome `json:"outcome"`
	EvidenceClass EvidenceClass   `json:"evidence_class"`
	EvaluationIDs []string        `json:"evaluation_ids"`
	PolicyDigest  string          `json:"policy_digest"`
	Comparison    Comparison      `json:"comparison"`
	Reasons       []string        `json:"reasons"`
	CreatedAt     time.Time       `json:"created_at"`
}

Decision binds selection policy to the exact compared evidence.

func BuildTaskDecision

func BuildTaskDecision(experiment Experiment, evidence []DecisionEvidence) (Decision, error)

BuildTaskDecision deterministically selects from the complete stored roster. The caller supplies decision identity and the frozen baseline policy digest.

type DecisionEvidence

type DecisionEvidence struct {
	Trial      Trial
	Evaluation *Evaluation
}

DecisionEvidence binds an immutable trial to its optional captured evaluation. Missing evaluations can support an inconclusive decision, never a recommendation.

type DecisionOutcome

type DecisionOutcome string

DecisionOutcome is a recommendation, never an implicit activation command.

const (
	DecisionSelect       DecisionOutcome = "select"
	DecisionRecommend    DecisionOutcome = "recommend"
	DecisionRetain       DecisionOutcome = "retain"
	DecisionInconclusive DecisionOutcome = "inconclusive"
	DecisionReject       DecisionOutcome = "reject"
)

type DiscoveryEvidence

type DiscoveryEvidence struct {
	Trial      Trial      `json:"trial"`
	Evaluation Evaluation `json:"evaluation"`
}

DiscoveryEvidence deliberately omits frozen evaluator definitions and answers. Callers must also filter it by split before supplying it to a controller.

type DiscoveryLessons

type DiscoveryLessons struct {
	ExperimentID       id.ID         `json:"experiment_id"`
	ParentExperimentID id.ID         `json:"parent_experiment_id"`
	Controller         VersionRef    `json:"controller"`
	Arm                int           `json:"arm"`
	Sequence           int           `json:"sequence"`
	Domain             string        `json:"domain"`
	Lessons            []LessonDraft `json:"lessons"`
	Digest             string        `json:"digest"`
	CreatedAt          time.Time     `json:"created_at"`
}

DiscoveryLessons retains provisional learning from one controller-arm task. It is private to the comparison and cannot enter the published lesson library.

type DiscoveryLessonsRequest

type DiscoveryLessonsRequest struct {
	ExperimentID id.ID         `json:"experiment_id"`
	Lease        WorkLease     `json:"lease"`
	Domain       string        `json:"domain"`
	Lessons      []LessonDraft `json:"lessons"`
}

DiscoveryLessonsRequest records one completed discovery reflection. An empty non-nil Lessons slice records that the controller produced no reusable lesson.

func (DiscoveryLessonsRequest) Validate

func (request DiscoveryLessonsRequest) Validate() error

Validate checks bounded provisional content before storage resolves its evidence.

type DiscoveryRef

type DiscoveryRef struct {
	ExperimentID id.ID  `json:"experiment_id"`
	Digest       string `json:"digest"`
}

DiscoveryRef freezes one earlier task's private reflection content.

type Edit

type Edit struct {
	Participant string    `json:"participant,omitempty"`
	Kind        EditKind  `json:"kind"`
	Target      string    `json:"target,omitempty"`
	Text        string    `json:"text,omitempty"`
	Tools       *[]string `json:"tools,omitempty"`
	Number      *float64  `json:"number,omitempty"`
}

Edit carries one typed change. A non-nil empty Tools list means deny all tools.

type EditKind

type EditKind string

EditKind enumerates the only fields a candidate may propose changing.

const (
	EditOrchestrationPreset EditKind = "orchestration_preset"
	EditParticipantGuidance EditKind = "participant_guidance"
	EditSectionBody         EditKind = "section_body"
	EditToolDescription     EditKind = "tool_description"
	EditToolSubset          EditKind = "tool_subset"
	EditTemperature         EditKind = "temperature"
)

type EditPolicy

type EditPolicy struct {
	OrchestrationPresets    []OrchestrationPreset `json:"orchestration_presets,omitempty"`
	MutableSections         []string              `json:"mutable_sections"`
	MutableToolDescriptions []string              `json:"mutable_tool_descriptions"`
	AllowToolSubset         bool                  `json:"allow_tool_subset"`
	TemperatureMin          *float64              `json:"temperature_min,omitempty"`
	TemperatureMax          *float64              `json:"temperature_max,omitempty"`
	MaxBodyBytes            int                   `json:"max_body_bytes"`
	MaxPatchBytes           int                   `json:"max_patch_bytes"`
	MaxEdits                int                   `json:"max_edits"`
}

EditPolicy is a frozen host allowlist. Bounds must be positive and finite.

type EngineCompatibility

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

EngineCompatibility checks current stored sources and runtime implementations after the host has checked external dependencies and policy.

func NewEngineCompatibility

func NewEngineCompatibility(config EngineCompatibilityConfig) (*EngineCompatibility, error)

NewEngineCompatibility creates a read-only checker for a production engine. RuntimeVersion must identify the deployed runtime, not a caller-selected label.

func (*EngineCompatibility) Check

Check revalidates an execution version without executing models or tools. Host checks receive a detached version. A change during those checks is caught by the subsequent current-source snapshot and runtime-binding check.

type EngineCompatibilityConfig

type EngineCompatibilityConfig struct {
	Engine         *engine.Engine
	Host           Compatibility
	RuntimeVersion string
}

EngineCompatibilityConfig binds the production engine and its deployed revision. Host must check current policy and any external dependencies in version.Sources. Returning compatible grants no execution authority.

type EnvironmentFactory

EnvironmentFactory owns durable isolation and remote cancellation.

type EnvironmentReceipt

type EnvironmentReceipt struct {
	ID            string                `json:"id"`
	Provider      string                `json:"provider"`
	EnvironmentID string                `json:"environment_id"`
	Scope         cortex.Scope          `json:"scope"`
	AttemptID     id.ID                 `json:"attempt_id"`
	Snapshot      ContentRef            `json:"snapshot"`
	Capabilities  IsolationCapabilities `json:"capabilities"`
	Fence         Fence                 `json:"fence"`
	CreatedAt     time.Time             `json:"created_at"`
}

EnvironmentReceipt must be persisted before execution begins.

func (EnvironmentReceipt) Validate

func (receipt EnvironmentReceipt) Validate() error

Validate checks receipt identity; capability qualification belongs to the host.

type Evaluation

type Evaluation struct {
	// Score preserves the evaluator aggregate; nil means no complete score is available.
	Score           *float64         `json:"score,omitempty"`
	ID              string           `json:"id"`
	ReportID        string           `json:"report_id"`
	ExperimentID    id.ID            `json:"experiment_id"`
	TrialID         id.ID            `json:"trial_id"`
	CaseID          string           `json:"case_id"`
	CaseDigest      string           `json:"case_digest"`
	Repetition      int              `json:"repetition"`
	PlanDigest      string           `json:"plan_digest"`
	ExecutionDigest string           `json:"execution_digest"`
	Scorers         []run.Revision   `json:"scorers"`
	Criteria        []CriterionValue `json:"criteria"`
	Complete        bool             `json:"complete"`
	Errors          []string         `json:"errors"`
	JudgeUsage      Usage            `json:"judge_usage"`
	StartedAt       time.Time        `json:"started_at"`
	CompletedAt     time.Time        `json:"completed_at"`
	RecordedAt      time.Time        `json:"recorded_at"`
}

Evaluation identifies the durable external job, distinct from its report ID.

func (Evaluation) ValidateCaptured

func (evaluation Evaluation) ValidateCaptured(experiment Experiment, trial Trial) error

ValidateCaptured checks scoring identity and completeness without executing a target.

type EvaluationPlan

type EvaluationPlan struct {
	Ref         ContentRef            `json:"ref"`
	CaseDigests map[string]string     `json:"case_digests"`
	Scorers     []run.Revision        `json:"scorers"`
	FrozenAt    time.Time             `json:"frozen_at"`
	Criteria    []CriterionDefinition `json:"criteria"`
}

EvaluationPlan stores an immutable evaluator reference and scorer revisions. Private rubric bytes remain in evaluator storage.

func (EvaluationPlan) Validate

func (plan EvaluationPlan) Validate(spec ExperimentSpec) error

Validate binds public plan metadata to the frozen experiment inputs. Authenticating the external plan and private rubric remains the adapter's job.

type EvaluationRequest

type EvaluationRequest struct {
	// Lease fences any charged judge call to the requesting worker generation.
	Lease          WorkLease       `json:"lease"`
	ExperimentID   id.ID           `json:"experiment_id"`
	TrialID        id.ID           `json:"trial_id"`
	CandidateID    id.ID           `json:"candidate_id,omitempty"`
	CaseID         string          `json:"case_id"`
	CaseDigest     string          `json:"case_digest"`
	Repetition     int             `json:"repetition"`
	Plan           EvaluationPlan  `json:"plan"`
	Execution      ExecutionRecord `json:"execution"`
	IdempotencyKey string          `json:"idempotency_key"`
}

EvaluationRequest contains recorded output, never a callback to execute a task.

type EvaluationSpec

type EvaluationSpec struct {
	Source           ContentRef `json:"source"`
	Tasks            []TaskCase `json:"tasks"`
	RequiredCriteria []string   `json:"required_criteria"`
}

EvaluationSpec names a host-approved source and exact frozen task identities.

type Evaluator

Evaluator scores captured output and owns paired statistical calculations.

type Event

type Event struct {
	ID           id.ID           `json:"id"`
	ExperimentID id.ID           `json:"experiment_id"`
	Sequence     int64           `json:"sequence"`
	Type         string          `json:"type"`
	Actor        IdentityRef     `json:"actor"`
	Resources    []id.ID         `json:"resources"`
	Payload      json.RawMessage `json:"payload"`
	CreatedAt    time.Time       `json:"created_at"`
}

Event is redacted durable history with a monotonic experiment sequence.

type EvidenceClass

type EvidenceClass = learning.EvidenceClass

EvidenceClass describes which claims a comparison can support.

const (
	EvidenceValidated   EvidenceClass = learning.EvidenceValidated
	EvidenceContrastive EvidenceClass = learning.EvidenceContrastive
	EvidenceExploratory EvidenceClass = learning.EvidenceExploratory
)

type ExecutionRecord

type ExecutionRecord struct {
	RunID          id.AgentRunID           `json:"run_id"`
	Orchestration  *OrchestrationExecution `json:"orchestration,omitempty"`
	StepIDs        []id.ID                 `json:"step_ids"`
	ToolCallIDs    []id.ID                 `json:"tool_call_ids"`
	PreparedDigest string                  `json:"prepared_digest"`
	InputDigest    string                  `json:"input_digest"`
	Outcome        run.Outcome             `json:"outcome"`
	State          run.State               `json:"state"`
	Usage          Usage                   `json:"usage"`
	StartedAt      time.Time               `json:"started_at"`
	CompletedAt    time.Time               `json:"completed_at"`
	Duration       time.Duration           `json:"duration"`
	Environment    EnvironmentReceipt      `json:"environment"`
	Artifacts      []ArtifactRef           `json:"artifacts"`
	Digest         string                  `json:"digest"`
}

ExecutionRecord captures the original run and accounting for later evaluation.

func CaptureOrchestration

func CaptureOrchestration(ctx context.Context, source OrchestrationCaptureSource, version HarnessVersion, receipt EnvironmentReceipt, key id.OrchestrationID) (ExecutionRecord, error)

CaptureOrchestration reads a terminal team's original evidence without running or resuming it. It does not qualify isolation or authenticate provider billing.

func SealExecution

func SealExecution(record ExecutionRecord) (ExecutionRecord, error)

SealExecution binds the captured output, original run identity and receipts. It checks internal consistency, not whether referenced artifacts still exist.

func (ExecutionRecord) ExecutionID

func (record ExecutionRecord) ExecutionID() id.ID

ExecutionID returns the original agent or team identity without changing its prefix.

type Experiment

type Experiment struct {
	RetainedBaseline *RetainedBaseline `json:"retained_baseline,omitempty"`
	Discoveries      []DiscoveryRef    `json:"discoveries,omitempty"`
	DecisionID       id.ID             `json:"decision_id,omitempty"`
	ID               id.ID             `json:"id"`
	Spec             ExperimentSpec    `json:"spec"`
	SpecDigest       string            `json:"spec_digest"`
	EvaluationPlan   EvaluationPlan    `json:"evaluation_plan"`
	State            State             `json:"state"`
	Phase            Phase             `json:"phase"`
	Round            int               `json:"round"`
	Revision         int64             `json:"revision"`
	Lease            WorkLease         `json:"lease"`
	Plan             TrialPlan         `json:"plan"`
	LessonIDs        []id.ID           `json:"lesson_ids"`
	FrozenLessons    []LessonRef       `json:"frozen_lessons"`
	CreatedAt        time.Time         `json:"created_at"`
	UpdatedAt        time.Time         `json:"updated_at"`
	Deadline         time.Time         `json:"deadline"`
	Failure          string            `json:"failure,omitempty"`
}

Experiment combines a frozen specification with revision-fenced work state.

type ExperimentBundle

type ExperimentBundle struct {
	ParentLease     *WorkLease       `json:"parent_lease,omitempty"`
	ExpectedLessons []LessonRef      `json:"expected_lessons,omitempty"`
	Experiment      Experiment       `json:"experiment"`
	Versions        []HarnessVersion `json:"versions"`
}

ExperimentBundle atomically creates a draft and its frozen version content.

type ExperimentSpec

type ExperimentSpec struct {
	Improvement   *ImprovementPlan  `json:"improvement,omitempty"`
	Parent        *ParentExperiment `json:"parent,omitempty"`
	Task          *TaskPolicy       `json:"task,omitempty"`
	SchemaVersion int               `json:"schema_version"`
	Scope         cortex.Scope      `json:"scope"`
	AgentID       id.AgentID        `json:"agent_id"`
	Baseline      VersionRef        `json:"baseline"`
	Controller    VersionRef        `json:"controller"`
	Mode          Mode              `json:"mode"`
	Tasks         []TaskCase        `json:"tasks"`
	Evaluation    ContentRef        `json:"evaluation"`
	Objective     Objective         `json:"objective"`
	Limits        Limits            `json:"limits"`
	Budget        Budget            `json:"budget"`
	LessonCutoff  time.Time         `json:"lesson_cutoff"`
	Requester     IdentityRef       `json:"requester"`
}

ExperimentSpec is frozen before work begins. Host authorization must still validate its requested limits and references before persistence or dispatch.

func DecodeSpec

func DecodeSpec(data []byte) (ExperimentSpec, error)

DecodeSpec rejects duplicate or unknown JSON members before validation.

type Fence

type Fence struct {
	Owner      string `json:"owner"`
	Generation int64  `json:"generation"`
}

Fence identifies the current generation allowed to control an environment.

type Harness

type Harness struct {
	ID        id.ID        `json:"id"`
	Scope     cortex.Scope `json:"scope"`
	AgentID   id.AgentID   `json:"agent_id"`
	Name      string       `json:"name"`
	Kind      HarnessKind  `json:"kind"`
	Revision  int64        `json:"revision"`
	CreatedAt time.Time    `json:"created_at"`
	CreatedBy IdentityRef  `json:"created_by"`
}

Harness groups immutable versions for one agent within an exact scope.

type HarnessKind

type HarnessKind string

HarnessKind distinguishes execution inputs from the improvement controller.

const (
	HarnessExecution   HarnessKind = "execution"
	HarnessImprovement HarnessKind = "improvement"
)

func ActivationKind

func ActivationKind(kind HarnessKind) (HarnessKind, error)

ActivationKind resolves legacy execution routes and rejects unsupported kinds.

type HarnessVersion

type HarnessVersion struct {
	Orchestration  *OrchestrationSelection `json:"orchestration,omitempty"`
	ID             id.ID                   `json:"id"`
	HarnessID      id.ID                   `json:"harness_id"`
	ParentID       id.ID                   `json:"parent_id,omitempty"`
	SchemaVersion  int                     `json:"schema_version"`
	Kind           HarnessKind             `json:"kind"`
	Scope          cortex.Scope            `json:"scope"`
	AgentID        id.AgentID              `json:"agent_id"`
	Prepared       *engine.PreparedAgent   `json:"prepared,omitempty"`
	Controller     *ControllerSpec         `json:"controller,omitempty"`
	RuntimeVersion string                  `json:"runtime_version,omitempty"`
	Policy         EditPolicy              `json:"policy"`
	PolicyDigest   string                  `json:"policy_digest"`
	Sources        []run.Revision          `json:"sources"`
	Digest         string                  `json:"digest"`
	Name           string                  `json:"name,omitempty"`
	CreatedAt      time.Time               `json:"created_at"`
	CreatedBy      string                  `json:"created_by"`
}

HarnessVersion contains immutable execution content and separate display metadata. Persisted digests are checked before deriving or executing another version.

func SealVersion

func SealVersion(version HarnessVersion) (HarnessVersion, error)

SealVersion validates and detaches all mutable content before assigning a digest.

func ValidateProposal

func ValidateProposal(base HarnessVersion, proposal Proposal, policy EditPolicy) (HarnessVersion, error)

ValidateProposal derives a detached version through the root engine's frozen edit API. It refuses a changed host policy and never reloads live sources.

type HostCapabilities

type HostCapabilities struct {
	Target          CapabilityTarget              `json:"target"`
	Checks          map[Capability]ReadinessState `json:"checks"`
	Environment     IsolationCapabilities         `json:"environment"`
	PricingQuality  UsageQuality                  `json:"pricing_quality"`
	PricingRevision string                        `json:"pricing_revision,omitempty"`
}

HostCapabilities contains current host observations, never authorization grants. Missing checks remain unknown. Pricing must name its revision when qualified.

type IdentityRef

type IdentityRef struct {
	Subject string `json:"subject"`
}

IdentityRef names a host subject whose current permissions workers must resolve.

type IdentityResolver

type IdentityResolver interface {
	Resolve(context.Context, IdentityRef, cortex.Scope) (context.Context, error)
}

IdentityResolver rebuilds a host context from a stable subject reference.

type ImprovementChild

type ImprovementChild struct {
	ExperimentID   id.ID          `json:"experiment_id"`
	Spec           ExperimentSpec `json:"spec"`
	EvaluationPlan EvaluationPlan `json:"evaluation_plan"`
}

ImprovementChild retains the complete child template for restartable scheduling. Templates cannot contain another improvement plan.

type ImprovementPhaseHandler

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

ImprovementPhaseHandler schedules the frozen child stream with a dedicated worker.

func NewImprovementPhaseHandler

func NewImprovementPhaseHandler(config OptimizerConfig) (*ImprovementPhaseHandler, error)

NewImprovementPhaseHandler wraps child phase execution and owns no goroutines. The returned handler belongs to the parent optimizer; config.Handler executes children.

func (*ImprovementPhaseHandler) Execute

Execute advances one bounded parent step or delegates a standalone experiment. Child progress returns ErrConflict while the parent remains in its current phase.

type ImprovementPlan

type ImprovementPlan struct {
	Controllers [2]VersionRef      `json:"controllers"`
	Children    []ImprovementChild `json:"children"`
}

ImprovementPlan freezes two controller arms and their ordered child templates. Children are stored as consecutive pairs, baseline arm followed by candidate arm.

type ImprovementSpec

type ImprovementSpec struct {
	Bundle ExperimentBundle `json:"bundle"`
}

ImprovementSpec contains a host-frozen parent and its ordered child templates. Bundle.Experiment.Spec.Improvement identifies both immutable controller arms.

type InputTokenBound

type InputTokenBound struct {
	Model         string
	ModelRevision string
	Tokens        int64
	Bounded       bool
}

InputTokenBound includes all provider input framing, messages and tool schemas. Bounded is a host assertion about an upper bound, not an approximate count.

type InputTokenCounter

type InputTokenCounter interface {
	Bound(context.Context, *llm.Request) (InputTokenBound, error)
}

InputTokenCounter supplies a local, model-specific conservative input bound. Implementations must include provider-added framing and cannot make unmetered charged calls. Unknown tokenizer or model revisions must return Bounded=false.

type IsolationCapabilities

type IsolationCapabilities struct {
	Isolated              bool `json:"isolated"`
	Resettable            bool `json:"resettable"`
	IdempotentEffects     bool `json:"idempotent_effects"`
	Recoverable           bool `json:"recoverable"`
	Stoppable             bool `json:"stoppable"`
	ReadOnly              bool `json:"read_only"`
	FrozenRetrieval       bool `json:"frozen_retrieval"`
	AtomicSources         bool `json:"atomic_sources"`
	DeterministicApproval bool `json:"deterministic_approval"`
}

IsolationCapabilities are host guarantees, not inferred from session IDs.

type LedgerMeter

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

LedgerMeter applies current host authority to durable accounting transactions. It resolves the experiment's original requester for every operation. Provider execution and receipt reconciliation remain the caller's responsibility.

func NewLedgerMeter

func NewLedgerMeter(repository MeterRepository, authorizer Authorizer, resolver IdentityResolver) (*LedgerMeter, error)

NewLedgerMeter requires explicit persistence and host authorization services.

func (*LedgerMeter) BeginCall

func (m *LedgerMeter) BeginCall(ctx context.Context, request UsageReservation, digest string) (Reservation, error)

BeginCall atomically reserves and marks a bound request as possibly started. An existing dispatch returns ErrUnknownAttempt and must be reconciled, even when the worker cannot determine whether the provider received the request.

func (*LedgerMeter) Reserve

func (m *LedgerMeter) Reserve(ctx context.Context, request UsageReservation) (Reservation, error)

Reserve holds a conservative debit without dispatching any provider operation.

func (*LedgerMeter) Settle

func (m *LedgerMeter) Settle(ctx context.Context, settlement UsageSettlement) error

Settle records a host-attributed provider receipt or uncertainty observation. Callers must establish receipt provenance; model output is not a usage receipt.

type Lesson

type Lesson = learning.Lesson

Lesson shares the root learning schema while optimizer acceptance retains its decision and trial provenance rules.

type LessonDraft

type LessonDraft struct {
	Statement         string   `json:"statement"`
	Domain            string   `json:"domain"`
	Applicability     []string `json:"applicability"`
	Contraindications []string `json:"contraindications"`
	EvidenceIDs       []id.ID  `json:"evidence_ids"`
}

LessonDraft is controller output requiring validation and provenance binding.

type LessonPage

type LessonPage = Page[Lesson]

LessonPage contains eligible lessons and a stable continuation cursor.

type LessonQuery

type LessonQuery struct {
	PageQuery
	Domain        string        `json:"domain,omitempty"`
	EvidenceClass EvidenceClass `json:"evidence_class,omitempty"`
	EligibleOnly  bool          `json:"eligible_only,omitempty"`
}

LessonQuery can omit lessons whose frozen sources are no longer eligible.

type LessonRef

type LessonRef = learning.Ref

LessonRef freezes local eligibility and content at experiment creation.

type LessonRevocation

type LessonRevocation struct {
	CommandKey       string      `json:"command_key,omitempty"`
	LessonID         id.ID       `json:"lesson_id"`
	ExpectedRevision int64       `json:"expected_revision"`
	Actor            IdentityRef `json:"actor"`
	Reason           string      `json:"reason"`
}

LessonRevocation permanently withdraws a lesson at the expected local revision. Current actor authorization is checked by the service before this command.

type LessonStore

type LessonStore interface {
	Publish(context.Context, Lesson) (PublicationReceipt, error)
	Recall(context.Context, RecallQuery) (LessonPage, error)
	Revoke(context.Context, id.ID, int64) error
}

LessonStore publishes governed lessons through the host's shared knowledge store.

type Limits

type Limits struct {
	MaxRounds         int           `json:"max_rounds"`
	MaxCandidates     int           `json:"max_candidates"`
	MaxTrials         int           `json:"max_trials"`
	Concurrency       int           `json:"concurrency"`
	ExperimentTimeout time.Duration `json:"experiment_timeout"`
	TrialTimeout      time.Duration `json:"trial_timeout"`
	MaxSteps          int           `json:"max_steps"`
	MaxOutputTokens   int           `json:"max_output_tokens"`
	Repetitions       int           `json:"repetitions"`
}

Limits bounds scheduling and each provider dispatch. Durations use nanoseconds in JSON. MaxCandidates includes every composed candidate across all rounds.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns explicit scheduling defaults. Hosts can tighten them before freezing a spec; no zero field is interpreted as unlimited.

type ListQuery

type ListQuery struct {
	Limit   int        `json:"limit"`
	Cursor  string     `json:"cursor,omitempty"`
	AgentID id.AgentID `json:"agent_id,omitempty"`
	State   State      `json:"state,omitempty"`
}

ListQuery requests a bounded page within the context's exact scope.

type Meter

type Meter interface {
	Reserve(context.Context, UsageReservation) (Reservation, error)
	Settle(context.Context, UsageSettlement) error
}

Meter reserves before external dispatch and settles each receipt once.

type MeterRepository

type MeterRepository interface {
	GetExperiment(context.Context, id.ID) (Experiment, error)
	Transact(context.Context, func(Transaction) error) error
}

MeterRepository supplies scoped experiment authority and atomic accounting.

type MeteredClient

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

MeteredClient applies durable accounting to synchronous and streaming model calls. Estimators must conservatively bound the actual request, including input tokens and frozen pricing. Providers must honor context cancellation and caps.

func NewMeteredClient

func NewMeteredClient(provider llm.Client, meter CallMeter, estimator UsageEstimator, reporter ModelUsageReporter, config MeteredClientConfig) (*MeteredClient, error)

NewMeteredClient requires a provider, meter, estimator and explicit frozen binding. Without a reporter, observed counts remain unknown accounting and cannot release the reserved upper bound. The host must pin provider routing to Model and ModelRevision; a model name alone does not establish that pin.

func (*MeteredClient) Complete

func (c *MeteredClient) Complete(ctx context.Context, request *llm.Request) (*llm.Response, error)

Complete reserves and marks dispatch before invoking the provider once. A partial response may accompany an error; callers must not treat it as success.

func (*MeteredClient) CompleteStream

func (c *MeteredClient) CompleteStream(ctx context.Context, request *llm.Request) (llm.Stream, error)

CompleteStream reserves before opening a stream. Callers must close it when abandoning iteration. EOF and iteration failures close and settle it once.

type MeteredClientConfig

type MeteredClientConfig struct {
	Scope            cortex.Scope
	ExperimentID     id.ID
	AttemptID        id.ID
	Operation        OperationClass
	Model            string
	ModelRevision    string
	MaxRequestBytes  int
	MaxResponseBytes int
}

MeteredClientConfig binds a client to one frozen model and optimization attempt. Byte limits bound accepted JSON, not allocations inside a provider or estimator.

type Mode

type Mode string

Mode controls how discovery candidates share their baseline.

const (
	ModeSequential Mode = "sequential"
	ModeParallel   Mode = "parallel"
	ModeTaskLocal  Mode = "task_local"
)

type ModelBinding

type ModelBinding struct {
	Model, Revision string
	Provider        llm.Client
	Counter         InputTokenCounter
	Pricing         Pricing
	Reporter        ModelUsageReporter
}

ModelBinding pins host provider routing and accounting to a resolved revision. Counter and Pricing must cover that provider's full billing semantics.

type ModelObservation

type ModelObservation struct {
	Reservation   UsageReservation
	RequestDigest string
	Model         string
	ModelRevision string
	ReportedModel string
	Streaming     bool
	Usage         llm.Usage
	UsagePresent  bool
	Completed     bool
	Err           error
}

ModelObservation carries provider accounting facts without prompts or outputs. Completed describes execution, independently of whether usage is authoritative.

type ModelUsageReport

type ModelUsageReport struct {
	Usage    Usage
	Complete bool
}

ModelUsageReport attributes usage to a trusted provider receipt. Complete means the accounting is complete, not that the model produced a successful answer.

type ModelUsageReporter

type ModelUsageReporter interface {
	Observe(context.Context, ModelObservation) (ModelUsageReport, error)
}

ModelUsageReporter verifies provider usage and frozen pricing. Implementations must not infer authoritative zero usage from an absent report. Its work must not itself perform unmetered model calls or other charged operations.

type MoneyEstimate

type MoneyEstimate struct {
	USDMicros       int64        `json:"usd_micros"`
	Quality         UsageQuality `json:"quality"`
	PricingRevision string       `json:"pricing_revision"`
}

MoneyEstimate carries a conservative charge and its pricing provenance.

type Objective

type Objective struct {
	MinImprovement         float64  `json:"min_improvement"`
	MaxProtectedRegression float64  `json:"max_protected_regression"`
	ProtectedCriteria      []string `json:"protected_criteria"`
	RequiredCriteria       []string `json:"required_criteria"`
	MinValidationCases     int      `json:"min_validation_cases"`
	Confidence             float64  `json:"confidence"`
	BootstrapSamples       int      `json:"bootstrap_samples"`
	BootstrapSeed          uint64   `json:"bootstrap_seed"`
	MaxCostRatio           *float64 `json:"max_cost_ratio,omitempty"`
	MaxLatencyRatio        *float64 `json:"max_latency_ratio,omitempty"`
	RequireReproducibility bool     `json:"require_reproducibility"`
}

Objective freezes selection thresholds. Insufficient distinct validation cases produce exploratory evidence, not a relaxed confidence requirement.

func DefaultObjective

func DefaultObjective() Objective

DefaultObjective returns the initial paired quality selection policy.

type OperationClass

type OperationClass string

OperationClass separates every source of metered experiment usage.

const (
	OperationBaseline    OperationClass = "baseline"
	OperationProposal    OperationClass = "proposal"
	OperationProbe       OperationClass = "probe"
	OperationComposition OperationClass = "composition"
	OperationValidation  OperationClass = "validation"
	OperationReflection  OperationClass = "reflection"
	OperationJudge       OperationClass = "judge"
	OperationEmbedding   OperationClass = "embedding"
	OperationRetrieval   OperationClass = "retrieval"
	OperationTool        OperationClass = "tool"
)

type Optimizer

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

Optimizer provides experiment commands and a bounded, host-started worker.

func NewOptimizer

func NewOptimizer(config OptimizerConfig, options ...Option) (*Optimizer, error)

NewOptimizer never starts background work. The host runs Work with an exact scoped context and cancels it during shutdown. Each instance has a unique owner.

func (*Optimizer) Activate

func (o *Optimizer) Activate(ctx context.Context, request ActivationRequest) (*Activation, error)

Activate rechecks current authority, compatibility and retained evidence.

func (*Optimizer) AdoptArtifacts

AdoptArtifacts verifies selected evidence and current authority before asking the host to commit artifacts. It never reruns a trial or retries host effects.

func (*Optimizer) Cancel

func (o *Optimizer) Cancel(ctx context.Context, experimentID id.ID, revision int64) (Experiment, error)

Cancel invalidates running authority immediately; worker polling cancels active work.

func (*Optimizer) CancelCommand

func (o *Optimizer) CancelCommand(ctx context.Context, request CommandRequest) (Experiment, error)

CancelCommand cancels pending work and permits an identical recovery retry.

func (*Optimizer) Capabilities

func (o *Optimizer) Capabilities(ctx context.Context, experimentID id.ID) (CapabilitySnapshot, error)

Capabilities reads current scoped diagnostics. It never starts a worker, executes a trial, or treats an absent host probe as an empty ready catalog.

func (*Optimizer) Create

func (o *Optimizer) Create(ctx context.Context, bundle ExperimentBundle) (Experiment, error)

Create saves a host-frozen bundle, including its immutable versions and plan.

func (*Optimizer) CreateCommand

func (o *Optimizer) CreateCommand(ctx context.Context, request CreationRequest) (Experiment, error)

CreateCommand resolves host catalog choices once and saves a durable receipt. Identical retries recheck current catalog and creation grants, then return the original experiment's current state without preparing from live sources again.

func (*Optimizer) CreateImprovementExperiment

func (o *Optimizer) CreateImprovementExperiment(ctx context.Context, request ImprovementSpec) (*Experiment, error)

CreateImprovementExperiment authenticates a frozen comparison before saving its draft. It does not start workers or dispatch controller or judge calls.

func (*Optimizer) CreateWithLessons

func (o *Optimizer) CreateWithLessons(ctx context.Context, bundle ExperimentBundle, query RecallQuery) (Experiment, error)

CreateWithLessons recalls one complete bounded result set before creating a draft. The cutoff must already be frozen in the supplied specification. Store creation atomically verifies the recalled revisions and digests again.

func (*Optimizer) Deactivate

func (o *Optimizer) Deactivate(ctx context.Context, request DeactivationRequest) (*Activation, error)

Deactivate turns off the route even when its previous evidence is unavailable.

func (*Optimizer) Get

func (o *Optimizer) Get(ctx context.Context, experimentID id.ID) (Experiment, error)

Get reads one experiment after checking its exact scope and current authority.

func (*Optimizer) GetCandidate

func (o *Optimizer) GetCandidate(ctx context.Context, experimentID, key id.ID) (Candidate, error)

GetCandidate binds the candidate to the authorized parent experiment.

func (*Optimizer) GetComparison

func (o *Optimizer) GetComparison(ctx context.Context, experimentID id.ID, query PageQuery) (ComparisonDetail, error)

GetComparison returns recorded evidence without evaluating or rerunning a trial.

func (*Optimizer) GetLesson

func (o *Optimizer) GetLesson(ctx context.Context, key id.ID) (Lesson, error)

GetLesson reads a local lesson, including its current revocation state.

func (*Optimizer) GetTaskResult

func (o *Optimizer) GetTaskResult(ctx context.Context, experimentID id.ID) (*TaskResult, error)

GetTaskResult rechecks authority, lessons and artifacts without rerunning work.

func (*Optimizer) GetTrial

func (o *Optimizer) GetTrial(ctx context.Context, experimentID, key id.ID) (Trial, error)

GetTrial binds original execution evidence to its authorized parent.

func (*Optimizer) GetVersion

func (o *Optimizer) GetVersion(ctx context.Context, key id.ID) (HarnessVersion, error)

GetVersion reads immutable content; compatibility is a separate current check.

func (*Optimizer) List

func (o *Optimizer) List(ctx context.Context, query ListQuery) (Page[Experiment], error)

List reads one bounded page in an explicitly authorized exact scope.

func (*Optimizer) ListActivations

func (o *Optimizer) ListActivations(ctx context.Context, query ActivationQuery) (ResourcePage[Activation], error)

ListActivations returns immutable history for an explicitly selected route.

func (*Optimizer) ListCandidates

func (o *Optimizer) ListCandidates(ctx context.Context, experimentID id.ID, query PageQuery) (ResourcePage[Candidate], error)

ListCandidates includes rejected proposals without granting execution authority.

func (*Optimizer) ListCatalog

func (o *Optimizer) ListCatalog(ctx context.Context, query CatalogQuery) (ResourcePage[CatalogChoice], error)

ListCatalog returns authorized metadata without preparing or executing work. Missing configuration is unavailable; it is never an empty successful catalog.

func (*Optimizer) ListEvents

func (o *Optimizer) ListEvents(ctx context.Context, experimentID id.ID, query PageQuery) (ResourcePage[Event], error)

ListEvents binds reconnect cursors to the exact scope and experiment.

func (*Optimizer) ListExperiments

func (o *Optimizer) ListExperiments(ctx context.Context, query ListQuery) (ResourcePage[Experiment], error)

ListExperiments reads a bounded, authorized page for the operator interfaces.

func (*Optimizer) ListLessons

func (o *Optimizer) ListLessons(ctx context.Context, query LessonQuery) (ResourcePage[Lesson], error)

ListLessons reads local eligibility, including revoked lessons when requested.

func (*Optimizer) ListPublications

func (o *Optimizer) ListPublications(ctx context.Context, query PublicationQuery) (ResourcePage[Publication], error)

ListPublications exposes durable delivery status independently of remote indexes.

func (*Optimizer) ListTrials

func (o *Optimizer) ListTrials(ctx context.Context, experimentID id.ID, query TrialQuery) (ResourcePage[Trial], error)

ListTrials retains original attempts and explicit unknown outcomes.

func (*Optimizer) ListVersions

func (o *Optimizer) ListVersions(ctx context.Context, query VersionQuery) (ResourcePage[HarnessVersion], error)

ListVersions returns only versions allowed by the current resource grants.

func (*Optimizer) OptimizeTask

func (o *Optimizer) OptimizeTask(ctx context.Context, request TaskSpec) (*TaskResult, error)

OptimizeTask runs bounded task-local work through the configured phase handler. After interruption, the returned experiment ID supports explicit recovery.

func (*Optimizer) Pause

func (o *Optimizer) Pause(ctx context.Context, experimentID id.ID, revision int64) (Experiment, error)

Pause stops scheduling while retaining the frozen phase, deadline and history.

func (*Optimizer) ResolveActiveController

func (o *Optimizer) ResolveActiveController(ctx context.Context, request ActiveControllerRequest) (*ControllerSelection, error)

ResolveActiveController rechecks current grants, evidence and model bindings without dispatching a model or changing any existing experiment.

func (*Optimizer) Resume

func (o *Optimizer) Resume(ctx context.Context, experimentID id.ID, revision int64) (Experiment, error)

Resume revalidates the original requester and queues the same frozen phase.

func (*Optimizer) ResumeCommand

func (o *Optimizer) ResumeCommand(ctx context.Context, request CommandRequest) (Experiment, error)

ResumeCommand rechecks the original requester before queuing a paused experiment.

func (*Optimizer) RetainCommand

func (o *Optimizer) RetainCommand(ctx context.Context, request RetainRequest) (Experiment, error)

RetainCommand closes a pending review without changing any production route. It remains available without the original requester's current grants or old artifact content. A currently active adoption of this decision must first be explicitly deactivated or replaced through the activation workflow.

func (*Optimizer) RetryLessonCommand

func (o *Optimizer) RetryLessonCommand(ctx context.Context, request RetryLessonRequest) (Publication, error)

RetryLessonCommand queues another bounded cycle without calling the destination. Replays return current publication state, including any later delivery outcome.

func (*Optimizer) RevokeLessonCommand

func (o *Optimizer) RevokeLessonCommand(ctx context.Context, request RevokeLessonRequest) (Lesson, error)

RevokeLessonCommand commits local withdrawal and its outbox atomically. It requires the current operator's grant without resolving the original requester.

func (*Optimizer) Rollback

func (o *Optimizer) Rollback(ctx context.Context, request RollbackRequest) (*Activation, error)

Rollback revalidates a previously activated version under current policy.

func (*Optimizer) RunActive

func (o *Optimizer) RunActive(ctx context.Context, request ActiveRunRequest) (*run.Run, error)

RunActive resolves one activation and executes its immutable production snapshot.

func (*Optimizer) RunActiveOrchestration

func (o *Optimizer) RunActiveOrchestration(ctx context.Context, request ActiveOrchestrationRequest) (*orchestration.Run, error)

RunActiveOrchestration executes the reviewed team under its approved shared budget.

func (*Optimizer) Start

func (o *Optimizer) Start(ctx context.Context, experimentID id.ID, revision int64) (Experiment, error)

Start queues a frozen draft and returns without running the controller.

func (*Optimizer) StartCommand

func (o *Optimizer) StartCommand(ctx context.Context, request CommandRequest) (Experiment, error)

StartCommand queues a frozen draft and records the caller's idempotency key. It never runs a controller or trial in the requesting goroutine.

func (*Optimizer) Work

func (o *Optimizer) Work(ctx context.Context) error

Work polls top-level experiments in the caller's exact scope. Parent handlers schedule their children through WorkOnce. It owns one active phase and one heartbeat goroutine; the host owns scope enumeration and supervision.

func (*Optimizer) WorkOnce

func (o *Optimizer) WorkOnce(ctx context.Context, experimentID id.ID) error

WorkOnce claims one experiment, renews authority while executing one phase, and commits its transition. A failed parallel batch can commit successful siblings while returning its error; interrupted phases retain durable markers.

type OptimizerConfig

type OptimizerConfig struct {
	Catalog                 CatalogProvider
	CreationCatalog         CreationCatalog
	Capabilities            CapabilityProbe
	Repository              Repository
	Authorizer              Authorizer
	IdentityResolver        IdentityResolver
	Caller                  CallerIdentity
	Lessons                 LessonStore
	Compatibility           Compatibility
	ControllerCompatibility Compatibility
	ArtifactVerifier        *ArtifactVerifier
	TaskEvaluator           Evaluator
	ImprovementEvaluator    Evaluator
	Handler                 PhaseHandler
	UsageRecovery           *UsageRecovery
	Worker                  WorkerConfig
}

OptimizerConfig supplies explicit persistence, authority and phase execution. A Handler must reconcile durable external attempts before dispatching effects.

type Option

type Option func(*Optimizer) error

Option binds an optional host integration during optimizer construction.

func WithActiveEngine

func WithActiveEngine(runtime *engine.Engine) Option

WithActiveEngine supplies the production engine for explicitly active routes.

func WithArtifactAdopter

func WithArtifactAdopter(adopter ArtifactAdopter) Option

WithArtifactAdopter binds the explicit host commit operation for task artifacts.

type OrchestrationCaptureSource

type OrchestrationCaptureSource interface {
	GetOrchestrationRun(context.Context, id.OrchestrationID) (*orchestration.Run, error)
	GetOrchestrationBudgetSnapshot(context.Context, id.OrchestrationID) (orchestration.BudgetSnapshot, error)
	ListOrchestrationReservations(context.Context, execution.ReservationListRequest) ([]execution.Reservation, error)
	GetRun(context.Context, id.AgentRunID) (*run.Run, error)
	ListSteps(context.Context, id.AgentRunID) ([]*run.Step, error)
	ListToolCalls(context.Context, id.StepID) ([]*run.ToolCall, error)
}

OrchestrationCaptureSource reads original runtime evidence. The host supplies its isolated store and authenticates settlements before they reach that store.

type OrchestrationChildExecution

type OrchestrationChildExecution struct {
	Reservation execution.Reservation `json:"reservation"`
	Execution   *ExecutionRecord      `json:"execution,omitempty"`
}

OrchestrationChildExecution binds one original reservation to its captured run. Execution is absent when dispatch or capture failed before a terminal result.

type OrchestrationExecution

type OrchestrationExecution struct {
	Run      orchestration.Run             `json:"run"`
	Budget   orchestration.BudgetSnapshot  `json:"budget"`
	Children []OrchestrationChildExecution `json:"children"`
}

OrchestrationExecution retains the original team, closed account and every reserved child. A failed team may retain reservations without child captures. Receipt integrity is checked here; the environment authenticates their source.

type OrchestrationPreset

type OrchestrationPreset struct {
	Name     string                        `json:"name"`
	Prepared *engine.PreparedOrchestration `json:"prepared"`
	Limits   execution.Resources           `json:"limits"`
	Guidance map[string][]string           `json:"guidance"`
	Digest   string                        `json:"digest"`
}

OrchestrationPreset freezes a host-approved team, shared ceilings and editable participant sections. Sealing proves content integrity, not current authority.

func SealOrchestrationPreset

func SealOrchestrationPreset(preset OrchestrationPreset) (OrchestrationPreset, error)

SealOrchestrationPreset validates and detaches an approved configuration. The current runtime supports token ceilings and refuses unrestricted messaging.

type OrchestrationSelection

type OrchestrationSelection struct {
	Preset   string                        `json:"preset"`
	Prepared *engine.PreparedOrchestration `json:"prepared"`
	Guidance map[string]map[string]string  `json:"guidance,omitempty"`
}

OrchestrationSelection identifies one preset from the frozen edit policy. Prepared retains the selected team's complete immutable runtime snapshot.

type OrchestrationTrialEnvironment

type OrchestrationTrialEnvironment interface {
	TrialEnvironment
	ExecuteOrchestration(context.Context, *engine.PreparedOrchestration, string, engine.PreparedRunOptions) (*ExecutionRecord, error)
}

OrchestrationTrialEnvironment is optional host support for isolated team trials. The host enforces the supplied shared policy and retains original child evidence. Inspect recovers the same team; it must never dispatch a replacement execution.

type Page

type Page[T any] struct {
	Items      []T    `json:"items"`
	NextCursor string `json:"next_cursor,omitempty"`
}

Page carries stable cursor pagination without exposing backend offsets.

type PageQuery

type PageQuery struct {
	Limit  int    `json:"limit"`
	Cursor string `json:"cursor,omitempty"`
}

PageQuery bounds a resource read. A cursor binds the scope, collection and filters.

type ParentExperiment

type ParentExperiment struct {
	ExperimentID id.ID `json:"experiment_id"`
	Arm          int   `json:"arm"`
	Sequence     int   `json:"sequence"`
}

ParentExperiment binds a child to one position in a frozen controller comparison.

type Phase

type Phase string

Phase records the durable point from which an experiment resumes.

const (
	PhaseBaseline Phase = "baseline"
	PhasePropose  Phase = "propose"
	PhaseProbe    Phase = "probe"
	PhaseCompose  Phase = "compose"
	PhaseValidate Phase = "validate"
	PhaseDecide   Phase = "decide"
	PhaseReflect  Phase = "reflect"
)

type PhaseHandler

type PhaseHandler interface {
	Execute(context.Context, WorkItem) (Transition, error)
}

PhaseHandler executes one bounded phase step. It must honor cancellation and reconcile prior attempts before effects. The worker supplies transition authority.

type Pricing

type Pricing interface {
	Price(context.Context, UsageEstimate) (MoneyEstimate, error)
}

Pricing supplies host-approved bounds for the frozen pricing revision.

type Proposal

type Proposal struct {
	Edits       []Edit  `json:"edits"`
	Rationale   string  `json:"rationale,omitempty"`
	EvidenceIDs []id.ID `json:"evidence_ids,omitempty"`
}

Proposal contains candidate edits and their explanation, never host settings.

func DecodeProposal

func DecodeProposal(data []byte) (Proposal, error)

DecodeProposal rejects unknown and duplicate JSON members at every depth.

type ProposalInput

type ProposalInput struct {
	Discoveries []DiscoveryLessons  `json:"discoveries,omitempty"`
	Baseline    HarnessVersion      `json:"baseline"`
	Round       int                 `json:"round"`
	Evidence    []DiscoveryEvidence `json:"evidence"`
	Lessons     []Lesson            `json:"lessons"`
	Policy      EditPolicy          `json:"policy"`
}

ProposalInput carries the current discovery baseline and frozen lesson set.

type Publication

type Publication struct {
	RetryAttemptBase  int                  `json:"retry_attempt_base"`
	LastRetry         *PublicationRetry    `json:"last_retry,omitempty"`
	RetriedAt         time.Time            `json:"retried_at,omitempty"`
	DeliveryLease     PublicationLease     `json:"delivery_lease"`
	DeliveryActor     IdentityRef          `json:"delivery_actor"`
	Receipt           *PublicationReceipt  `json:"receipt,omitempty"`
	LastErrorCode     string               `json:"last_error_code,omitempty"`
	CreatedAt         time.Time            `json:"created_at"`
	ExperimentID      id.ID                `json:"experiment_id"`
	SupersededAt      time.Time            `json:"superseded_at,omitempty"`
	LessonID          id.ID                `json:"lesson_id"`
	Operation         PublicationOperation `json:"operation"`
	Payload           Lesson               `json:"payload"`
	PayloadDigest     string               `json:"payload_digest"`
	LocalRevision     int64                `json:"local_revision"`
	RemoteAggregateID string               `json:"remote_aggregate_id,omitempty"`
	RemoteVersion     int64                `json:"remote_version"`
	Attempts          int                  `json:"attempts"`
	NextRetry         time.Time            `json:"next_retry"`
	CompletedAt       time.Time            `json:"completed_at"`
	TerminalError     string               `json:"terminal_error,omitempty"`
}

Publication is the durable outbox entry committed with its local decision.

type PublicationClaim

type PublicationClaim struct {
	LessonID      id.ID         `json:"lesson_id"`
	LocalRevision int64         `json:"local_revision"`
	Owner         string        `json:"owner"`
	Duration      time.Duration `json:"duration"`
	Actor         IdentityRef   `json:"actor"`
}

PublicationClaim acquires one outbox payload independently of experiment work. Delivery continues after review or completion without reopening the experiment.

type PublicationLease

type PublicationLease struct {
	LessonID      id.ID     `json:"lesson_id"`
	LocalRevision int64     `json:"local_revision"`
	Owner         string    `json:"owner"`
	Generation    int64     `json:"generation"`
	ExpiresAt     time.Time `json:"expires_at"`
}

PublicationLease fences acknowledgements to one delivery attempt.

type PublicationOperation

type PublicationOperation string

PublicationOperation distinguishes immutable publish from revocation payloads.

const (
	PublicationPublish PublicationOperation = "publish"
	PublicationRevoke  PublicationOperation = "revoke"
)

type PublicationQuery

type PublicationQuery struct {
	PageQuery
	ExperimentID id.ID                `json:"experiment_id,omitempty"`
	LessonID     id.ID                `json:"lesson_id,omitempty"`
	Operation    PublicationOperation `json:"operation,omitempty"`
	PendingOnly  bool                 `json:"pending_only,omitempty"`
}

PublicationQuery filters local delivery records. PendingOnly omits acknowledged, superseded and terminally failed entries; workers still need a fenced claim.

type PublicationReceipt

type PublicationReceipt struct {
	LessonID       id.ID     `json:"lesson_id"`
	PayloadDigest  string    `json:"payload_digest"`
	AggregateID    string    `json:"aggregate_id"`
	Version        int64     `json:"version"`
	AcknowledgedAt time.Time `json:"acknowledged_at"`
}

PublicationReceipt acknowledges a concrete remote aggregate revision.

type PublicationRequest

type PublicationRequest struct {
	ExperimentID      id.ID       `json:"experiment_id"`
	Lease             WorkLease   `json:"lease"`
	Actor             IdentityRef `json:"actor"`
	Lesson            Lesson      `json:"lesson"`
	RemoteAggregateID string      `json:"remote_aggregate_id"`
}

PublicationRequest accepts one reflection under its current worker lease. The store assigns payload revision, digest and timestamps before any remote call.

type PublicationRetry

type PublicationRetry struct {
	CommandKey         string      `json:"command_key,omitempty"`
	LessonID           id.ID       `json:"lesson_id"`
	LocalRevision      int64       `json:"local_revision"`
	ExpectedGeneration int64       `json:"expected_generation"`
	Actor              IdentityRef `json:"actor"`
	Reason             string      `json:"reason"`
}

PublicationRetry requests another bounded delivery cycle after a failed one. The service stamps Actor from the authenticated caller.

type PublicationSink

type PublicationSink interface {
	Deliver(context.Context, Publication) (PublicationReceipt, error)
}

PublicationSink delivers immutable outbox payloads. Implementations must reconcile the stable aggregate ID and digest before retrying an ambiguous write. A receipt must come from authoritative destination state, never a search index.

type Publisher

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

Publisher drains scoped lesson outbox records without changing experiment state. Each instance owns one serial delivery loop. The host supplies its scoped context.

func NewPublisher

func NewPublisher(config PublisherConfig) (*Publisher, error)

NewPublisher validates dependencies without starting background work.

func (*Publisher) Retry

func (p *Publisher) Retry(ctx context.Context, request PublicationRetry) (Publication, error)

Retry starts another bounded delivery cycle after current host authorization.

func (*Publisher) Work

func (p *Publisher) Work(ctx context.Context) error

Work polls until canceled. Durable delivery failures are retried with backoff; authorization and persistence failures return to the host supervisor.

func (*Publisher) WorkOnce

func (p *Publisher) WorkOnce(ctx context.Context) error

WorkOnce visits one bounded page. A failed delivery records a retry before returning ErrUnavailable. Later pages remain reachable when earlier rows wait.

type PublisherConfig

type PublisherConfig struct {
	Repository       Repository
	Authorizer       Authorizer
	IdentityResolver IdentityResolver
	Caller           CallerIdentity
	Sink             PublicationSink
	Now              func() time.Time
}

PublisherConfig supplies the destination and current host authority. Now must agree with the repository clock; nil selects the system clock.

type ReadinessState

type ReadinessState string

ReadinessState distinguishes missing, unverified and denied integrations.

const (
	ReadinessReady       ReadinessState = "ready"
	ReadinessUnavailable ReadinessState = "unavailable"
	ReadinessUnknown     ReadinessState = "unknown"
	ReadinessDenied      ReadinessState = "denied"
)

type RecallQuery

type RecallQuery struct {
	Scope         cortex.Scope `json:"scope"`
	Domain        string       `json:"domain"`
	HarnessSchema int          `json:"harness_schema"`
	Query         string       `json:"query"`
	Cutoff        time.Time    `json:"cutoff"`
	Limit         int          `json:"limit"`
	Cursor        string       `json:"cursor,omitempty"`
}

RecallQuery preserves exact scope, compatibility and a frozen time cutoff.

type RecoveryRepository

type RecoveryRepository interface {
	MeterRepository
	GetReservation(context.Context, id.ID, string) (Reservation, error)
	ListReservations(context.Context, id.ID, PageQuery) (Page[Reservation], error)
}

RecoveryRepository supplies durable accounting and bounded reservation reads.

type ReflectionInput

type ReflectionInput struct {
	Evidence   []DiscoveryEvidence `json:"evidence"`
	Candidates []Candidate         `json:"candidates"`
	Domain     string              `json:"domain"`
}

ReflectionInput excludes held-out evaluations, even after a decision exists.

type Repository

type Repository interface {
	GetCreationReceipt(context.Context, string) (CreationReceipt, error)
	Transact(context.Context, func(Transaction) error) error
	GetExperiment(context.Context, id.ID) (Experiment, error)
	GetDiscoveryLessons(context.Context, id.ID) (DiscoveryLessons, error)
	ResolveDiscoveryLessons(context.Context, id.ID, DiscoveryRef) (DiscoveryLessons, error)
	GetArtifact(context.Context, ArtifactRef) (ArtifactRetention, error)
	ListArtifactWork(context.Context, time.Time, PageQuery) (Page[ArtifactRetention], error)
	ListExperiments(context.Context, ListQuery) (Page[Experiment], error)
	ListEvents(context.Context, id.ID, int64, int) (Page[Event], error)
	GetVersion(context.Context, id.ID) (HarnessVersion, error)
	GetReservation(context.Context, id.ID, string) (Reservation, error)
	GetValidationAllocation(context.Context, id.ID) (ValidationAllocation, error)
	GetCandidate(context.Context, id.ID) (Candidate, error)
	GetTrial(context.Context, id.ID) (Trial, error)
	GetEvaluation(context.Context, string) (Evaluation, error)
	GetDecision(context.Context, id.ID) (Decision, error)
	GetActivation(context.Context, id.AgentID, string) (Activation, error)
	GetActivationForKind(context.Context, id.AgentID, string, HarnessKind) (Activation, error)
	ResolveActivation(context.Context, id.ID) (Activation, error)
	GetActivationGeneration(context.Context, id.ID) (Activation, error)
	GetLesson(context.Context, id.ID) (Lesson, error)
	ResolveLesson(context.Context, LessonRef) (Lesson, error)
	GetPublication(context.Context, id.ID, int64) (Publication, error)
	ListVersions(context.Context, VersionQuery) (Page[HarnessVersion], error)
	ListCandidates(context.Context, id.ID, PageQuery) (Page[Candidate], error)
	ListTrials(context.Context, id.ID, TrialQuery) (Page[Trial], error)
	ListEvaluations(context.Context, id.ID, PageQuery) (Page[Evaluation], error)
	ListDecisions(context.Context, id.ID, PageQuery) (Page[Decision], error)
	ListReservations(context.Context, id.ID, PageQuery) (Page[Reservation], error)
	ListValidationAllocations(context.Context, id.ID, PageQuery) (Page[ValidationAllocation], error)
	ListLessons(context.Context, LessonQuery) (Page[Lesson], error)
	ListPublications(context.Context, PublicationQuery) (Page[Publication], error)
	ListActivationHistory(context.Context, id.AgentID, string, PageQuery) (Page[Activation], error)
	ListActivationHistoryForKind(context.Context, id.AgentID, string, HarnessKind, PageQuery) (Page[Activation], error)
	Migrate(context.Context) error
	Ping(context.Context) error
	Close() error
}

Repository owns exactly scoped persistence. Transaction implementations must publish all changes together and return detached resource values.

type RequestEstimator

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

RequestEstimator computes the full token and monetary reservation at dispatch.

func NewRequestEstimator

func NewRequestEstimator(counter InputTokenCounter, pricing Pricing, config RequestEstimatorConfig) (*RequestEstimator, error)

NewRequestEstimator requires explicit token-only mode or frozen pricing.

func (*RequestEstimator) Estimate

func (e *RequestEstimator) Estimate(ctx context.Context, req *llm.Request) (UsageReservation, error)

Estimate includes input and the provider output cap, refusing unknown bounds.

type RequestEstimatorConfig

type RequestEstimatorConfig struct {
	Scope           cortex.Scope
	Reservation     UsageReservation
	Model           string
	ModelRevision   string
	TokenOnly       bool
	MaxRequestBytes int
}

RequestEstimatorConfig binds estimates to one durable logical call. The caller assigns its stable call key before dispatch; retries must reuse that identity.

type Reservation

type Reservation struct {
	Call             *UsageCall        `json:"call,omitempty"`
	Request          UsageReservation  `json:"request"`
	State            ReservationState  `json:"state"`
	Revision         int64             `json:"revision"`
	Settlement       *UsageSettlement  `json:"settlement,omitempty"`
	History          []UsageSettlement `json:"history"`
	DebitedTokens    int64             `json:"debited_tokens"`
	DebitedUSDMicros int64             `json:"debited_usd_micros"`
	CreatedAt        time.Time         `json:"created_at"`
}

Reservation records an upper-bound debit until authoritative settlement.

type ReservationState

type ReservationState string

ReservationState distinguishes conservative debits from settled receipts.

const (
	ReservationHeld    ReservationState = "held"
	ReservationUnknown ReservationState = "unknown"
	ReservationSettled ReservationState = "settled"
)

type Resource

type Resource struct {
	Scope   cortex.Scope `json:"scope"`
	AgentID id.AgentID   `json:"agent_id"`
	ID      id.ID        `json:"id"`
	Kind    string       `json:"kind"`
}

Resource carries exact scope and resource identity to host authorization.

type ResourcePage

type ResourcePage[T any] struct {
	Items      []T    `json:"items"`
	NextCursor string `json:"next_cursor,omitempty"`
	Complete   bool   `json:"complete"`
}

ResourcePage is an operator-facing page. Complete describes this collection, not the experiment's execution state. No total is inferred from a cursor.

type RetainDecision

type RetainDecision struct {
	DecisionID id.ID  `json:"decision_id"`
	Reason     string `json:"reason"`
}

RetainDecision binds an operator's reason to the measured decision being reviewed. It does not replace that decision or change a production activation.

func (RetainDecision) Validate

func (r RetainDecision) Validate() error

Validate checks bounded review content and the decision identity kind.

type RetainRequest

type RetainRequest struct {
	CommandRequest
	RetainDecision
}

RetainRequest supplies the reviewed decision, revision and durable command key.

type RetainedBaseline

type RetainedBaseline struct {
	DecisionID id.ID       `json:"decision_id"`
	Baseline   VersionRef  `json:"baseline"`
	Actor      IdentityRef `json:"actor"`
	Reason     string      `json:"reason"`
	CreatedAt  time.Time   `json:"created_at"`
}

RetainedBaseline is a transaction-stamped human review, separate from the immutable measured decision. It closes adoption of this experiment's candidate.

type RetryLessonRequest

type RetryLessonRequest struct {
	LessonID           id.ID  `json:"lesson_id"`
	LocalRevision      int64  `json:"local_revision"`
	ExpectedGeneration int64  `json:"expected_generation"`
	Reason             string `json:"reason"`
	IdempotencyKey     string `json:"idempotency_key"`
}

RetryLessonRequest identifies a bounded delivery cycle and its operator command.

type RevokeLessonRequest

type RevokeLessonRequest struct {
	LessonID         id.ID  `json:"lesson_id"`
	ExpectedRevision int64  `json:"expected_revision"`
	Reason           string `json:"reason"`
	IdempotencyKey   string `json:"idempotency_key"`
}

RevokeLessonRequest withdraws local eligibility before remote delivery resumes.

type RollbackRequest

type RollbackRequest struct {
	Kind               HarnessKind `json:"kind,omitempty"`
	ID                 id.ID       `json:"id"`
	AgentID            id.AgentID  `json:"agent_id"`
	Channel            string      `json:"channel"`
	TargetID           id.ID       `json:"target_id"`
	ExpectedGeneration int64       `json:"expected_generation"`
	Reason             string      `json:"reason"`
}

RollbackRequest appends a generation referring to a previous activation.

type Split

type Split string

Split keeps controller-visible discovery separate from held-out validation.

const (
	SplitDiscovery  Split = "discovery"
	SplitValidation Split = "validation"
)

type State

type State string

State records experiment lifecycle independently of the active phase.

const (
	StateDraft           State = "draft"
	StateQueued          State = "queued"
	StateRunning         State = "running"
	StatePaused          State = "paused"
	StateReviewRequired  State = "review_required"
	StateCompleted       State = "completed"
	StateCancelled       State = "cancelled"
	StateFailed          State = "failed"
	StateBudgetExhausted State = "budget_exhausted"
)

type StopReceipt

type StopReceipt struct {
	EnvironmentReceiptID string     `json:"environment_receipt_id"`
	AttemptID            id.ID      `json:"attempt_id"`
	Fence                Fence      `json:"fence"`
	State                StopState  `json:"state"`
	Evidence             ContentRef `json:"evidence"`
	ObservedAt           time.Time  `json:"observed_at"`
}

StopReceipt records authoritative containment for a fenced attempt.

func (StopReceipt) Validate

func (receipt StopReceipt) Validate() error

Validate requires concrete containment evidence for a confirmed stop.

type StopState

type StopState string

StopState distinguishes positive containment evidence from an ambiguous reply.

const (
	StopTerminated  StopState = "terminated"
	StopQuarantined StopState = "quarantined"
	StopUnknown     StopState = "unknown"
)

type TaskCase

type TaskCase struct {
	ID                  string       `json:"id"`
	Input               string       `json:"input"`
	EnvironmentSnapshot ContentRef   `json:"environment_snapshot"`
	Context             []ContentRef `json:"context"`
	DatasetItem         *ContentRef  `json:"dataset_item,omitempty"`
	Split               Split        `json:"split"`
	InputDigest         string       `json:"input_digest"`
	Digest              string       `json:"digest"`
}

TaskCase freezes input and environment identity. Private answers belong to the evaluator's plan and must never be placed in this controller-visible record.

func SealTaskCase

func SealTaskCase(task TaskCase) (TaskCase, error)

SealTaskCase detaches context and hashes original execution content. Input allocation identity normalizes line endings and surrounding whitespace only.

type TaskPolicy

type TaskPolicy struct {
	Deadline       time.Time             `json:"deadline"`
	Isolation      IsolationCapabilities `json:"isolation"`
	AdoptionPolicy *ContentRef           `json:"adoption_policy,omitempty"`
}

TaskPolicy freezes host isolation and optional artifact adoption policy. A nil adoption policy permits returning output but forbids artifact adoption.

type TaskResult

type TaskResult struct {
	ExperimentID  id.ID              `json:"experiment_id"`
	Trial         Trial              `json:"trial"`
	Output        string             `json:"output"`
	Artifacts     []ArtifactRef      `json:"artifacts"`
	EvidenceClass EvidenceClass      `json:"evidence_class"`
	Decision      Decision           `json:"decision"`
	Evidence      []DecisionEvidence `json:"evidence"`
}

TaskResult returns the selected capture and every trial outcome for review. No execution or artifact adoption occurs when reading a completed result.

type TaskSelection

type TaskSelection struct {
	TrialID id.ID   `json:"trial_id"`
	Score   float64 `json:"score"`
}

TaskSelection identifies an already completed trial. Its score is contrastive evidence for this task, not a confidence estimate or an activation approval.

type TaskSpec

type TaskSpec struct {
	Bundle         ExperimentBundle      `json:"bundle"`
	Isolation      IsolationCapabilities `json:"isolation"`
	AdoptionPolicy *ContentRef           `json:"adoption_policy,omitempty"`
}

TaskSpec carries one discovery task, frozen versions and evaluator criteria. Limits and budget are host-approved; zero rounds default to one.

type TokenPrice

type TokenPrice struct {
	Model                     string
	ModelRevision             string
	PricingRevision           string
	PromptUSDMicrosPerMillion int64
	OutputUSDMicrosPerMillion int64
	RequestUSDMicros          int64
}

TokenPrice is a host-approved upper bound for one model and pricing revision. Rates are USD micro-units per million tokens. RequestUSDMicros covers a fixed per-call charge. Hosts must account for every billable category in these bounds or provide a different Pricing implementation. No rates are fetched implicitly.

type TokenPricing

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

TokenPricing implements Pricing with immutable host-supplied token rates. A quote is an estimate, not evidence of the provider's final charge.

func NewTokenPricing

func NewTokenPricing(rates TokenPrice) (*TokenPricing, error)

NewTokenPricing freezes the supplied rates. Explicit zero rates are supported for free or deterministic fixture providers; omitted revisions are refused.

func (*TokenPricing) Price

func (p *TokenPricing) Price(ctx context.Context, usage UsageEstimate) (MoneyEstimate, error)

Price verifies the frozen model binding and rounds each token category's charge upward to a whole USD micro-unit before adding the fixed request charge. Intermediate arithmetic is exact; a result above int64 fails without a quote.

type Transaction

type Transaction interface {
	CreateExperimentCommand(CreationCommand) (CreationReceipt, error)
	RegisterArtifact(ArtifactRegistration) error
	BeginArtifactDeletion(ArtifactDeletion) error
	CompleteArtifactDeletion(ArtifactRef, string) error
	CreateExperiment(ExperimentBundle) error
	PutDiscoveryLessons(DiscoveryLessonsRequest) (DiscoveryLessons, error)
	CommitTransition(Transition) error
	ClaimWork(ClaimRequest) (WorkLease, error)
	RenewLease(WorkLease) error
	Reserve(UsageReservation) (Reservation, error)
	BeginUsageCall(UsageReservation, string) (Reservation, error)
	Settle(UsageSettlement) error
	ReconcileUsage(UsageReconciliation) error
	AllocateValidation(ValidationAllocationRequest) (ValidationAllocation, error)
	ExposeValidation(ValidationAccess) error
	ReleaseValidation(ValidationAccess) error
	Deactivate(DeactivationChange) (Activation, error)
	CompareAndSwapActivation(ActivationChange) (Activation, error)
	PutPublication(PublicationRequest) error
	ClaimPublication(PublicationClaim) (Publication, error)
	RetryPublication(PublicationRetry) error
	CompletePublication(PublicationLease, PublicationReceipt) error
	FailPublication(PublicationLease, string, time.Time, bool) error
	RevokeLesson(LessonRevocation) error
}

Transaction is valid only during its synchronous callback. Callers must not retain it or use it from concurrent goroutines.

type Transition

type Transition struct {
	Retain *RetainDecision `json:"retain,omitempty"`
	// CommandAction binds operator retries to their lifecycle intent. Omitted
	// values retain the digest of existing host and worker transitions.
	CommandAction    Action               `json:"command_action,omitempty"`
	Decision         *Decision            `json:"decision,omitempty"`
	ExperimentID     id.ID                `json:"experiment_id"`
	ExpectedRevision int64                `json:"expected_revision"`
	NextState        State                `json:"next_state"`
	NextPhase        Phase                `json:"next_phase"`
	Lease            WorkLease            `json:"lease"`
	IdempotencyKey   string               `json:"idempotency_key"`
	Actor            IdentityRef          `json:"actor"`
	Candidates       []Candidate          `json:"candidates,omitempty"`
	Versions         []HarnessVersion     `json:"versions,omitempty"`
	Trials           []Trial              `json:"trials,omitempty"`
	TrialUpdates     []TrialUpdate        `json:"trial_updates,omitempty"`
	Evaluations      []Evaluation         `json:"evaluations,omitempty"`
	Publications     []PublicationRequest `json:"publications,omitempty"`
}

Transition binds a requested state change to its prior revision and actor. Idempotency keys can be reused only with identical request content.

type Trial

type Trial struct {
	ID           id.ID            `json:"id"`
	ExperimentID id.ID            `json:"experiment_id"`
	CandidateID  id.ID            `json:"candidate_id,omitempty"`
	AllocationID id.ID            `json:"allocation_id,omitempty"`
	Split        Split            `json:"split"`
	Version      VersionRef       `json:"version"`
	CaseID       string           `json:"case_id"`
	CaseDigest   string           `json:"case_digest"`
	Repetition   int              `json:"repetition"`
	State        TrialState       `json:"state"`
	Revision     int64            `json:"revision"`
	Attempts     []Attempt        `json:"attempts"`
	Execution    *ExecutionRecord `json:"execution,omitempty"`
	EvaluationID string           `json:"evaluation_id,omitempty"`
	Error        string           `json:"error,omitempty"`
	CreatedAt    time.Time        `json:"created_at"`
}

Trial identifies one arm, case and repetition. A nil candidate is the baseline.

type TrialAllowance

type TrialAllowance struct {
	MaxTokens       int64  `json:"max_tokens"`
	MaxUSDMicros    int64  `json:"max_usd_micros"`
	PricingRevision string `json:"pricing_revision"`
}

TrialAllowance is a host-approved bound for every charged operation in a trial. The environment must enforce these limits, including model, tool and retrieval work.

type TrialConfig

type TrialConfig struct {
	Repository       Repository
	Authorizer       Authorizer
	IdentityResolver IdentityResolver
	Environments     EnvironmentFactory
	Allowance        TrialAllowance
	Evaluator        Evaluator
}

TrialConfig binds trial execution to host isolation, accounting and recorded scoring.

type TrialEnvironment

TrialEnvironment reconnects to one attempt. Close releases the client handle; only EnvironmentFactory.Stop can establish remote termination or quarantine.

type TrialPhaseHandler

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

TrialPhaseHandler advances durable execution and captured evaluation steps.

func NewTrialPhaseHandler

func NewTrialPhaseHandler(config TrialConfig) (*TrialPhaseHandler, error)

NewTrialPhaseHandler installs host adapters without starting any work.

func (*TrialPhaseHandler) Execute

func (h *TrialPhaseHandler) Execute(ctx context.Context, item WorkItem) (Transition, error)

Execute advances one serial operation or a bounded parallel batch.

type TrialPlan

type TrialPlan struct {
	DiscoveryTrials         int `json:"discovery_trials"`
	ValidationTrials        int `json:"validation_trials"`
	TotalTrials             int `json:"total_trials"`
	DistinctValidationCases int `json:"distinct_validation_cases"`
}

TrialPlan reserves final validation capacity before discovery is scheduled.

func Preflight

func Preflight(spec ExperimentSpec) (TrialPlan, error)

Preflight counts the maximum permitted discovery and final paired trials, including baseline and composed candidates, with overflow-safe arithmetic.

type TrialQuery

type TrialQuery struct {
	PageQuery
	VersionID id.ID      `json:"version_id,omitempty"`
	Split     Split      `json:"split,omitempty"`
	State     TrialState `json:"state,omitempty"`
}

TrialQuery filters one experiment's immutable trial identities and current state.

type TrialRequest

type TrialRequest struct {
	// Allowance and Limits must be enforced by the host environment.
	Allowance    TrialAllowance `json:"allowance"`
	Limits       Limits         `json:"limits"`
	Scope        cortex.Scope   `json:"scope"`
	ExperimentID id.ID          `json:"experiment_id"`
	TrialID      id.ID          `json:"trial_id"`
	AttemptID    id.ID          `json:"attempt_id"`
	Task         TaskCase       `json:"task"`
	Version      VersionRef     `json:"version"`
	Fence        Fence          `json:"fence"`
	Deadline     time.Time      `json:"deadline"`
}

TrialRequest provisions one idempotent attempt from a frozen task snapshot.

type TrialState

type TrialState string

TrialState distinguishes an unknown external effect from a confirmed failure.

const (
	TrialQueued      TrialState = "queued"
	TrialRunning     TrialState = "running"
	TrialCompleted   TrialState = "completed"
	TrialFailed      TrialState = "failed"
	TrialCancelled   TrialState = "cancelled"
	TrialBlocked     TrialState = "blocked"
	TrialUnknown     TrialState = "unknown"
	TrialInvalidated TrialState = "invalidated"
)

type TrialUpdate

type TrialUpdate struct {
	TrialID                 id.ID               `json:"trial_id"`
	ExpectedRevision        int64               `json:"expected_revision"`
	State                   TrialState          `json:"state"`
	StartAttemptID          id.ID               `json:"start_attempt_id,omitempty"`
	AttemptID               id.ID               `json:"attempt_id,omitempty"`
	ExpectedAttemptRevision int64               `json:"expected_attempt_revision"`
	Receipt                 *EnvironmentReceipt `json:"receipt,omitempty"`
	Stop                    *StopReceipt        `json:"stop,omitempty"`
	Execution               *ExecutionRecord    `json:"execution,omitempty"`
	RetryApproval           *ContentRef         `json:"retry_approval,omitempty"`
	Error                   string              `json:"error,omitempty"`
}

TrialUpdate changes execution state without replacing the frozen trial identity. StartAttemptID creates a new attempt; all other writes fence the current one.

type Usage

type Usage struct {
	Tokens          int64        `json:"tokens"`
	TokenQuality    UsageQuality `json:"token_quality"`
	USDMicros       int64        `json:"usd_micros"`
	MoneyQuality    UsageQuality `json:"money_quality"`
	PricingRevision string       `json:"pricing_revision,omitempty"`
	Receipt         string       `json:"receipt,omitempty"`
}

Usage keeps token and money provenance separate. Missing quality is unknown.

func OrchestrationChildUsage

func OrchestrationChildUsage(policy orchestration.BudgetPolicy, reservation execution.Reservation) (Usage, error)

OrchestrationChildUsage reads measured dimensions from a host-authenticated settlement. Missing receipts remain unknown; reserved capacity is never usage.

func OrchestrationUsage

func OrchestrationUsage(capture OrchestrationExecution) (Usage, error)

OrchestrationUsage aggregates original receipts, retaining unknown dimensions and observed lower bounds. It never reads BudgetSnapshot.Charged as usage.

func (Usage) KnownCost

func (usage Usage) KnownCost() (int64, bool)

KnownCost exposes a comparable price only when its provenance is explicit.

func (Usage) Validate

func (usage Usage) Validate() error

Validate refuses negative quantities and unqualified priced receipts.

type UsageCall

type UsageCall struct {
	RequestDigest string    `json:"request_digest"`
	StartedAt     time.Time `json:"started_at"`
	Lease         WorkLease `json:"lease"`
}

UsageCall records that a provider operation may have started. It is written before dispatch and never grants a second dispatch after an unknown outcome.

func (UsageCall) Validate

func (call UsageCall) Validate() error

Validate checks the immutable request binding and durable dispatch authority.

type UsageEstimate

type UsageEstimate struct {
	Model           string `json:"model"`
	ModelRevision   string `json:"model_revision"`
	PromptTokens    int64  `json:"prompt_tokens"`
	OutputTokens    int64  `json:"output_tokens"`
	PricingRevision string `json:"pricing_revision"`
}

UsageEstimate binds conservative token bounds to a resolved provider model.

type UsageEstimator

type UsageEstimator interface {
	Estimate(context.Context, *llm.Request) (UsageReservation, error)
}

UsageEstimator operates on the actual provider request at the call boundary.

type UsageQuality

type UsageQuality string

UsageQuality describes accounting provenance, independently of result quality.

const (
	UsageKnown     UsageQuality = "known"
	UsageEstimated UsageQuality = "estimated"
	UsageUnknown   UsageQuality = "unknown"
)

type UsageReceiptProvider

type UsageReceiptProvider interface {
	Recover(context.Context, Reservation) (VerifiedUsageReceipt, error)
}

UsageReceiptProvider looks up existing accounting evidence without replaying the original operation. Ambiguous or missing evidence returns an error.

type UsageReconciliation

type UsageReconciliation struct {
	Settlement       UsageSettlement `json:"settlement"`
	RequestDigest    string          `json:"request_digest"`
	ExpectedRevision int64           `json:"expected_revision"`
	Actor            IdentityRef     `json:"actor"`
}

UsageReconciliation applies a verified late receipt without granting dispatch. ExpectedRevision fences concurrent observations; Actor is the recovery caller.

type UsageRecovery

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

UsageRecovery reconciles existing dispatches after cancellation or lease loss.

func NewUsageRecovery

func NewUsageRecovery(repo RecoveryRepository, auth Authorizer, resolver IdentityResolver, provider UsageReceiptProvider) (*UsageRecovery, error)

NewUsageRecovery requires host authority and an explicit receipt verifier.

func (*UsageRecovery) Recover

func (r *UsageRecovery) Recover(ctx context.Context, experimentID id.ID, key string, actor IdentityRef) error

Recover accepts a host-attributed actor, never an agent-provided subject. It rechecks current caller and original requester grants after receipt retrieval.

type UsageReservation

type UsageReservation struct {
	ExperimentID    id.ID          `json:"experiment_id"`
	AttemptID       id.ID          `json:"attempt_id"`
	CallKey         string         `json:"call_key"`
	Operation       OperationClass `json:"operation"`
	MaxTokens       int64          `json:"max_tokens"`
	MaxUSDMicros    int64          `json:"max_usd_micros"`
	PricingRevision string         `json:"pricing_revision"`
	Lease           WorkLease      `json:"lease"`
	ExpiresAt       time.Time      `json:"expires_at"`
}

UsageReservation binds an upper bound to one durable external call key.

type UsageSettlement

type UsageSettlement struct {
	ExperimentID id.ID     `json:"experiment_id"`
	CallKey      string    `json:"call_key"`
	AttemptID    id.ID     `json:"attempt_id"`
	Receipt      string    `json:"receipt"`
	Usage        Usage     `json:"usage"`
	Complete     bool      `json:"complete"`
	Lease        WorkLease `json:"lease"`
	ObservedAt   time.Time `json:"observed_at"`
}

UsageSettlement is idempotent by receipt and never hides observed overruns.

type ValidationAccess

type ValidationAccess struct {
	AllocationID id.ID     `json:"allocation_id"`
	ExperimentID id.ID     `json:"experiment_id"`
	Lease        WorkLease `json:"lease"`
}

ValidationAccess identifies the current worker consuming or releasing holdout. Only the owner can release an allocation; an exposure must name a frozen arm.

type ValidationAllocation

type ValidationAllocation struct {
	CreatedAt    time.Time       `json:"created_at"`
	ID           id.ID           `json:"id"`
	Scope        cortex.Scope    `json:"scope"`
	AgentID      id.AgentID      `json:"agent_id"`
	ExperimentID id.ID           `json:"experiment_id"`
	CaseDigests  []string        `json:"case_digests"`
	InputDigests []string        `json:"input_digests"`
	DatasetItems []ContentRef    `json:"dataset_items"`
	PairedRoster []ValidationArm `json:"paired_roster"`
	ExposedAt    time.Time       `json:"exposed_at"`
	ReleasedAt   time.Time       `json:"released_at"`
	Revision     int64           `json:"revision"`
}

ValidationAllocation permanently tracks holdout exposure per scope and agent.

type ValidationAllocationRequest

type ValidationAllocationRequest struct {
	ID           id.ID           `json:"id"`
	ExperimentID id.ID           `json:"experiment_id"`
	PairedRoster []ValidationArm `json:"paired_roster"`
	Lease        WorkLease       `json:"lease"`
}

ValidationAllocationRequest freezes one experiment or a parent's paired child roster. Cases are taken from the stored specification, never caller hashes.

type ValidationArm

type ValidationArm struct {
	CaseDigests  []string   `json:"case_digests,omitempty"`
	Controller   VersionRef `json:"controller"`
	ExperimentID id.ID      `json:"experiment_id"`
	Baseline     VersionRef `json:"baseline"`
	Finalist     VersionRef `json:"finalist"`
}

ValidationArm pins the only child allowed to use an arm of a paired allocation.

type VerifiedUsageReceipt

type VerifiedUsageReceipt struct {
	RequestDigest string
	Settlement    UsageSettlement
}

VerifiedUsageReceipt is returned only after the host verifies provider receipt provenance and its exact dispatch digest. Recovery cannot execute another call.

type VersionQuery

type VersionQuery struct {
	PageQuery
	AgentID id.AgentID  `json:"agent_id,omitempty"`
	Kind    HarnessKind `json:"kind,omitempty"`
}

VersionQuery filters immutable harness versions within the exact scope.

type VersionRef

type VersionRef struct {
	ID     id.ID  `json:"id"`
	Digest string `json:"digest"`
}

VersionRef binds a stored immutable version to the expected content.

type WorkItem

type WorkItem struct {
	Experiment Experiment
	Lease      WorkLease
}

WorkItem contains a frozen experiment snapshot and current persistence fence.

type WorkLease

type WorkLease struct {
	ParentGeneration int64     `json:"parent_generation,omitempty"`
	ExperimentID     id.ID     `json:"experiment_id"`
	Owner            string    `json:"owner"`
	Generation       int64     `json:"generation"`
	ExpiresAt        time.Time `json:"expires_at"`
}

WorkLease fences persisted writes from replaced workers.

type WorkerConfig

type WorkerConfig struct{ LeaseDuration, HeartbeatInterval, PollInterval time.Duration }

WorkerConfig bounds an experiment worker's lease, renewal and idle polling.

func DefaultWorkerConfig

func DefaultWorkerConfig() WorkerConfig

DefaultWorkerConfig uses a thirty-second lease with ten-second renewal.

Directories

Path Synopsis
Package artifacts coordinates protected content with optimization retention.
Package artifacts coordinates protected content with optimization retention.
internal
canonical
Package canonical encodes versioned optimization content and rejects ambiguous JSON.
Package canonical encodes versioned optimization content and rejects ambiguous JSON.
Package operator shares typed request adapters between HTTP and dashboard transports.
Package operator shares typed request adapters between HTTP and dashboard transports.
Package store exposes optimization persistence ports for backend implementers.
Package store exposes optimization persistence ports for backend implementers.
internal/scoped
Package scoped shares exact-scope index construction across storage adapters.
Package scoped shares exact-scope index construction across storage adapters.
internal/sqlstore
Package sqlstore shares transactional record persistence across SQL backends.
Package sqlstore shares transactional record persistence across SQL backends.
internal/state
Package state shares optimization storage invariants across persistence adapters.
Package state shares optimization storage invariants across persistence adapters.
memory
Package memory provides process-local optimization storage for tests and fixtures.
Package memory provides process-local optimization storage for tests and fixtures.
mongo
Package mongo persists optimization records in MongoDB snapshot transactions.
Package mongo persists optimization records in MongoDB snapshot transactions.
postgres
Package postgres persists optimization state with PostgreSQL transactions.
Package postgres persists optimization state with PostgreSQL transactions.
sqlite
Package sqlite persists optimization state in SQLite through Grove transactions.
Package sqlite persists optimization state in SQLite through Grove transactions.
storetest
Package storetest runs the same optimization storage checks against each backend.
Package storetest runs the same optimization storage checks against each backend.

Jump to

Keyboard shortcuts

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