preflight

package
v0.73.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 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 NoApprovalRecordDetail added in v0.67.0

func NoApprovalRecordDetail(id string) string

NoApprovalRecordDetail / NoApprovalRecordRemediation are the Spec 105 FR-009 implicit-pending bodies shared by dispatch (toolPendingApprovalResult, reason no_approval_record), describe_tool and check mode, so the three FR-009 readers cannot drift (astra r1 R1): a tool the discovery snapshot contains with NO stored approval record is pending under its own name while the quarantine gate applies, but nothing is listed in the review UI to approve yet — the taxonomy's "approve" remediation is a dead end (ApproveTools skips a missing record and triggers no rediscovery). The server's next discovery pass files the real record, so the caller is pointed at re-discovery.

func NoApprovalRecordRemediation added in v0.67.0

func NoApprovalRecordRemediation(serverName string) string

NoApprovalRecordRemediation is the re-discovery instruction for a record-less tool; see NoApprovalRecordDetail.

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" — NOT an error. It is the implicit-approved default EXCEPT for a discovered tool under an active quarantine gate, which ClassifyTool reports as pending (Spec 105 FR-009; see ClassifyInputs.Discovered).

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
	// Discovered reports whether the tool is in the proxy's discovery corpus
	// under its exact raw name — the live StateView snapshot for the dispatch
	// paths, the indexed corpus for the preflight evaluator (which resolves
	// existence at its FR-004 slot before classifying). Spec 105 FR-009
	// (research D4): while the quarantine gate applies to the server, a
	// discovered tool with NO approval record is pending, never ready —
	// "no record" is the implicit-approved default only for a tool the
	// proxy has not discovered, or while the gate is off. False keeps the
	// pre-105 default, so a caller that cannot answer the question fails the
	// same way it always did.
	Discovered bool
}

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
	// ToolPolicy is the caller's effective profile tool policy (issue #1548).
	// nil means no profile policy is in effect (an unprofiled operator, or a
	// pure-unit evaluation); it is never a default-deny.
	ToolPolicy ToolPolicyReader
	// TokenPermissions is the caller's credential permission tier (issue #1548
	// follow-up). nil means no token permissions restrict the caller.
	TokenPermissions TokenPermissionReader

	// 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
	// Restricted marks a non-administrator caller (Spec 107 FR-006): an empty
	// TokenServers is then deny-all, not "no restriction". See ScopeInputs.
	Restricted bool
	// 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
	// TokenPermissions is the agent token's permission list (read / write /
	// destructive), applied as dispatch applies it when Restricted is true
	// (issue #1548 follow-up). Ignored for operator callers.
	TokenPermissions []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 ProfileToolDecision added in v0.71.0

type ProfileToolDecision struct {
	// Blocked is true when any profile in effect for the caller refuses the
	// tool. Every profile in effect must admit it: an explicitly requested
	// profile can only narrow a credential's pinned or bound one.
	Blocked bool
	// Detail is the occurrence-specific operator text — the same refusal text
	// dispatch returns. It is never shown at the agent-token tier.
	Detail string
}

ProfileToolDecision is the effective profile tool policy's verdict for one existing tool (issue #1548).

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"
	// ReasonToolBlockedByProfile (issue #1548) is the effective Spec 108
	// profile tool policy — tier cap, deny rules, unannotated handling and
	// classification — refusing a tool that exists. It is the preflight
	// projection of dispatch's "blocked by profile: ..." refusal, so a tool
	// dispatch refuses under a profile can never preflight as ready. Added
	// additively: a consumer that predates it treats it as non-retryable.
	// Emitted at the OPERATOR tier only; the agent-token tier answers the
	// scope-silent not_found instead (FR-013), because discovery hides a
	// profile-excluded tool (Spec 108 FR-011) and the check must not confirm
	// what discovery withholds.
	ReasonToolBlockedByProfile Reason = "tool_blocked_by_profile"
	// ReasonTokenPermissionDenied (issue #1548 follow-up) is the caller's
	// agent-token permission tier (read / write / destructive) refusing a tool
	// that exists: the preflight projection of dispatch's "Permission denied:
	// token does not have '<tier>' permission required for tool ..." refusal,
	// decided from the same effective annotations. Added additively. Unlike a
	// profile exclusion it is NOT scope-silenced at the agent-token tier:
	// discovery (retrieve_tools, routed describe_tool) still lists a tool above
	// the token's tier, and the access explainer reports it visible but
	// blocked, so the check names the refusal rather than calling it absent.
	// Operator callers hold no token permissions and never see it.
	ReasonTokenPermissionDenied Reason = "token_permission_denied"
)

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.

func NotFound added in v0.63.0

func NotFound(id string) Result

NotFound builds the canonical not_found result for an id, WITHOUT consulting any reader.

It exists for surfaces that decide visibility before evaluation rather than during it (spec 102's direct describe_tool, whose permission-tier and display-name-collision gates are not preflight concepts). Such a surface must answer a gated id with exactly the bytes an absent id produces — otherwise the gate itself becomes the disclosure FR-013 exists to prevent — so it shares this constructor rather than hand-assembling a lookalike.

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 {
	// Restricted marks a NON-ADMINISTRATOR caller (Spec 107 FR-006): for such
	// a caller an empty TokenServers is deny-all — the owner's entitlement no
	// longer covers any granted server (storage.intersectAllowedServers hands
	// back a non-nil empty list), or a tenant principal is entitled to nothing.
	// Without the marker "empty" reads as "no restriction", which is right only
	// for operator callers; the REST preflight door used to evaluate a fully
	// unentitled token as token-unrestricted (the empty-list two-semantics trap).
	// A literal "*" stays unrestricted whatever the marker says.
	Restricted bool
	// 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)
	// ToolIdentity resolves a (server, raw tool) pair against the same
	// snapshot. A reader with no identity information returns the zero value
	// (no claim).
	ToolIdentity(serverName, toolName string) ToolIdentity
}

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 TokenPermissionDecision added in v0.71.0

type TokenPermissionDecision struct {
	// Blocked is true when the tool's tier, established from its effective
	// annotations, is a permission the credential does not hold.
	Blocked bool
	// Indeterminate is true when no authoritative annotations establish the
	// tool's tier (dispatch then fails closed to destructive) and the
	// credential lacks that fail-closed permission. The evaluator lets every
	// other gate answer first — a transient connection state stays its
	// retryable verdict — but never reports such a tool ready.
	Indeterminate bool
	// Detail is the exact refusal text dispatch returns for the same call.
	Detail string
}

TokenPermissionDecision is the caller's credential permission tier verdict for one existing tool (issue #1548 follow-up).

type TokenPermissionReader added in v0.71.0

type TokenPermissionReader interface {
	TokenPermissionDecision(serverName, toolName string) TokenPermissionDecision
}

TokenPermissionReader reads the caller's agent-token permission tier. Implementations MUST make the decision dispatch makes for the same caller (the target tool's tier from its effective annotations, then the credential's permission check), never a parallel re-implementation of it; the glue layer is the only implementation. A nil reader means the caller holds no restricting permissions (an operator, an administrator session, an unauthenticated or confined-anonymous session) — never a default-deny.

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.

A fourth rule is Spec 105 FR-009's (research D4): a DISCOVERED tool with no approval record is pending while the quarantine gate applies to its server, so an absent record can never be classified as callable for a tool the discovery snapshot contains — the gate is consulted before "no record" is allowed to mean ready.

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 ToolIdentity added in v0.67.0

type ToolIdentity struct {
	Known         bool
	Hydrated      bool
	DiscoveryDone bool
	Found         bool
}

ToolIdentity is the read-only outcome of resolving one (server, raw tool) pair against the live discovery snapshot — the registration identity every dispatch path authorizes against (Spec 105 FR-009, research D4). It mirrors the dispatch-side resolution without importing it:

  • Known: the snapshot holds the server at all. The zero value (Known false) is "no identity claim" — a pure-unit reader, or a server the snapshot has never held — and the evaluator then falls through to the existence test it always ran.
  • Hydrated: the server is enabled, not quarantined and CONNECTED, so its snapshot is the authority on its tool set. A known server that is not hydrated keeps the server-level connection verdicts.
  • DiscoveryDone: a discovery pass has completed for the LIVE connection (the snapshot's stamp was captured on the connection the client currently holds).
  • Found: the completed result lists the raw name, verbatim.

func (ToolIdentity) Unresolved added in v0.67.0

func (id ToolIdentity) Unresolved() bool

Unresolved reports the D4 refusal condition dispatch applies: a known, hydrated server whose discovery has not completed for the live connection or whose completed discovery does not list the name.

type ToolPolicyReader added in v0.71.0

type ToolPolicyReader interface {
	ProfileToolDecision(serverName, toolName string) ProfileToolDecision
}

ToolPolicyReader reads the caller's effective Spec 108 profile tool policy. Implementations MUST make the same decision dispatch makes (the compiled policy's Decide over the same effective annotations), never a parallel re-implementation of it; the glue layer is the only implementation.

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