rollout

package
v1.0.310 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package rollout is the capability-local rollout state model for the MCP Security Gateway and Culvert Management MCP Server (PR-11). It owns the mode ladder (Disabled → Observe → Shadow → Canary → Production), the immutable revisioned rollout scope, the single central hard-failure classifier, and the Production-Qualification lockout.

It is a pure leaf: it imports only the standard library and internal/mcp/mcperr (plus a stable hash for percentage bucketing). It performs NO I/O, reads NO wall clock of its own (callers pass an explicit time), and holds no policy, token, credential, or raw request/response. The signed, distributable subset (mode + scope) is carried inside the PR-10 cpdp signed snapshot payload, so cpdp imports rollout — never the reverse.

Doctrine (ROLLOUT-AND-ROLLBACK.md): the two capabilities keep SEPARATE modes, scopes, transition history, kill switches, evidence, and rollback state. A Gateway transition never alters Management mode and vice versa. Management stays read-only/draft/validate/simulate in every mode. Production is a real mode semantic but is UNREACHABLE without a machine-verifiable ProductionQualificationVerifier receipt; this package contains no issuer that can mint one.

Index

Constants

View Source
const (
	// ConnectorLocalClient is Model A — the only supported V1 connectivity model
	// (managed internal AI client → LAN/VPN → Culvert MCP Gateway → approved remote
	// MCP server). No public ingress, no vendor connector.
	ConnectorLocalClient = "local-client"
	// ConnectorOutbound is Model B — a post-V1 roadmap slice. REJECTED in V1.
	ConnectorOutbound = "outbound-connector"
	// ConnectorDMZ is Model C — deferred, default-off. REJECTED in V1.
	ConnectorDMZ = "dmz-endpoint"
)

Connector-mode constants. V1 supports ONLY Model A (local-client). The other two are reserved, unimplemented, and ungated — every configuration surface and the snapshot validator must reject them (ON-PREM-CONNECTIVITY.md D-8/D-9).

View Source
const (
	// ShadowWindowTarget is the continuous Shadow window floor (≥14 days).
	ShadowWindowTarget = 14 * 24 * time.Hour
	// CanaryWindowTarget is the continuous Canary window floor (≥7 days).
	CanaryWindowTarget = 7 * 24 * time.Hour
	// SoakTarget is the stable-soak floor at every promotion boundary (≥24 hours).
	SoakTarget = 24 * time.Hour
)

Design-target evidence windows (ROLLOUT-AND-ROLLBACK.md §1). These are MEASURED, never fabricated: the machinery below reports elapsed continuous time against them, but Production remains locked behind the separate Production Qualification gate regardless of what these report. Tests use an injected clock and MUST label synthetic elapsed time as test evidence.

Variables

This section is empty.

Functions

func Demotable

func Demotable(from, to Mode) bool

Demotable reports whether to is strictly below from (any number of stages).

func IsHardFailure

func IsHardFailure(r mcperr.Reason) bool

IsHardFailure reports whether the reason ALWAYS blocks regardless of mode.

func NormalizeConnectorMode

func NormalizeConnectorMode(mode string) string

NormalizeConnectorMode returns the effective connector mode, defaulting an empty value to local-client. It assumes the value has already passed ValidateConnectorMode (callers validate before persisting).

func Promotable

func Promotable(from, to Mode) bool

Promotable reports whether to is exactly one stage above from.

func StableBucket

func StableBucket(salt, key string) uint32

StableBucket maps (salt, key) deterministically into [0,100). It uses a domain-separated SHA-256 of the salt and key — never math/rand, process start time, or map iteration order — so the same subject falls in the same bucket across restarts and across every node. Changing the percentage does not move a subject relative to the bucket boundary; changing the salt (a new revision) re-buckets deterministically.

func SupportsSelectorSchema

func SupportsSelectorSchema(v int) bool

SupportsSelectorSchema reports whether a scope declaring schema version v is interpretable by this build. A higher schema is rejected whole (fail closed).

func ValidateConnectorMode

func ValidateConnectorMode(mode string) error

ValidateConnectorMode accepts ONLY "local-client". An empty string is treated as the default local-client (safe). "outbound-connector" and "dmz-endpoint" — and any other value — are rejected with ReasonRolloutConnectorModeRejected. This is the single reusable enforcement point for every surface (API, YAML/env/flag, import, snapshot apply).

Types

type ActionKind

type ActionKind uint8

ActionKind is the rollout-local view of a PR-6 policy decision's disposition. The runtime maps policy.Action → ActionKind so this leaf package never imports the policy engine. The mapping preserves the allow-class distinction exactly.

const (
	// ActionKindDenied — DENY or QUARANTINE (a block-class decision).
	ActionKindDenied ActionKind = iota
	// ActionKindAllow — ALLOW or MONITOR (execute subject to obligations/hard controls).
	ActionKindAllow
	// ActionKindConfirm — REQUIRE_CONFIRMATION (no execution without confirmation).
	ActionKindConfirm
	// ActionKindApproval — REQUIRE_APPROVAL (no execution without an approval receipt).
	ActionKindApproval
	// ActionKindAllowOnce — ALLOW_ONCE (one-call allowance, consumed atomically).
	ActionKindAllowOnce
	// ActionKindAllowSession — ALLOW_FOR_SESSION (session-bounded allowance).
	ActionKindAllowSession
	// ActionKindRedaction — ALLOW_WITH_REDACTION (execute only the transformed args).
	ActionKindRedaction
)

func (ActionKind) IsAllowClass

func (a ActionKind) IsAllowClass() bool

IsAllowClass reports whether the action executes (subject to obligations + hard controls). Mirrors policy.Action.IsAllowClass: ALLOW, MONITOR, ALLOW_ONCE, ALLOW_FOR_SESSION, ALLOW_WITH_REDACTION.

type BucketKeyKind

type BucketKeyKind uint8

BucketKeyKind selects which stable subject attribute keys a percentage bucket. The keyed attribute MUST be stable for a subject across restarts (so the same subject stays in or out); it is never a clock, random value, or map order.

const (
	// BucketByPrincipal keys the bucket by the authenticated principal id (default).
	BucketByPrincipal BucketKeyKind = iota
	// BucketByTenant keys the bucket by tenant id.
	BucketByTenant
	// BucketByAgent keys the bucket by agent id.
	BucketByAgent
	// BucketByClient keys the bucket by client/application id.
	BucketByClient
)

type Capability

type Capability uint8

Capability identifies which MCP capability a rollout state belongs to. It is a small local enum (rollout is a leaf and must not import the runtime/cpdp capability types); mapping to those types happens at the wiring layer.

const (
	// CapabilityUnknown is the zero value; it fails closed (never a valid rollout).
	CapabilityUnknown Capability = iota
	// CapabilityGateway is the MCP Security Gateway (the only capability that ever
	// executes upstream).
	CapabilityGateway
	// CapabilityManagement is the Culvert Management MCP Server (read-only/draft/
	// validate/simulate in every mode — it never executes an upstream tools/call).
	CapabilityManagement
)

func ParseCapability

func ParseCapability(s string) (Capability, error)

ParseCapability parses a stable capability token, failing closed on anything other than the two admitted values.

func (Capability) String

func (c Capability) String() string

String returns the stable wire token for the capability.

func (Capability) Valid

func (c Capability) Valid() bool

Valid reports whether the capability is one of the two real capabilities.

type EffectiveDisposition

type EffectiveDisposition uint8

EffectiveDisposition is what the rollout mode actually does with a request after combining mode, scope, hard failures, the policy action, and obligations.

const (
	// EffectRecordOnly — record the decision; NO upstream execution (Disabled,
	// Observe, or out-of-scope with no shadow fallback).
	EffectRecordOnly EffectiveDisposition = iota
	// EffectExecute — perform the real guarded upstream execution.
	EffectExecute
	// EffectBlock — block the call (a hard failure in any mode, or an enforced
	// non-allow decision / unsatisfied obligation in Canary/Production).
	EffectBlock
	// EffectShadowEvaluate — Shadow mode: compute the would-be outcome
	// (WOULD_EXECUTE / WOULD_BLOCK) and record durable evidence, but NEVER perform the
	// upstream side effect. This is a DISTINCT disposition from EffectExecute
	// precisely so a Shadow request can never share the execute path with
	// Canary/Production. The executor routes it to a non-executing evaluator that holds
	// no path to Upstream.Call or credential materialization (SH-INV-1/2,
	// docs/design/mcp/SHADOW-ARCHITECTURE.md §3). Shadow does not execute; it evaluates.
	EffectShadowEvaluate
)

func (EffectiveDisposition) String

func (d EffectiveDisposition) String() string

String returns a stable token for the disposition.

type EvidenceOrigin

type EvidenceOrigin uint8

EvidenceOrigin marks whether an evidence figure came from real production operation or a synthetic (injected-clock) test. A synthetic figure MUST NEVER be reported as production evidence.

const (
	// OriginUnset is the zero value.
	OriginUnset EvidenceOrigin = iota
	// OriginProduction is real, measured production operation.
	OriginProduction
	// OriginSynthetic is injected-clock/test time; never production-qualifying.
	OriginSynthetic
)

func (EvidenceOrigin) String

func (o EvidenceOrigin) String() string

String returns a stable token.

type EvidenceSummary

type EvidenceSummary struct {
	Version                 int            `json:"version"`
	Origin                  EvidenceOrigin `json:"origin"`
	ShadowStartUnix         int64          `json:"shadow_start_unix,omitempty"`
	CanaryStartUnix         int64          `json:"canary_start_unix,omitempty"`
	SoakStartUnix           int64          `json:"soak_start_unix,omitempty"`
	OpenCriticalHighDefects int            `json:"open_critical_high_defects"`
	RollbackRehearsed       bool           `json:"rollback_rehearsed"`
	FalsePositiveReviews    int            `json:"false_positive_reviews"`
}

EvidenceSummary is the bounded, restart-durable rollout evidence for one capability. It records when the current mode window began, the continuous elapsed time (computed with an injected clock), the open-defect count, and the origin label. It NEVER stores tenant/subject/argument/URL/token content.

func (*EvidenceSummary) AddFalsePositiveReview

func (e *EvidenceSummary) AddFalsePositiveReview(lim Limits)

AddFalsePositiveReview increments the bounded false-positive review counter.

func (*EvidenceSummary) BeginWindow

func (e *EvidenceSummary) BeginWindow(mode Mode, nowUnix int64, origin EvidenceOrigin)

BeginWindow stamps the start of a mode window (Shadow/Canary) and the soak window at nowUnix. It is idempotent per mode (re-stamping only on first entry so the CONTINUOUS window is preserved across re-applies of the same mode).

func (EvidenceSummary) CanaryElapsed

func (e EvidenceSummary) CanaryElapsed(now time.Time) time.Duration

CanaryElapsed returns the continuous Canary window elapsed at now.

func (EvidenceSummary) PromotionEvidenceMet

func (e EvidenceSummary) PromotionEvidenceMet(from, to Mode, now time.Time) (met bool, reason string)

PromotionEvidenceMet reports whether the evidence FLOORS for a from→to promotion are satisfied at now (window + soak + zero open critical/high). This is a REPORTING gate only — it never authorizes Production (the qualification verifier does). It returns (met, reason) where reason is a fail-closed classification when not met.

func (EvidenceSummary) ShadowElapsed

func (e EvidenceSummary) ShadowElapsed(now time.Time) time.Duration

ShadowElapsed returns the continuous Shadow window elapsed at now.

func (EvidenceSummary) SoakElapsed

func (e EvidenceSummary) SoakElapsed(now time.Time) time.Duration

SoakElapsed returns the soak elapsed at now.

type HardClass

type HardClass uint8

HardClass is the fixed hard-failure taxonomy. A hard failure ALWAYS blocks in Shadow, Canary, and Production alike — it is never policy-overridable and never downgraded to MONITOR/ALLOW by any rollout mode. The seven security classes mandated by ROLLOUT-AND-ROLLBACK.md §2 are joined by HardInspectionPrivacy, which carries the PR-7 inspection/DLP hard blocks the spec requires be preserved ("Also preserve every hard inspection block from PR-7").

const (
	// HardNone means the reason is NOT a fixed hard failure. It may still deny a
	// request (an ordinary policy DENY, an obligation gate, an operational error, or
	// a control-plane rejection), but a rollout mode may treat it per mode semantics
	// (e.g. Shadow records-and-allows an ordinary policy DENY).
	HardNone HardClass = iota
	// HardAuthIdentity — authentication + sender identity: invalid/expired token,
	// wrong audience/resource, invalid sender constraint, replay, tenant mismatch,
	// identity-session rebind.
	HardAuthIdentity
	// HardServerTrust — server trust: unregistered/disabled server, failed/changed
	// TLS/workload identity, endpoint no longer matching its registered identity.
	HardServerTrust
	// HardCredentialSafety — credential safety: scope mismatch, power exceeds plan,
	// expired/revoked profile, broker/provider failure under a fail-closed profile.
	HardCredentialSafety
	// HardAvailabilityBounds — availability bounds: protocol/body/depth/string limits,
	// queue/admission exhaustion, upstream response limit, redirect/timeout budget.
	HardAvailabilityBounds
	// HardDestinationSafety — destination safety: private/loopback/metadata/reserved
	// destination, DNS rebinding, connect-peer mismatch, forbidden redirect, scheme
	// downgrade; plus inbound Host/Origin rebinding.
	HardDestinationSafety
	// HardToolTrust — tool trust: unknown tool, unapproved fingerprint, privilege
	// expansion, identity/schema drift requiring quarantine.
	HardToolTrust
	// HardManagementSafety — Management safety: any Management mutation/command/secret
	// export/approval/config/publish/rollback mutation through Management MCP.
	HardManagementSafety
	// HardInspectionPrivacy — PR-7 inspection/DLP hard blocks: secret/PII detected,
	// schema invalid/unsupported/over-limit, output too large/invalid, injection,
	// redaction failed, inspection unavailable, or a durable-event secret backstop.
	HardInspectionPrivacy
)

func Classify

func Classify(r mcperr.Reason) HardClass

Classify returns the hard-failure class for a reason, or HardNone if it is not a fixed hard failure. It is a pure lookup — no rollout mode can change its result.

func (HardClass) String

func (h HardClass) String() string

String returns the stable token for the class.

type LimitConfig

type LimitConfig struct {
	MaxSelectors       int // total selector entries across all selector kinds in one scope
	MaxSelectorValues  int // values within a single multi-value selector (e.g. tenant list)
	MaxExclusions      int // exclusion entries (which may only narrow)
	MaxResolvedMembers int // upper bound on an enumerable resolved subject set
	MaxValueBytes      int // bytes of a single selector value string
	MaxTransitions     int // mode transitions retained/permitted per rolling interval
	MaxHistory         int // retained transition-history entries
	MaxEvidenceItems   int // retained evidence-summary entries
	MaxReviewEntries   int // retained bounded false-positive review entries
}

LimitConfig is the mutable input to NewLimits. Every field bounds a rollout data structure so nothing an operator or a signed snapshot supplies can grow unbounded. Zero in any field means "use the safe default" (see DefaultLimits).

type Limits

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

Limits is the immutable, validated bounds set. All access is through accessors; the zero Limits is never valid (construct via NewLimits/DefaultLimits).

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the safe default bounds.

func NewLimits

func NewLimits(c LimitConfig) (Limits, error)

NewLimits validates and freezes a bounds set, filling zero fields with the safe defaults. It rejects any explicitly-negative field.

func (Limits) MaxEvidenceItems

func (l Limits) MaxEvidenceItems() int

MaxEvidenceItems returns the evidence-summary retention bound.

func (Limits) MaxExclusions

func (l Limits) MaxExclusions() int

MaxExclusions returns the exclusion-entry bound.

func (Limits) MaxHistory

func (l Limits) MaxHistory() int

MaxHistory returns the transition-history retention bound.

func (Limits) MaxResolvedMembers

func (l Limits) MaxResolvedMembers() int

MaxResolvedMembers returns the resolved-subject-set bound.

func (Limits) MaxReviewEntries

func (l Limits) MaxReviewEntries() int

MaxReviewEntries returns the false-positive-review retention bound.

func (Limits) MaxSelectorValues

func (l Limits) MaxSelectorValues() int

MaxSelectorValues returns the per-selector value-count bound.

func (Limits) MaxSelectors

func (l Limits) MaxSelectors() int

MaxSelectors returns the total selector-entry bound for one scope.

func (Limits) MaxTransitions

func (l Limits) MaxTransitions() int

MaxTransitions returns the per-interval transition bound.

func (Limits) MaxValueBytes

func (l Limits) MaxValueBytes() int

MaxValueBytes returns the per-value byte bound.

func (Limits) Valid

func (l Limits) Valid() bool

Valid reports whether the limits were constructed (never the zero value).

type Mode

type Mode uint8

Mode is one rung of the rollout ladder. The zero value (ModeDisabled) is the safe default: no listener, no execution, no request-path cost.

const (
	// ModeDisabled — the capability is absent: no listener bound, no MCP traffic
	// accepted, no upstream pool, no credential materialization, no worker loop, no
	// request-path overhead on the existing SWG. Signed snapshots may be retained but
	// are not active for execution. "Disabled" means absent, not a DENY-returning
	// listener.
	ModeDisabled Mode = iota
	// ModeObserve — a bounded listener may run; requests pass protocol/auth/identity/
	// registry/inspection/policy and are recorded, but NOTHING is executed upstream,
	// no credential is materialized, and no provider is contacted. The decision-only
	// posture (execution_state = not_implemented / observe) is preserved.
	ModeObserve
	// ModeShadow — for an explicit bounded Shadow scope only (default empty; a Shadow
	// config with an empty/non-enumerable scope is REJECTED at validation, so "no scope"
	// can never mean "shadow everything"). After Layer B (#1226) Shadow does NOT reach
	// the upstream: an in-scope request is handed to the capability-reduced
	// ShadowEvaluator, which computes the formal Model-1 ShadowDecision (WOULD_EXECUTE /
	// WOULD_BLOCK / WOULD_FAIL_*), records durable evidence, and returns — it holds no
	// path to Upstream.Call or credential materialization, so it NEVER crosses the
	// irreversible side-effect boundary and NEVER enforces (a hard failure is PREDICTED
	// as WOULD_FAIL_*, never emitted as a real block). Outside the scope: Observe behavior.
	ModeShadow
	// ModeCanary — full enforcement (all nine policy actions) for an explicit,
	// enumerated, read-first scope. Outside scope: Shadow (if enabled) else Observe.
	ModeCanary
	// ModeProduction — full enforcement for an approved scope. Implemented as a mode
	// semantic but UNREACHABLE without a valid Production Qualification receipt; a
	// transition into it fails closed otherwise.
	ModeProduction
)

func EmergencyTarget

func EmergencyTarget(from Mode, disable bool) Mode

EmergencyTarget returns the safe demotion target for an emergency narrowing of mode: one stage down, except an explicit disable goes straight to Disabled. It never returns a mode above from.

func ParseMode

func ParseMode(s string) (Mode, error)

ParseMode parses a stable mode token, failing closed on anything unknown.

func (Mode) FullyEnforces

func (m Mode) FullyEnforces() bool

FullyEnforces reports whether the mode blocks on a non-hard policy DENY inside scope (Canary and Production). Shadow records-and-allows a non-hard DENY; Observe/Disabled never enforce policy at all.

func (Mode) Rank

func (m Mode) Rank() int

Rank returns the ladder position (Disabled=0 … Production=4). Higher rank means more enforcement/execution surface; promotion increases rank by exactly one and demotion decreases it by one or more.

func (Mode) RequiresExecutionPlane added in v1.0.218

func (m Mode) RequiresExecutionPlane() bool

RequiresExecutionPlane reports whether the mode requires the guarded-execution plane (the executor / exec-deps) to be COMPOSED before a transition is honored — Shadow, Canary and Production all do. This is deliberately NOT "performs real upstream execution": Shadow composes the plane to EVALUATE via the non-executing EffectShadowEvaluate disposition and NEVER crosses the side-effect boundary (Layer B). Only Canary/Production perform real upstream execution (see FullyEnforces). Used to fail a Shadow/Canary/Production transition closed when exec-deps are not configured, so the value for Shadow MUST stay true (Codex P2: the old name/doc mislabelled Shadow as live-execution-capable).

func (Mode) RequiresLiveExecution added in v1.0.218

func (m Mode) RequiresLiveExecution() bool

RequiresLiveExecution reports whether the mode performs a REAL upstream side effect — an upstream tools/call and credential materialization — for an in-scope allow-class request (Canary and Production). It is the STRICT subset of RequiresExecutionPlane that excludes Shadow: after Layer B (#1226) Shadow composes the evaluation plane but NEVER crosses the irreversible side-effect boundary, so its readiness is a distinct, weaker gate (a non-executing ShadowEvaluator, no upstream client, no materialize-capable broker). The two predicates are the whole point of splitting shadow readiness from live-execution readiness — a Shadow transition must NOT be gated on live-execution dependencies it does not require, and a live-execution transition must NOT be admitted merely because Shadow is composed. Value-identical to FullyEnforces by construction; named for the readiness gate so the call site reads as the capability it demands.

func (Mode) String

func (m Mode) String() string

String returns the stable token, or "invalid" for an unknown mode.

func (Mode) Valid

func (m Mode) Valid() bool

Valid reports whether m is one of the five defined modes.

type ProductionQualificationVerifier

type ProductionQualificationVerifier interface {
	VerifyProductionQualification(binding QualificationBinding) error
}

ProductionQualificationVerifier is the narrow, injected interface that gates entry into Production. The separate Production Qualification gate owns the real evidence (full shadow/canary windows, soak, defect closure) and issues an immutable receipt; this build contains NO issuer that can mint a receipt this verifier accepts. A nil verifier ⇒ Production is unreachable (fail closed).

VerifyProductionQualification MUST return nil ONLY for a present, valid receipt that binds EXACTLY to the supplied binding (capability + target scope hash + snapshot hash). No environment variable, CLI flag, API parameter, signed snapshot field, or boolean can substitute for it.

type QualificationBinding

type QualificationBinding struct {
	Capability      Capability `json:"capability"`
	FromMode        Mode       `json:"from_mode"`
	ToMode          Mode       `json:"to_mode"` // MUST be ModeProduction
	TargetScopeHash string     `json:"target_scope_hash"`
	SnapshotHash    string     `json:"snapshot_hash"`
}

QualificationBinding is the exact target a Production Qualification receipt must bind to. A receipt valid for one capability/scope/snapshot can never authorize a different one. It carries only non-secret identifiers.

type Resolution

type Resolution struct {
	Disposition     EffectiveDisposition
	EvaluatedAction ActionKind
	EffectiveAction ActionKind
	InScope         bool
	HardFailure     bool
	ShadowOverride  bool
	Executed        bool
	BlockReason     mcperr.Reason
	// ScopeHash identifies the EXACT authorization envelope this resolution was decided
	// against — the content hash of the active scope, covering every selector dimension
	// (tenants, servers, tools, fingerprints, principals, agents, clients, groups,
	// environments, every exclusion set, the operation set, the percentage and bucket salt,
	// and the scope revision).
	//
	// It is a BOUNDARY FACT, not policy semantics: nothing here decides anything, and it is
	// deliberately absent from policy.DecisionInput. Its only consumer is the live
	// side-effect admission transaction, which requires it to still equal the scope in force
	// before it grants budget authority — so a request cannot resolve under one authorization
	// envelope and spend authority under another.
	//
	// It is populated ONLY by State.ResolveFor, from the SAME atomic snapshot that decided
	// InScope. A Resolution built by the pure Resolve() carries "" — which the admission
	// boundary treats as fail-closed, never as a match.
	ScopeHash string
}

Resolution is the truthful mode-resolution result. It preserves the evaluated policy action UNCHANGED and records the effective disposition separately.

func Resolve

func Resolve(in ResolveInput) Resolution

Resolve computes the effective disposition. It is pure (no I/O, no clock) and fail-closed: an unknown mode blocks. It NEVER downgrades a hard failure and NEVER overwrites the evaluated policy action.

type ResolveInput

type ResolveInput struct {
	Mode Mode
	// InScope reports whether the subject is inside THIS mode's active scope.
	InScope bool
	// ShadowEnabled + ShadowInScope drive the Canary/Production out-of-scope
	// fallback: outside Canary scope a subject retains Shadow behavior when a shadow
	// scope is enabled and the subject is in it; otherwise Observe behavior.
	ShadowEnabled bool
	ShadowInScope bool
	// Action is the PR-6 policy decision's disposition class.
	Action ActionKind
	// HardFailure reports whether a fixed hard failure fired (auth/server/credential/
	// availability/destination/tool/management/inspection). It blocks in EVERY mode.
	HardFailure bool
	// HardReason is the classified reason for a hard failure (informational).
	HardReason mcperr.Reason
	// ObligationsSatisfied reports whether allow-class obligations were met (an
	// ALLOW_ONCE consumed, an ALLOW_FOR_SESSION within its bound). Trivially true for
	// plain ALLOW/MONITOR/REDACTION. Only consulted in Canary/Production.
	ObligationsSatisfied bool
}

ResolveInput is the fully-resolved evidence the mode resolver combines. The caller (the runtime executor) supplies the resolved policy action, whether the subject is in the active/shadow scope, whether a fixed hard failure fired, and whether allow-class obligations were satisfied.

type RiskClass

type RiskClass uint8

RiskClass classifies an operation by reversibility/blast radius. The zero value fails closed (never admitted to any scope).

const (
	// RiskUnknown is the zero value; fails closed.
	RiskUnknown RiskClass = iota
	// RiskRead — read-only/reversible.
	RiskRead
	// RiskWrite — mutating but recoverable.
	RiskWrite
	// RiskDestructive — irreversible/high blast radius.
	RiskDestructive
)

func (RiskClass) HighRisk

func (r RiskClass) HighRisk() bool

HighRisk reports whether the class is write or destructive (requires an explicit high-risk scope to enter Shadow/Canary).

func (RiskClass) String

func (r RiskClass) String() string

String returns the stable token.

func (RiskClass) Valid

func (r RiskClass) Valid() bool

Valid reports whether r is a defined risk class.

type RollbackState

type RollbackState struct {
	LastTargetHash string `json:"last_target_hash,omitempty"`
	LastCommandID  string `json:"last_command_id,omitempty"`
	AtUnixNano     int64  `json:"at_unix_nano,omitempty"`
}

RollbackState records the last rollback/demotion reference (truthful local vs fleet convergence is tracked by the distribution layer, not here).

type Scope

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

Scope is the immutable, revisioned, content-hashed rollout scope. It is capability-scoped (tenant isolation and capability isolation are structural: a Gateway scope never matches a Management subject and vice versa). Construct via Compile; the zero Scope matches nothing.

func Compile

func Compile(spec ScopeSpec, revision uint64, lim Limits) (Scope, error)

Compile validates spec and returns an immutable Scope at the given revision. It enforces bounds, value sizes, the no-wildcard rule, the high-risk gate for write/destructive operations, and percentage-bucket well-formedness. It is pure (no I/O, no clock). On any violation it returns a classified fail-closed error.

func EmptyScope

func EmptyScope(capb Capability) Scope

EmptyScope returns a compiled scope for a capability that matches nothing (the safe default at every mode's entry). Revision 0.

func (Scope) AdmitsToolForEvaluation added in v1.0.218

func (s Scope) AdmitsToolForEvaluation(serverID, toolName, fingerprint string) bool

AdmitsToolForEvaluation reports whether this scope TARGETS the given tool for a Gateway tools/call evaluation, INDEPENDENT of the calling identity. It checks the capability, the server and tool selectors, the server/tool exclusions, and that the write risk class (the class every tools/call is classified as) is admitted — but NOT the request-identity dimensions (principal/agent/client/tenant/environment/group), which are supplied per request, not by the catalog. A tool that is Usable AND targeted by the scope is one the scope can actually evaluate (rather than fail closed under the quarantine hard-override); Contains stays the per-request membership authority.

It is the scope half of the "does this Shadow scope have any evaluable tool" preflight gate (Codex P1, PR #1234): a scope that admits only the read class, excludes the tool's server, or does not target the tool returns false.

func (Scope) Capability

func (s Scope) Capability() Capability

Capability returns the scope's capability.

func (Scope) Contains

func (s Scope) Contains(subj Subject) bool

Contains reports whether subject is inside the scope. It is deterministic and performs no I/O or clock read. The evaluation order is: capability isolation → exclusions (which only narrow) → inclusion dimensions (AND across non-empty dimensions, OR within a dimension) → operation-class admission → percentage bucket. An empty scope contains nothing.

func (Scope) Enumerable

func (s Scope) Enumerable() bool

Enumerable reports whether the scope resolves to a frozen, inspectable subject set (has concrete inclusion selectors). A pure-percentage scope over an unbounded keyspace is NOT enumerable — Canary requires an enumerable scope, so a "1% of everything" scope cannot enter Canary.

func (Scope) Hash

func (s Scope) Hash() string

Hash returns the deterministic content hash of the normalized scope.

func (Scope) HighRisk

func (s Scope) HighRisk() bool

HighRisk reports whether this scope is permitted to include write/destructive.

func (Scope) MatchesNothing

func (s Scope) MatchesNothing() bool

MatchesNothing reports whether the scope can never match any subject (the safe default: no inclusion dimensions and no percentage gate).

func (Scope) Revision

func (s Scope) Revision() uint64

Revision returns the scope revision.

func (Scope) SelectorSchema

func (s Scope) SelectorSchema() int

SelectorSchema returns the selector-schema version the scope was built under.

type ScopeSpec

type ScopeSpec struct {
	Capability        Capability    `json:"capability"`
	Tenants           []string      `json:"tenants,omitempty"`
	Servers           []string      `json:"servers,omitempty"`
	ToolFingerprints  []string      `json:"tool_fingerprints,omitempty"`
	Tools             []ToolSel     `json:"tools,omitempty"`
	Principals        []string      `json:"principals,omitempty"`
	Agents            []string      `json:"agents,omitempty"`
	Clients           []string      `json:"clients,omitempty"`
	Groups            []string      `json:"groups,omitempty"`
	Environments      []string      `json:"environments,omitempty"`
	Operations        []RiskClass   `json:"operations,omitempty"`  // admitted risk classes; empty ⇒ read-only only
	Percent           int           `json:"percent,omitempty"`     // 0 ⇒ no percentage gate; 1..99 sub-samples; 100 ⇒ all-in-dims
	BucketSalt        string        `json:"bucket_salt,omitempty"` // REQUIRED when 0 < Percent < 100 (binds the stable hash)
	BucketKey         BucketKeyKind `json:"bucket_key,omitempty"`
	ExcludeTenants    []string      `json:"exclude_tenants,omitempty"`
	ExcludeServers    []string      `json:"exclude_servers,omitempty"`
	ExcludeTools      []ToolSel     `json:"exclude_tools,omitempty"`
	ExcludePrincipals []string      `json:"exclude_principals,omitempty"`
	// HighRisk must be true for a scope whose Operations include write/destructive.
	// A plain scope is read-only/reversible; write/destructive never enter a rollout
	// through a percentage or a non-high-risk scope.
	HighRisk bool `json:"high_risk,omitempty"`
}

ScopeSpec is the mutable input used to build (Compile) an immutable Scope. All slices are inclusion selectors unless prefixed Exclude*. An empty spec (no inclusion selectors and Percent==0) compiles to a scope that matches NOTHING — there is no wildcard "all" default.

type SignedConfig

type SignedConfig struct {
	// SelectorSchema is the scope selector-schema version the CP built this under. A
	// DP that supports a LOWER schema rejects the whole config (fail closed) rather
	// than silently under-matching an unknown selector.
	SelectorSchema int `json:"selector_schema"`
	// Capability MUST match the payload's capability (Gateway/Management isolation).
	Capability Capability `json:"capability"`
	// Mode is the published mode for this capability.
	Mode Mode `json:"mode"`
	// Scope is the serializable rollout scope spec (recompiled + revalidated on the
	// DP). Empty ⇒ matches nothing (the safe default).
	Scope ScopeSpec `json:"scope"`
	// ScopeRevision is the monotonic revision of the scope (a scope change — including
	// a percentage change — is a new revision).
	ScopeRevision uint64 `json:"scope_revision"`
	// ShadowScope is the OPTIONAL Shadow-scope fallback used only when Mode is
	// Canary/Production: a subject outside the Canary scope but inside this Shadow
	// scope retains Shadow behavior (never fleet-wide enforcement). Empty ⇒ Observe
	// behavior outside the Canary scope. Ignored when Mode is Shadow (Scope is the
	// shadow scope then).
	ShadowScope ScopeSpec `json:"shadow_scope,omitempty"`
	// ShadowScopeRevision is the revision of ShadowScope.
	ShadowScopeRevision uint64 `json:"shadow_scope_revision,omitempty"`
	// ConnectorMode is Gateway-only; it MUST be "local-client" (Model A). Ignored for
	// Management (which is inbound-only and has no connector topology).
	ConnectorMode string `json:"connector_mode,omitempty"`
}

SignedConfig is the distributable, capability-local rollout configuration that rides INSIDE a PR-10 cpdp signed snapshot payload (GatewayPayload / ManagementPayload). It is fully JSON-serializable and map-free so it is covered by the snapshot content hash and signature with no extra plumbing. It carries ONLY reviewed decision state (mode + scope + connector mode) — never a secret, token, credential, or raw request/response.

Presence semantics on the wire: a nil *SignedConfig on a payload means "no rollout change — keep local rollout state" (an older/rolled-back CP that predates rollout never wipes a DP's mode). An intended change is an explicit non-nil config at a new scope revision.

func DisabledConfig

func DisabledConfig(capability Capability) SignedConfig

DisabledConfig returns the safe-default config for a capability: Disabled mode, empty scope, local-client connector (Gateway).

func (SignedConfig) CompileScope

func (c SignedConfig) CompileScope(lim Limits) (Scope, error)

CompileScope compiles the embedded scope spec into an immutable Scope at the config's scope revision.

func (SignedConfig) CompileShadowScope

func (c SignedConfig) CompileShadowScope(lim Limits) (Scope, error)

CompileShadowScope compiles the optional shadow-scope fallback. Returns an empty scope (matches nothing) when no shadow scope is configured.

func (SignedConfig) ScopeHash

func (c SignedConfig) ScopeHash(lim Limits) string

ScopeHash returns the deterministic content hash of the compiled scope, or "" if the scope does not compile.

func (SignedConfig) Validate

func (c SignedConfig) Validate(capability Capability, lim Limits) error

Validate checks the config is well-formed and safe to apply: a supported selector schema, a valid mode, a matching capability, an accepted connector mode (Gateway), and a compilable scope. It is pure and fails closed.

type State

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

State is the capability-local rollout runtime state: the active mode + compiled scope (read lock-free on the request path), the emergency kill switch, the desired mode, bounded transition history, rollback metadata, and the evidence summary. Gateway and Management each own an independent State; nothing is shared between them.

func NewState

func NewState(capability Capability, lim Limits) *State

NewState returns a capability-local State seeded to Disabled with an empty scope.

func (*State) Capability

func (s *State) Capability() Capability

Capability returns the state's capability.

func (*State) ClearKillSwitch

func (s *State) ClearKillSwitch()

ClearKillSwitch clears the emergency disable. Idempotent.

func (*State) CurrentConfig

func (s *State) CurrentConfig() SignedConfig

CurrentConfig returns the active signed config (lock-free).

func (*State) CurrentMode

func (s *State) CurrentMode() Mode

CurrentMode returns the active mode (lock-free).

func (*State) Desired

func (s *State) Desired() Mode

Desired returns the desired mode.

func (*State) EngageKillSwitch

func (s *State) EngageKillSwitch(actor string, atUnixNano int64)

EngageKillSwitch engages the emergency disable (admission stop) without changing the mode/scope. Idempotent. Restart-persistent via ToPersist.

func (*State) Evidence

func (s *State) Evidence() EvidenceSummary

Evidence returns a copy of the evidence summary.

func (*State) History

func (s *State) History() []TransitionRecord

History returns a copy of the bounded transition history.

func (*State) InScope

func (s *State) InScope(subj Subject) bool

InScope reports whether subj is inside the active mode's scope (lock-free).

func (*State) KillGeneration added in v1.0.218

func (s *State) KillGeneration() uint64

KillGeneration returns the MONOTONIC emergency-kill generation (lock-free), read from the same atomic snapshot as Killed() so the two are always mutually consistent. It increments once per distinct kill engagement and is never rolled back by a clear. The executor captures it at admission and re-reads it immediately before the irreversible upstream side effect: a differing value means an emergency kill was engaged while the request was in flight (even if since cleared), and the request MUST NOT cross the boundary (PREREQ-MCP-KILL-1, docs/design/mcp/SHADOW-ARCHITECTURE.md §10). Because the generation is published in the SAME pointer swap that sets `killed`, an engagement that is observable via Killed() has necessarily advanced the generation too — so the boundary's generation-only re-read also catches a kill still in its engage critical section, with no split-publication window, and subsumes the "currently killed" case.

func (*State) Killed

func (s *State) Killed() bool

Killed reports whether the emergency kill switch is engaged (lock-free). A killed capability refuses new admission (ReasonRolloutEmergencyActive).

func (*State) LoadPersist

func (s *State) LoadPersist(p StatePersist) error

LoadPersist restores node-local state from a durable DTO. It re-validates and re-compiles the config (fail closed to Disabled on any error) and restores the kill switch, desired mode, history, rollback, and evidence.

func (*State) RecordRollback

func (s *State) RecordRollback(targetHash, commandID string, atUnixNano int64)

RecordRollback records a rollback/demotion reference for status truthfulness.

func (*State) ResolveFor

func (s *State) ResolveFor(subj Subject, action ActionKind, hardFailure bool, hardReason mcperr.Reason, obligationsSatisfied bool) Resolution

ResolveFor combines the active mode/scope with a resolved policy action + hard failure to produce the effective disposition. It is the single entry the runtime executor calls at the seam; it reads state lock-free and delegates to Resolve.

func (*State) ScopeHash

func (s *State) ScopeHash() string

ScopeHash returns the active scope's content hash (lock-free).

func (*State) SetConfig

func (s *State) SetConfig(cfg SignedConfig, actor string, atUnixNano int64) error

SetConfig validates cfg, compiles its scopes, and atomically installs it. It is used by the signed-snapshot apply path (the mode/scope are authoritative from the CP). It preserves the current kill-switch state (an emergency disable is not cleared by a config apply). A mode change is appended to history.

func (*State) SetDesired

func (s *State) SetDesired(m Mode)

SetDesired records the operator's desired mode (the target of an in-flight promotion whose distribution may still be pending).

func (*State) ShadowInScope

func (s *State) ShadowInScope(subj Subject) bool

ShadowInScope reports whether subj is inside the shadow-scope fallback.

func (*State) ToPersist

func (s *State) ToPersist() StatePersist

ToPersist snapshots the state into the restart-durable DTO.

func (*State) UpdateEvidence

func (s *State) UpdateEvidence(fn func(*EvidenceSummary))

UpdateEvidence applies fn to the evidence summary under the lock.

type StatePersist

type StatePersist struct {
	Version    int                `json:"version"`
	Capability Capability         `json:"capability"`
	Config     SignedConfig       `json:"config"`
	Killed     bool               `json:"killed"`
	Desired    Mode               `json:"desired"`
	History    []TransitionRecord `json:"history,omitempty"`
	Rollback   RollbackState      `json:"rollback"`
	Evidence   EvidenceSummary    `json:"evidence"`
}

StatePersist is the restart-durable, node-local DTO. It carries the kill-switch state, desired mode, bounded history, rollback metadata, and evidence — the node-local bits that must survive a restart. The active mode/scope are re-established from the signed snapshot on the DP (config is included for a CP that owns it locally).

type Subject

type Subject struct {
	Capability      Capability
	Tenant          string
	ServerID        string
	ToolFingerprint string // exact fingerprint hash
	ToolName        string
	PrincipalID     string
	AgentID         string
	ClientID        string
	Groups          []string
	Environment     string
	Operation       RiskClass
}

Subject is the per-request attribute tuple matched against a scope. It is derived from already-resolved request state (identity, registry, catalog, policy operation class); matching reads only these fields and never performs I/O or reads a clock.

type ToolSel

type ToolSel struct {
	Server      string `json:"server"`
	Name        string `json:"name"`
	Fingerprint string `json:"fingerprint"`
}

ToolSel is an exact tool selector: a tool name is only meaningful when bound to its server and fingerprint (a bare name is never a selector).

type TransitionInput

type TransitionInput struct {
	Capability Capability
	From       Mode
	To         Mode
	// Qualification is consulted ONLY for a promotion whose target is Production. It
	// is ignored for every other transition. nil ⇒ Production is unreachable.
	Qualification ProductionQualificationVerifier
	// Binding is required (and only used) when To == ModeProduction. It binds the
	// receipt to the exact capability/scope/snapshot being promoted.
	Binding QualificationBinding
}

TransitionInput fully describes a requested mode change.

type TransitionKind

type TransitionKind uint8

TransitionKind classifies a mode change.

const (
	// TransitionNone is the zero value (no valid transition classified).
	TransitionNone TransitionKind = iota
	// TransitionPromotion is a one-stage move up the ladder.
	TransitionPromotion
	// TransitionDemotion is a move down the ladder by one or more stages (including
	// an emergency straight to Disabled). It never requires a qualification receipt.
	TransitionDemotion
)

func CheckTransition

func CheckTransition(in TransitionInput) (TransitionKind, error)

CheckTransition is the single authoritative gate for a mode change. It returns the classified kind and a nil error only for an allowed transition; otherwise a classified, fail-closed error. It is pure (no I/O, no clock) except for the injected qualification verifier, which is consulted exactly once and only for a Production promotion.

Rules (ROLLOUT-AND-ROLLBACK.md §1, §3):

  • promotion is strictly one stage at a time (Disabled→Observe→Shadow→Canary→ Production); any skip (Disabled→Shadow, Observe→Canary, Shadow→Production) is rejected;
  • Canary→Production requires a valid Production Qualification receipt;
  • demotion may narrow by one or more stages and never needs a receipt;
  • a no-op (To == From) is not a transition — use a scope update instead;
  • an unknown/future mode is rejected.

type TransitionRecord

type TransitionRecord struct {
	From       Mode           `json:"from"`
	To         Mode           `json:"to"`
	Kind       TransitionKind `json:"kind"`
	ScopeHash  string         `json:"scope_hash"`
	Actor      string         `json:"actor"` // sanitized admin identity
	AtUnixNano int64          `json:"at_unix_nano"`
	Emergency  bool           `json:"emergency"`
	Note       string         `json:"note,omitempty"`
}

TransitionRecord is one bounded, sanitized transition-history entry.

Jump to

Keyboard shortcuts

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