preflight

package
v0.59.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package preflight is the shared eligibility evaluator behind the required-tools preflight (Spec 098): given a caller-supplied tool ID and a caller context, it answers `ready` or exactly one failure reason from a closed 15-code enum, by a fixed precedence chain.

Two invariants define this package and must survive every future change:

  1. ZERO UPSTREAM I/O, ZERO RUNTIME MUTATION (FR-006). The evaluator reads only the narrow interfaces in evaluator.go — an index reader, an approval reader, a connection-state reader and a config-policy reader. It cannot reach a transport, an upstream client, a reconnect path or an index writer, because none of those types are reachable from here: the package imports no transport, no runtime and no upstream package. In particular a preflight must NEVER call index ForProfile (it lazily creates and caches per-profile indexes, i.e. mutation) — profile semantics are "shared index existence + profile scope filter", nothing more.

  2. AN INFRASTRUCTURE ERROR IS AN ERROR, NEVER A REASON CODE. When the index, the approval store or the config-policy read fails, Evaluate returns an error and the caller answers 503. A reason code is a statement about the proxy's state; fabricating one from a failed read would make the whole taxonomy untrustworthy — an operator would chase a `not_found` that was really a BBolt hiccup. The only "absence" that legitimately becomes a reason is an absence the reader reported successfully.

The reason enum, its classes, retryability, default actions, the precedence chain and the set-verdict/exit-code mapping all live in reasons.go as the single source of truth; internal/contracts mirrors them for the wire and a drift test keeps the two identical.

Index

Constants

View Source
const (
	ApprovalStatusApproved = "approved"
	ApprovalStatusPending  = "pending"
	ApprovalStatusChanged  = "changed"
)

Tool-approval status values, mirrored from internal/storage (ToolApprovalStatus*). They are duplicated rather than imported so this package stays a leaf with no storage dependency; a unit test asserts the mirror is exact, so the duplication cannot drift.

View Source
const (
	ExitReady             = 0
	ExitDegradedRetryable = 10
	ExitBlocked           = 11
	ExitUnknownIDs        = 12
)

CLI exit codes (FR-009). Worst class present wins: 12 > 11 > 10 > 0.

View Source
const MaxSuggestions = 3

MaxSuggestions caps `did_you_mean` at three entries (FR-013): enough to fix a typo, too few to enumerate a corpus.

View Source
const MaxWaitMS = 10000

MaxWaitMS is the FR-012 cap on a request's wait budget. It lives here so the REST validator and the CLI flag check the same number: the CLI has to know it because it converts a duration to milliseconds, and a lossy conversion would otherwise smuggle an out-of-range wait past the daemon's own check as a rounded, in-range one.

Variables

View Source
var (
	// ErrUnknownProfile means the request named a profile that is not
	// configured. The served surface answers 400 (FR-010) — it is a caller
	// mistake, not proxy state, and inventing a verdict for it would put a
	// request bug into the reason taxonomy.
	ErrUnknownProfile = errors.New("preflight: unknown profile")
	// ErrRuntimeUnavailable means the process is too degraded to evaluate
	// honestly (no storage, no index, no live config). The served surface
	// answers 503 rather than emit reduced-fidelity verdicts (FR-006).
	ErrRuntimeUnavailable = errors.New("preflight: runtime unavailable")
)

Sentinel errors the GLUE returns for conditions the served surface must map to a specific HTTP status. Everything else that comes back from a preflight is an infrastructure read failure (FR-006) and answers 503.

Precedence is the fixed FR-004 chain: for one ID, the first reason in this order that applies wins. It covers every enum member exactly once — the two annotation reasons sit in the final "annotation filters" slot, where missing_annotation and policy_filtered are mutually exclusive per owning filter and therefore unordered relative to each other in practice.

Functions

func DefaultAction

func DefaultAction(code Reason) string

DefaultAction returns the health-vocabulary action for a reason, or "" when the reason has no action (the field is then omitted from the response). server_unhealthy's action is a best-effort default that the evaluator may override from spec 044 diagnostics.

func DefaultRemediation

func DefaultRemediation(code Reason) string

DefaultRemediation returns the one actionable instruction for a reason.

func ExitCode

func ExitCode(v Verdict) int

ExitCode maps a set verdict to the CLI exit code (FR-009).

func FormatPin

func FormatPin(schemaVersion uint64, hash string) string

FormatPin renders a stored hash as the wire pin format "sha256/v{HashSchemaVersion}:{hex}".

func ParsePin

func ParsePin(pin string) (schemaVersion uint64, hash string, err error)

ParsePin decodes a pin string. The schema version is part of the format so a proxy-side hash-algorithm bump is distinguishable from genuine upstream drift (it changes `detail`, not the reason code).

func Retryable

func Retryable(code Reason) bool

Retryable reports whether waiting can plausibly clear the reason. Unknown codes are non-retryable.

func Suggest

func Suggest(want string, candidates []string) []string

Suggest returns up to MaxSuggestions candidate ids nearest to want.

Candidates MUST already be filtered to what the caller may see: in-scope, non-quarantined servers only (a quarantined server's tools are never suggested — FR-013 — and they are not indexed in the first place). The function itself performs no filtering and no I/O; it is pure string work, so the visibility decision stays in one place (the evaluator's corpus builder).

Ranking: prefix relationships first (a truncated or over-typed id is the most common miss), then smaller edit distance, then lexicographic order for a deterministic response. Exact matches are never suggested — if the id existed the caller would not be seeing not_found.

func ValidReason

func ValidReason(code Reason) bool

ValidReason reports whether code is a member of the closed v1 enum.

Types

type ApprovalReader

type ApprovalReader interface {
	// ToolApproval returns the record for a tool, or (nil, nil) when no record
	// exists (the implicit-approved default). It must return an error ONLY for
	// genuine infrastructure failures — "no record" is not an error.
	ToolApproval(serverName, toolName string) (*ApprovalState, error)
}

ApprovalReader reads spec 032 tool-approval records.

type ApprovalState

type ApprovalState struct {
	Status            string
	Disabled          bool
	CurrentHash       string
	HashSchemaVersion uint64
}

ApprovalState is the narrow read of a spec 032 ToolApprovalRecord. A nil *ApprovalState means "no record", which is the implicit-approved default — NOT an error and NOT a pending state.

type Class

type Class = string

Class groups reasons by what an operator must do about them. It drives the set verdict and therefore the CLI exit code.

const (
	// ClassRetryable: waiting may fix it (the proxy is mid-transition).
	ClassRetryable Class = "retryable"
	// ClassFixState: an operator action on live state fixes it (approve,
	// enable, log in, re-lock a pin).
	ClassFixState Class = "fix_state"
	// ClassPermanentConfig: nothing changes until configuration or the request
	// itself changes.
	ClassPermanentConfig Class = "permanent"
)

func ReasonClass

func ReasonClass(code Reason) Class

ReasonClass returns the remediation class of a reason. Unknown codes are treated as permanent-config, matching the documented consumer rule ("treat unknown codes as non-retryable").

type ClassifyInputs

type ClassifyInputs struct {
	Server ServerPolicy
	// QuarantineEnabled is the GLOBAL quarantine switch (config.IsQuarantineEnabled()).
	QuarantineEnabled bool
	// ConfigDenied is the operator's enabled_tools/disabled_tools verdict.
	ConfigDenied bool
	// Approval is the tool's approval record, or nil when none exists.
	Approval *ApprovalState
}

ClassifyInputs are the locally-read facts the shared classifier needs. Every field is a plain value: the classifier performs no I/O, so it is callable from dispatch (latency-sensitive) and from the evaluator alike.

type ConfigPolicy

type ConfigPolicy interface {
	// ServerPolicy returns the config view of a server. A missing server is
	// reported as ServerPolicy{Found: false}, NOT as an error.
	ServerPolicy(serverName string) (ServerPolicy, error)
	// ToolConfigDenied reports the enabled_tools / disabled_tools verdict.
	ToolConfigDenied(serverName, toolName string) (bool, error)
	// QuarantineEnabled is the global quarantine switch.
	QuarantineEnabled() bool
}

ConfigPolicy reads configuration-derived policy.

type EvalContext

type EvalContext struct {
	Index     IndexReader
	Approvals ApprovalReader
	State     StateReader
	Policy    ConfigPolicy

	// Tier selects the disclosure rules (FR-013).
	Tier Tier
	// Scope is the effective evaluation scope (token scope ∩ token pin ∩
	// requested profile — see ResolveScope). nil means unrestricted.
	Scope *Scope
	// Filters are the caller's annotation policy filters (spec 094 semantics).
	Filters toolannotations.Filters
	// Pins maps a requested id to its pin string, for callers that carry pins
	// separately from the refs. A ToolRef.PinHash always wins over this map.
	Pins map[string]string
	// RequireRuntimeEntry says the State reader is the served, authoritative
	// snapshot. A configured server missing from it is state that has not been
	// PUBLISHED yet (the stateview starts empty and fills per-server
	// asynchronously — startup, first reconcile, config-add windows), so the
	// evaluator answers the retryable server_initializing verdict instead of
	// claiming ready/not_found from the gap (FR-005) — and instead of a 503,
	// which would misreport a healthy-but-not-caught-up runtime as broken.
	//
	// It stays false for pure-unit evaluations, which legitimately run with a
	// nil or partial StateReader and expect the evaluator to make no connection
	// claim at all. ErrRuntimeUnavailable remains the GLUE's refusal for a
	// runtime that is wired but has no stateview snapshot object at all.
	RequireRuntimeEntry bool
}

EvalContext carries everything one evaluation needs. It is a value: build it per request, never share it across requests.

type IndexReader

type IndexReader interface {
	// ToolsByServer returns the indexed tools for one server. A server with no
	// indexed tools returns an empty slice and a nil error.
	ToolsByServer(serverName string) ([]IndexedTool, error)
	// IndexedServerNames returns every server present in the shared index.
	IndexedServerNames() ([]string, error)
}

IndexReader reads the SHARED search index. Note what is absent: no per-profile index accessor. index.Manager.ForProfile lazily CREATES and caches a profile index — a mutation — so a preflight must never call it. Profile semantics here are "shared-index existence + profile scope filter".

type IndexedTool

type IndexedTool struct {
	Name        string
	Annotations *config.ToolAnnotations
}

IndexedTool is the slice of indexed metadata the evaluator uses: identity and annotations. Name may be either "server:tool" or the bare tool name — the evaluator normalizes both, exactly like the search paths do.

type Outcome

type Outcome struct {
	Verdict Verdict
	Results []Result
}

Outcome is one evaluated preflight: the per-tool results in request order plus the set-level verdict derived from them.

type Params

type Params struct {
	// Tools are the requested refs, already deduplicated by the caller, in
	// first-occurrence order.
	Tools []ToolRef
	// Tier selects the disclosure rules (FR-013). Defaults to TierOperator when
	// empty — the caller must set TierAgentToken explicitly, so a new call site
	// cannot accidentally get the more permissive disclosure.
	Tier Tier
	// Profile is the profile named in the request body ("" = unscoped operator
	// view).
	Profile string
	// TokenServers is the agent token's allowed_servers list (nil for operator
	// callers).
	TokenServers []string
	// TokenProfilePin is the profile an agent token is pinned to, propagated
	// through REST auth (Spec 057 / review finding 11). It can only narrow the
	// evaluation scope, never widen it.
	TokenProfilePin string
	// Filters are the caller's annotation policy filters (spec 094 semantics).
	Filters toolannotations.Filters
}

Params is one preflight request as the glue layer receives it: the caller's identity-derived inputs (tier, token scope, token profile pin) plus the request's own inputs (tool refs, profile, policy filters).

It carries NAMES, not resolved scopes: resolving a profile slug to its server set requires the live config, which only the glue can read. That is also where an unknown profile becomes ErrUnknownProfile.

type Reason

type Reason = string

Reason is the closed v1 failure-reason enum (Spec 098 FR-003). Evolution is additive-only and consumers must treat an unknown code as non-retryable.

`server_saturated` is RESERVED (spec 093 queue saturation) and deliberately not defined here: defining it would put it in AllReasons and therefore in the generated wire enum, promising a verdict nothing emits.

const (
	ReasonServerInitializing  Reason = "server_initializing"
	ReasonServerUnhealthy     Reason = "server_unhealthy"
	ReasonServerDisabled      Reason = "server_disabled"
	ReasonServerQuarantined   Reason = "server_quarantined"
	ReasonToolPendingApproval Reason = "tool_pending_approval"
	ReasonToolChanged         Reason = "tool_changed"
	ReasonToolBlockedByUser   Reason = "tool_blocked_by_user"
	ReasonOAuthRequired       Reason = "oauth_required"
	ReasonHashMismatch        Reason = "hash_mismatch"
	ReasonServerNotInScope    Reason = "server_not_in_scope"
	ReasonToolDeniedByConfig  Reason = "tool_denied_by_config"
	ReasonMissingAnnotation   Reason = "missing_annotation"
	ReasonPolicyFiltered      Reason = "policy_filtered"
	ReasonNotFound            Reason = "not_found"
	ReasonServerNotConfigured Reason = "server_not_configured"
)

func AllReasons

func AllReasons() []Reason

AllReasons returns the enum in precedence order (a stable, meaningful order for docs and tests). The slice is a copy; callers may not mutate Precedence.

type Result

type Result struct {
	ID          string
	Status      Status
	Reason      Reason
	Retryable   bool
	Action      string
	Detail      string
	Remediation string
	// Hash is the tool's current pin string ("sha256/v{N}:{hex}") — operator
	// tier, ready results only. Never populated for the agent-token tier.
	Hash string
	// DidYouMean is populated only on not_found, from the caller-visible corpus.
	DidYouMean []string
}

Result is one per-tool verdict. It mirrors the wire DTO minus serialization concerns; failure fields are empty for a ready result.

func Evaluate

func Evaluate(ctx context.Context, ec EvalContext, refs []ToolRef) ([]Result, error)

Evaluate answers one verdict per requested ref, in request order.

It returns an error — never a fabricated reason code — when an underlying read fails (index, approvals, config policy) or the context is cancelled. The served surface answers 503 in that case: a reason code is a statement about proxy state, and inventing one from a failed read would poison the taxonomy.

type Scope

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

Scope is the immutable set of upstream servers an evaluation may see. A nil *Scope means unrestricted (operator, no profile, no token scope) — the same nil-receiver convention profile.ProfileScope uses.

func NewScope

func NewScope(name string, servers []string) *Scope

NewScope builds a named scope over an explicit server set. An empty (but non-nil) set is a legal deny-everything scope.

func ResolveScope

func ResolveScope(in ScopeInputs) *Scope

ResolveScope computes the effective evaluation scope as token scope ∩ token pin ∩ requested profile.

The scope's name is the most specific label available (requested profile, else token pin), which is what the operator-tier `server_not_in_scope` detail quotes. When a pinned token requests a DIFFERENT profile, the intersection is naturally the overlap of the two profiles — possibly empty, in which case every id resolves out of scope (and, at the agent-token tier, to `not_found`). The pin can therefore never be widened by naming another profile.

func (*Scope) Allows

func (s *Scope) Allows(serverName string) bool

Allows reports whether the named server is visible under this scope.

func (*Scope) Name

func (s *Scope) Name() string

Name returns the scope's label (a profile slug), or "" for an unnamed or unrestricted scope. It is used only in operator-tier `detail` text.

func (*Scope) ServerNames

func (s *Scope) ServerNames() []string

ServerNames returns the sorted member list, or nil for an unrestricted scope.

type ScopeInputs

type ScopeInputs struct {
	// TokenServers is the agent token's allowed_servers list. nil for operator
	// callers (API key / socket / named pipe).
	TokenServers []string
	// TokenPinName / TokenPinServers describe the profile an agent token is
	// pinned to (auth.AgentToken.ProfilePin). Until this feature the pin was
	// dropped on the REST path; it is now carried into evaluation.
	TokenPinName    string
	TokenPinServers []string
	// RequestedProfileName / RequestedProfileServers describe the profile the
	// caller asked to evaluate under (`profile` in the request body).
	RequestedProfileName    string
	RequestedProfileServers []string
}

ScopeInputs are the three independent restrictions that compose an evaluation scope (Spec 098 FR-010/FR-013, review finding 11). Each is optional; the effective scope is their intersection.

A nil slice means "no restriction from this source". An agent token's AllowedServers containing "*" is likewise unrestricted (matching auth.AuthContext.CanAccessServer).

type ServerPolicy

type ServerPolicy struct {
	Found       bool
	Enabled     bool
	Quarantined bool
	// AutoApproveToolChanges mirrors ServerConfig.IsAutoApproveToolChanges()
	// (equivalently IsQuarantineSkipped() / trust_mode auto): the server opted
	// out of tool-level quarantine, so pending/changed approval records do NOT
	// gate its tools. This is the divergence research D2 records: dispatch
	// honors it, the old classifyServerToolStatus did not.
	AutoApproveToolChanges bool
}

ServerPolicy is the config-derived (non-runtime) view of one upstream server. Found=false means no server with that name is configured at all.

type ServerRuntime

type ServerRuntime struct {
	State ServerRuntimeState
	// Detail is an occurrence-specific human note (e.g. the last error, or a
	// spec 044 diagnostic message). Optional.
	Detail string
	// Action optionally overrides the default action for server_unhealthy with
	// a best-effort suggestion from the spec 044 diagnostic classifier
	// (restart / login / view_logs). Empty means "use the default".
	Action string
}

ServerRuntime is the read-only connection view of one server.

type ServerRuntimeState

type ServerRuntimeState string

ServerRuntimeState is the evaluator's normalized connection state. It mirrors upstream/types.ConnectionState without importing it, so this package stays free of anything that can dial a socket.

const (
	// RuntimeStateUnknown means the snapshot has no usable state for the
	// server. The evaluator then makes NO connection-state claim.
	RuntimeStateUnknown ServerRuntimeState = ""
	RuntimeStateReady   ServerRuntimeState = "ready"
	// RuntimeStateConnecting / Discovering / Authenticating are the
	// server-level "initializing" states (research D4). No per-tool indexing
	// progress is ever claimed.
	RuntimeStateConnecting     ServerRuntimeState = "connecting"
	RuntimeStateDiscovering    ServerRuntimeState = "discovering"
	RuntimeStateAuthenticating ServerRuntimeState = "authenticating"
	// RuntimeStatePendingAuth is the deferred-OAuth state (FR-007): mapped to
	// oauth_required explicitly, BEFORE any health fallthrough, because waiting
	// cannot help without a login.
	RuntimeStatePendingAuth  ServerRuntimeState = "pending_auth"
	RuntimeStateDisconnected ServerRuntimeState = "disconnected"
	RuntimeStateError        ServerRuntimeState = "error"
)

type StateReader

type StateReader interface {
	// ServerRuntime returns the runtime view of a server; found=false when the
	// snapshot has no entry for it.
	ServerRuntime(serverName string) (rt ServerRuntime, found bool)
}

StateReader reads the connection-state snapshot (stateview). It is a snapshot read: lock-free, never blocking, never triggering a connect.

type Status

type Status = string

Status is the per-tool outcome. `ready` is a success status, not a failure reason — a ready result carries no reason, retryable or action field.

const (
	StatusReady       Status = "ready"
	StatusUnavailable Status = "unavailable"
)

type Tier

type Tier = string

Tier is the caller's disclosure tier (FR-013). The operator tier sees the full diagnosis (including hashes and `server_not_in_scope`); the agent-token tier gets scope-silence — an out-of-scope id is byte-indistinguishable from an ordinary `not_found`.

const (
	TierOperator   Tier = "operator"
	TierAgentToken Tier = "agent_token"
)

type ToolClass

type ToolClass string

ToolClass is the shared classification consumed by the preflight evaluator, classifyServerToolStatus and describeGateReason (research D2). Exactly one class per tool, by fixed first-match precedence.

const (
	ToolClassReady               ToolClass = "ready"
	ToolClassServerNotConfigured ToolClass = "server_not_configured"
	ToolClassServerQuarantined   ToolClass = "server_quarantined"
	ToolClassServerDisabled      ToolClass = "server_disabled"
	ToolClassDeniedByConfig      ToolClass = "denied_by_config"
	ToolClassBlockedByUser       ToolClass = "blocked_by_user"
	ToolClassChanged             ToolClass = "changed"
	ToolClassPendingApproval     ToolClass = "pending_approval"
)

func ClassifyTool

func ClassifyTool(in ClassifyInputs) ToolClass

ClassifyTool is the single tool-eligibility classification (Spec 098 FR-002, research D2). Dispatch behavior is ground truth, so three divergences of the legacy classifiers are resolved here in dispatch's favor:

  • the tool-level quarantine gate applies ONLY when the global quarantine switch is on AND the server has not opted out (trust_mode auto / auto_approve_tool_changes). classifyServerToolStatus used to check the approval status unconditionally, which reported false positives for auto-approving servers;
  • `changed` (rug-pull guard) is a class of its own, not collapsed into `pending_approval` — the two have different stories and different remediation text;
  • a user block (ToolApprovalRecord.Disabled) applies unconditionally, even for auto-approving servers: it is a user decision, not a quarantine gate.

Precedence: server not configured → quarantined → disabled → denied by config → blocked by user → changed → pending → ready. Existence (index presence) is NOT part of this classification; the evaluator interleaves it at its FR-004 slot, between server_disabled and tool_denied_by_config.

func (ToolClass) Callable

func (c ToolClass) Callable() bool

Callable reports whether the class permits dispatch. It is the one-line form the dispatch paths consume (FR-002).

func (ToolClass) Reason

func (c ToolClass) Reason() Reason

Reason maps a class to its preflight reason code. ToolClassReady maps to the empty string (no failure).

type ToolRef

type ToolRef struct {
	ID      string
	PinHash string
}

ToolRef is one requested id, optionally hash-pinned.

type Verdict

type Verdict = string

Verdict is the set-level aggregate: the worst class present.

const (
	VerdictReady             Verdict = "ready"
	VerdictDegradedRetryable Verdict = "degraded_retryable"
	VerdictBlocked           Verdict = "blocked"
	VerdictUnknownIDs        Verdict = "unknown_ids"
)

func ReasonVerdict

func ReasonVerdict(code Reason) Verdict

ReasonVerdict maps one reason to the set verdict it forces on its own.

func VerdictForReasons

func VerdictForReasons(reasons []Reason) Verdict

VerdictForReasons aggregates per-tool reasons into the set verdict: the worst class present. An empty list (every tool ready) is VerdictReady.

func VerdictForResults

func VerdictForResults(results []Result) Verdict

VerdictForResults is VerdictForReasons over evaluator results, ignoring ready entries.

Jump to

Keyboard shortcuts

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