Documentation
¶
Overview ¶
Package guardy provides a pipeline engine for AI guardrails: validation, intervention actions (pass, block, redact, retry), and three-phase execution (sequential mutation, scoped policy, then parallel read-only via errgroup).
Boundary contracts: typed ScopeKey / ScopeRequirement, canonical Decision / PolicyFailure, ArgsPipeline / GuardedArgs, JSONArgsPipeline / GuardedJSONArgs, GuardedDelivery, DeliveryPolicy, GuardEvent, and GuardRoute.
See CONTRACTS.md for boundary and release invariants.
Example (GuardedConsumer) ¶
package main
import (
"context"
"fmt"
"strings"
g "github.com/skosovsky/guardy"
)
func main() {
redact := g.ValidatorFunc[string](func(_ context.Context, value string) (string, *g.Report, error) {
clean := strings.ReplaceAll(value, "[email protected]", "[email]")
return clean, &g.Report{Action: g.ActionRedact}, nil
})
pipeline := g.MustNewPipeline(g.WithSequential(redact))
delivery, err := pipeline.GuardOutput(context.Background(), nil, "Contact [email protected]")
if err != nil {
fmt.Println("delivery rejected")
return
}
projection, ok := delivery.Projection()
if !ok {
return
}
fmt.Println(projection.Value)
}
Output: Contact [email]
Index ¶
- Constants
- Variables
- func Guard[T any](p *Pipeline[T], extractor func(*http.Request) (T, error), ...) (func(http.Handler) http.Handler, error)
- func MissingScopeKeys(err error) []string
- func MustGuard[T any](p *Pipeline[T], extractor func(*http.Request) (T, error), ...) func(http.Handler) http.Handler
- func PlainTextInjector() func(*http.Request, string) error
- func WithCompletedObservations(cause error, completed ...*Report) error
- func WrapArgs[Req, Res any](p *ArgsPipeline[Req], scopeFactory ScopeFactory, next Handler[Req, Res]) func(context.Context, string) (Res, GuardedArgs[Req], error)
- func WrapGuardedArgs[Req, Res any](p *ArgsPipeline[Req], scopeFactory ScopeFactory, ...) func(context.Context, string) (Res, GuardedArgs[Req], error)
- func WrapGuardedJSONArgs[Res any](p *JSONArgsPipeline, scopeFactory ScopeFactory, ...) func(context.Context, string) (Res, GuardedJSONArgs, error)
- func WrapGuardedOutput[Req, Res any](p *Pipeline[Res], scopeFactory ScopeFactory, next Handler[Req, Res]) func(context.Context, Req) (GuardedDelivery[Res], error)
- func WrapInput[Req, Res any](p *Pipeline[Req], scopeFactory ScopeFactory, ...) func(context.Context, Req) (Res, error)
- func WrapOutput[Req, Res any](p *Pipeline[Res], scopeFactory ScopeFactory, ...) func(context.Context, Req) (Res, error)
- type Action
- type ArgsOption
- func WithArgsCodec[T any](decode func(string, *T) error, encode func(T) (string, error)) ArgsOption[T]
- func WithArgsConfigurationID[T any](identity string) ArgsOption[T]
- func WithArgsFinalGuard[T any](final *Pipeline[string]) ArgsOption[T]
- func WithArgsShapeProvider[T any](provider ShapeProvider[T]) ArgsOption[T]
- type ArgsPipeline
- type AttributeComparisonError
- type BlockError
- type Boundary
- type BoundaryConfigurationError
- type BoundaryProfile
- type CompletedObservationsError
- type ConfigurationError
- type ControlSpec
- type Decision
- type DeliveryClassificationError
- type DeliveryClassifier
- type DeliveryPolicy
- type DeliveryPolicyOption
- type DeliveryProjection
- type ExecutionScope
- type FailureDisposition
- type GuardEvent
- type GuardOption
- type GuardRoute
- type GuardRouteOutcome
- type GuardTelemetry
- type GuardedArgs
- type GuardedArgsHandler
- type GuardedDelivery
- type GuardedJSONArgs
- type GuardedJSONArgsHandler
- type Handler
- type JSONArgsMetadata
- type JSONArgsOption
- type JSONArgsPipeline
- func (p *JSONArgsPipeline) RequiredScope() []ScopeRequirement
- func (p *JSONArgsPipeline) RequiredScopeKeys() []string
- func (p *JSONArgsPipeline) SchemaID() string
- func (p *JSONArgsPipeline) Shape() (any, bool)
- func (p *JSONArgsPipeline) Validate(ctx context.Context, scope ExecutionScope, raw string) (GuardedJSONArgs, error)
- type JSONArgsValidator
- type JSONArgsValidatorFunc
- type Judge
- type LLMJudge
- type MapScope
- type Matcher
- type Observer
- type PayloadKind
- type Pipeline
- func (p *Pipeline[T]) GuardDelivery(ctx context.Context, scope ExecutionScope, policy DeliveryPolicy, output T) (GuardedDelivery[T], error)
- func (p *Pipeline[T]) GuardOutput(ctx context.Context, scope ExecutionScope, output T) (GuardedDelivery[T], error)
- func (p *Pipeline[T]) MustUse(mw ...ValidatorMiddleware[T]) *Pipeline[T]
- func (p *Pipeline[T]) RequiredScope() []ScopeRequirement
- func (p *Pipeline[T]) RequiredScopeKeys() []string
- func (p *Pipeline[T]) Run(ctx context.Context, scope ExecutionScope, input T) (RunResult[T], error)
- func (p *Pipeline[T]) Use(mw ...ValidatorMiddleware[T]) (*Pipeline[T], error)
- type PipelineOption
- func WithObserver[T any](o Observer) PipelineOption[T]
- func WithParallel[T any](v ...Validator[T]) PipelineOption[T]
- func WithPipelineName[T any](name string) PipelineOption[T]
- func WithPolicyValidators[T any](pv ...PolicyValidator[T]) PipelineOption[T]
- func WithSequential[T any](v ...Validator[T]) PipelineOption[T]
- func WithUserChannel[T any]() PipelineOption[T]
- func WithUserChannelFallback[T any](msg string) PipelineOption[T]
- type PolicyConfig
- type PolicyFailure
- type PolicyOption
- func WithPolicyCode(code string) PolicyOption
- func WithPolicyFatal(fatal bool) PolicyOption
- func WithPolicyName(name string) PolicyOption
- func WithPolicyReason(reason string) PolicyOption
- func WithPolicyRetryable(retryable bool) PolicyOption
- func WithPolicySafeUserMessage(msg string) PolicyOption
- func WithPolicySeverity(sev Severity) PolicyOption
- type PolicyValidator
- func MustPolicyFuncWithScope[T any](requirements []ScopeRequirement, ...) PolicyValidator[T]
- func MustTypedAttributeEquals[T any, V comparable](key ScopeKey[V], want V, opts ...PolicyOption) PolicyValidator[T]
- func MustTypedAttributePresent[T any, V any](key ScopeKey[V], opts ...PolicyOption) PolicyValidator[T]
- func NewPolicyFuncWithScope[T any](requirements []ScopeRequirement, ...) (PolicyValidator[T], error)
- func NewTypedAttributeEquals[T any, V comparable](key ScopeKey[V], want V, opts ...PolicyOption) (PolicyValidator[T], error)
- func NewTypedAttributePresent[T any, V any](key ScopeKey[V], opts ...PolicyOption) (PolicyValidator[T], error)
- func WithStreamingPolicyCapabilities(v PolicyValidator[string], capability StreamCapabilities) PolicyValidator[string]
- type PostBindValidator
- type ReleaseError
- type ReleaseProfile
- type RemediationPolicy
- type Report
- func (r *Report) Clone() *Report
- func (r *Report) CloneWithoutState() *Report
- func (r *Report) IsObservation() bool
- func (r *Report) IsRetryableCorrection() bool
- func (r *Report) IsSystemFault() bool
- func (r *Report) IsTerminalDeny() bool
- func (r *Report) OrchestratorMessage() string
- func (r *Report) PublicMessage() string
- type RetryError
- type RunResult
- type ScopeBinding
- type ScopeFactory
- type ScopeFunc
- type ScopeIncompleteError
- type ScopeKey
- type ScopeRequirement
- type ScopeTypeError
- type SemanticValidator
- type Severity
- type ShapeProvider
- type ShapeProviderFunc
- type StaticScope
- type StreamCapabilities
- type StreamCategory
- type StreamConfig
- type StreamEvent
- type StreamOutcome
- type StreamProcessor
- func (s *StreamProcessor) Abort(cause error) (StreamOutcome, error)
- func (s *StreamProcessor) Close() error
- func (s *StreamProcessor) Complete(ctx context.Context) (StreamOutcome, error)
- func (s *StreamProcessor) DeliverFallback(ctx context.Context) (StreamOutcome, error)
- func (s *StreamProcessor) Outcome() StreamOutcome
- func (s *StreamProcessor) Write(p []byte) (int, error)
- func (s *StreamProcessor) WriteContext(ctx context.Context, p []byte) (int, error)
- type StreamStage
- type ValidationPhase
- type Validator
- type ValidatorFaultError
- type ValidatorFunc
- type ValidatorMiddleware
- type ValidatorPanicError
Examples ¶
- Package (GuardedConsumer)
- ArgsPipeline.Validate
- CompileStream
- Decision.Route
- Guard
- JSONArgsPipeline.Validate
- MustNewPipeline
- Pipeline.GuardDelivery
- Pipeline.GuardOutput
- Pipeline.Run
- Pipeline.Run (WithScope)
- ScopeFactory (PolicyFacts)
- ScopeKey (SourceTransformArgumentsDestination)
- WrapGuardedJSONArgs
Constants ¶
const ( CodeJSONInvalid = "JSON_INVALID" CodeJSONRedactCorrupted = "JSON_REDACT_CORRUPTED" CodeJSONSchemaInvalid = "JSON_SCHEMA_INVALID" CodePolicyViolation = "POLICY_VIOLATION" CodeAttributeMissing = "ATTRIBUTE_MISSING" CodeAttributeMismatch = "ATTRIBUTE_MISMATCH" CodeAttributeTypeMismatch = "ATTRIBUTE_TYPE_MISMATCH" CodePostBindViolation = "POST_BIND_VIOLATION" CodeValidatorFailed = "VALIDATOR_FAILED" )
Neutral machine-readable report codes (host apps may define their own strings).
const DefaultMaxBodyBytes = 1 << 20
DefaultMaxBodyBytes is the default request body size limit for Guard (1 MiB of consumed input).
Variables ¶
var ( // ErrBlocked is returned when the pipeline result is Block (e.g. by StreamProcessor, WrapInput, WrapOutput). // Match with [errors.Is] against err and ErrBlocked for quick checks; use [errors.As] into [*PolicyFailure] for routing. ErrBlocked = errors.New("guardy: input blocked") // ErrRetryRequested is returned when the pipeline result is Retry; the orchestrator should retry with Feedback. // Match with [errors.Is] against err and ErrRetryRequested for quick checks; use [errors.As] into [*PolicyFailure] for routing. ErrRetryRequested = errors.New("guardy: retry requested") // ErrValidatorFailed is returned when a validator returns a system error. // Use [errors.As] into [*PolicyFailure] for the canonical system-fault decision. ErrValidatorFailed = errors.New("guardy: validator failed") )
var ( // ErrInvalidStreamUnit indicates malformed or incompatible framed input. ErrInvalidStreamUnit = errors.New("guardy: invalid stream unit") // ErrIncompleteStreamUnit indicates input ended before a complete unit. ErrIncompleteStreamUnit = errors.New("guardy: incomplete stream unit") // ErrStreamUnitLimit indicates framing exceeded the configured unit budget. ErrStreamUnitLimit = errors.New("guardy: stream unit exceeds limit") )
var ErrAttributeIncomparable = errors.New("guardy: attribute equality requires comparable values")
ErrAttributeIncomparable identifies equality operands that cannot safely use Go ==.
var ErrBoundaryConfiguration = errors.New("guardy: invalid boundary configuration")
ErrBoundaryConfiguration identifies a rejected mapping/coverage contract.
var ErrConfiguration = errors.New("guardy: invalid configuration")
ErrConfiguration identifies invalid built-in compilation settings.
var ErrDeliveryClassification = errors.New("guardy: unsupported delivery representation")
ErrDeliveryClassification identifies unsupported or cyclic representations.
var ErrScopeIncompatible = errors.New("guardy: incompatible scope value")
ErrScopeIncompatible distinguishes incompatible facts from absent facts.
var ErrScopeIncomplete = errors.New("guardy: execution scope incomplete")
ErrScopeIncomplete is returned when Pipeline.Run is called without required scope keys.
Functions ¶
func Guard ¶
func Guard[T any]( p *Pipeline[T], extractor func(*http.Request) (T, error), injector func(*http.Request, T) error, opts ...GuardOption, ) (func(http.Handler) http.Handler, error)
Guard builds HTTP request middleware, returning deterministic config errors. Extractor/injector and handler borrow bodies; Guard closes consumed/installed bodies as specified in CONTRACTS.md. Redaction uses returned T, not MutatedText. Oversize is 413; read/extract error is 400; deny/retry is 422; faults are 500. Extractor/injector/next and options must not panic; they are trusted host callbacks.
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"github.com/skosovsky/guardy"
"github.com/skosovsky/guardy/ext"
)
func main() {
regexV, _ := ext.NewRegexValidator(`(?i)ignore`, ext.WithCode("INJECT"))
pipeline := guardy.MustNewPipeline(guardy.WithSequential(regexV))
extractor := func(r *http.Request) (string, error) {
body, _ := io.ReadAll(r.Body)
return string(body), nil
}
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
handler := guardy.MustGuard(pipeline, extractor, guardy.PlainTextInjector())(next)
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("hello"))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Println(rec.Code)
}
Output: 200
func MissingScopeKeys ¶ added in v0.10.0
MissingScopeKeys extracts missing scope keys from an error.
func MustGuard ¶ added in v0.13.0
func MustGuard[T any]( p *Pipeline[T], extractor func(*http.Request) (T, error), injector func(*http.Request, T) error, opts ...GuardOption, ) func(http.Handler) http.Handler
MustGuard builds HTTP middleware or panics on Guard's configuration error.
func PlainTextInjector ¶ added in v0.5.0
PlainTextInjector returns an injector that replaces the request body with the mutated string. Syncs Body, ContentLength, Header[Content-Length], and GetBody for proxy/retry compatibility. Guard closes the replaced borrowed body. Standalone callers must close the old body themselves and own the new body and each independently opened GetBody.
func WithCompletedObservations ¶ added in v0.13.0
WithCompletedObservations attaches only previously completed reports to a fault. It combines nested carrier evidence from wrapped/joined causes. A nil cause returns nil; with no observations the original error is returned unchanged. Reports returned by the failing callback must not be passed as completed.
func WrapArgs ¶ added in v0.10.0
func WrapArgs[Req, Res any]( p *ArgsPipeline[Req], scopeFactory ScopeFactory, next Handler[Req, Res], ) func(context.Context, string) (Res, GuardedArgs[Req], error)
WrapArgs validates raw arguments through an ArgsPipeline before calling next.
func WrapGuardedArgs ¶ added in v0.11.0
func WrapGuardedArgs[Req, Res any]( p *ArgsPipeline[Req], scopeFactory ScopeFactory, next GuardedArgsHandler[Req, Res], ) func(context.Context, string) (Res, GuardedArgs[Req], error)
WrapGuardedArgs validates raw arguments and passes the full GuardedArgs boundary to next.
func WrapGuardedJSONArgs ¶ added in v0.11.0
func WrapGuardedJSONArgs[Res any]( p *JSONArgsPipeline, scopeFactory ScopeFactory, next GuardedJSONArgsHandler[Res], ) func(context.Context, string) (Res, GuardedJSONArgs, error)
WrapGuardedJSONArgs validates dynamic raw JSON and passes the full GuardedJSONArgs boundary to next.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/guardy"
)
func main() {
argsPipeline := guardy.MustCompileJSONArgs(
guardy.MustNewPipeline[string](),
nil,
guardy.WithJSONArgsMetadata(guardy.JSONArgsMetadata{ID: "command.schema"}),
)
handler := guardy.WrapGuardedJSONArgs(
argsPipeline,
nil,
func(_ context.Context, args guardy.GuardedJSONArgs) (string, error) {
return args.SchemaID + ":" + args.Object["name"].(string), nil
},
)
result, args, err := handler(context.Background(), `{"name":"Ada"}`)
if err != nil {
panic(err)
}
fmt.Println(result)
fmt.Println(args.Decision.Action)
}
Output: command.schema:Ada pass
func WrapGuardedOutput ¶ added in v0.10.0
func WrapGuardedOutput[Req, Res any]( p *Pipeline[Res], scopeFactory ScopeFactory, next Handler[Req, Res], ) func(context.Context, Req) (GuardedDelivery[Res], error)
WrapGuardedOutput validates next's output and returns a guarded output contract. ScopeFactory obtains current facts after next succeeds, immediately before validation. Handler errors suppress the partial value and do not call the scope factory. Deliver only an approved Projection. Neither validation nor errors can undo handler side effects; this wrapper never retries next.
func WrapInput ¶ added in v0.7.0
func WrapInput[Req, Res any]( p *Pipeline[Req], scopeFactory ScopeFactory, next func(context.Context, Req) (Res, error), ) func(context.Context, Req) (Res, error)
WrapInput constructs current caller-owned facts through scopeFactory, then runs the pipeline on the request value before calling next. Nil factories mean empty scope. Deadlines and cancellation come from ctx (e.g. wrap with context.WithTimeout at the call site); no implicit timeout is applied.
On ActionRedact, next receives the mutated Output from the pipeline. Terminal deny (Report.IsTerminalDeny) returns *BlockError (unwraps to ErrBlocked; use errors.As for Disposition). Retryable correction (Report.IsRetryableCorrection) returns *RetryError (unwraps to ErrRetryRequested).
Composing WrapOutput(outPipeline, WrapInput(inPipeline, fn)) yields input and output guards around fn without net/http.
func WrapOutput ¶ added in v0.7.0
func WrapOutput[Req, Res any]( p *Pipeline[Res], scopeFactory ScopeFactory, next func(context.Context, Req) (Res, error), ) func(context.Context, Req) (Res, error)
WrapOutput runs next first, then constructs current caller-owned facts through scopeFactory and validates the result. Facts are refreshed after handler execution, including any host-controlled pause. Nil factories mean empty scope. This is a low-level partial-result API. If next returns an error, res is returned unvalidated and must not reach a sink. Prefer WrapGuardedOutput for delivery. Neither wrapper retries next or undoes its side effects. Deadlines for the output pipeline use the same ctx as for next.
On ActionRedact, the returned value is the pipeline Output (mutated). Terminal deny and retryable correction follow the same disposition routing as WrapInput.
Types ¶
type Action ¶
type Action int
Action is the intervention outcome from a validator or pipeline.
type ArgsOption ¶ added in v0.10.0
type ArgsOption[T any] func(*ArgsPipeline[T])
ArgsOption configures ArgsPipeline.
func WithArgsCodec ¶ added in v0.12.0
func WithArgsCodec[T any](decode func(string, *T) error, encode func(T) (string, error)) ArgsOption[T]
WithArgsCodec installs caller-owned bind/encode functions. Both are required. Encode must faithfully represent the bound value; custom codecs own this invariant.
func WithArgsConfigurationID ¶ added in v0.12.0
func WithArgsConfigurationID[T any](identity string) ArgsOption[T]
WithArgsConfigurationID attaches caller-owned policy/configuration identity.
func WithArgsFinalGuard ¶ added in v0.12.0
func WithArgsFinalGuard[T any](final *Pipeline[string]) ArgsOption[T]
WithArgsFinalGuard checks canonical bytes after decode and all post-bind hooks. Providing this option requires a non-nil pipeline; omitting it permits no final checks. This pipeline must be read-only: changing final bytes is a configuration fault.
func WithArgsShapeProvider ¶ added in v0.10.0
func WithArgsShapeProvider[T any](provider ShapeProvider[T]) ArgsOption[T]
WithArgsShapeProvider attaches optional shape metadata to an args pipeline.
type ArgsPipeline ¶ added in v0.10.0
type ArgsPipeline[T any] struct { // contains filtered or unexported fields }
ArgsPipeline validates raw arguments and decodes them into T as one guardy-owned contract.
func CompileArgs ¶ added in v0.10.0
func CompileArgs[T any](raw *Pipeline[string], opts ...ArgsOption[T]) (*ArgsPipeline[T], error)
CompileArgs builds a typed arguments pipeline from a raw string guard.
func MustCompileArgs ¶ added in v0.10.0
func MustCompileArgs[T any](raw *Pipeline[string], opts ...ArgsOption[T]) *ArgsPipeline[T]
MustCompileArgs is like CompileArgs but panics on invalid configuration.
func (*ArgsPipeline[T]) RequiredScope ¶ added in v0.10.0
func (p *ArgsPipeline[T]) RequiredScope() []ScopeRequirement
RequiredScope returns typed scope requirements from the raw guard.
func (*ArgsPipeline[T]) RequiredScopeKeys ¶ added in v0.10.0
func (p *ArgsPipeline[T]) RequiredScopeKeys() []string
RequiredScopeKeys returns scope keys from the raw guard.
func (*ArgsPipeline[T]) Shape ¶ added in v0.10.0
func (p *ArgsPipeline[T]) Shape() (any, bool)
Shape returns optional metadata attached at compile time.
func (*ArgsPipeline[T]) Validate ¶ added in v0.10.0
func (p *ArgsPipeline[T]) Validate(ctx context.Context, scope ExecutionScope, raw string) (GuardedArgs[T], error)
Validate runs raw validation before decoding into T. Cancellation is checked before/after each codec and post-bind callback and outranks correction. Wrapped cancellation causes remain accessible through errors.Is.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/guardy"
)
func main() {
type Command struct {
Name string `json:"name"`
}
argsPipeline := guardy.MustCompileArgs[Command](guardy.MustNewPipeline[string]())
payload, err := argsPipeline.Validate(context.Background(), nil, `{"name":"Ada"}`)
if err != nil {
panic(err)
}
fmt.Println(payload.Value.Name)
fmt.Println(payload.Decision.Action)
}
Output: Ada pass
type AttributeComparisonError ¶ added in v0.12.0
type AttributeComparisonError struct{ Key string }
AttributeComparisonError identifies the scope key of an invalid equality check. It contains no operand values and is a system fault when returned through Pipeline.
func (*AttributeComparisonError) Error ¶ added in v0.12.0
func (e *AttributeComparisonError) Error() string
func (*AttributeComparisonError) Unwrap ¶ added in v0.12.0
func (e *AttributeComparisonError) Unwrap() error
type BlockError ¶ added in v0.9.0
type BlockError struct {
Message string
Failure PolicyFailure
// contains filtered or unexported fields
}
BlockError carries a terminal policy failure from WrapInput or WrapOutput.
func (*BlockError) As ¶ added in v0.10.0
func (e *BlockError) As(target any) bool
As exposes the canonical policy failure contract.
func (*BlockError) Error ¶ added in v0.9.0
func (e *BlockError) Error() string
Error implements error.
func (*BlockError) ReportSnapshot ¶ added in v0.10.0
func (e *BlockError) ReportSnapshot() Report
ReportSnapshot returns a validator report snapshot for telemetry.
func (*BlockError) Unwrap ¶ added in v0.9.0
func (e *BlockError) Unwrap() error
Unwrap returns ErrBlocked so errors.Is matches *BlockError.
type Boundary ¶ added in v0.12.0
type Boundary string
Boundary identifies a configured data interception point, not an authorization gate.
type BoundaryConfigurationError ¶ added in v0.12.0
BoundaryConfigurationError distinguishes incompatible mappings from unsupported mandatory coverage without embedding caller data in public error text.
func (*BoundaryConfigurationError) Error ¶ added in v0.12.0
func (e *BoundaryConfigurationError) Error() string
func (*BoundaryConfigurationError) Unwrap ¶ added in v0.12.0
func (e *BoundaryConfigurationError) Unwrap() error
type BoundaryProfile ¶ added in v0.12.0
type BoundaryProfile struct {
// contains filtered or unexported fields
}
BoundaryProfile is an immutable declaration of caller-reported adapter coverage. It checks declared membership, not real wiring or enforcement. Caller owns the adapters; prove handler/sink behavior with integration fixtures.
func CompileBoundaryProfile ¶ added in v0.12.0
func CompileBoundaryProfile(identity string, supported, mandatory []Boundary) (*BoundaryProfile, error)
CompileBoundaryProfile rejects unsupported mandatory boundaries before execution. Supported must list only boundaries that the integration really enforces; CompileBoundaryProfile cannot inspect or verify that claim.
func (*BoundaryProfile) Covers ¶ added in v0.12.0
func (p *BoundaryProfile) Covers(b Boundary) bool
Covers reports only the explicitly configured boundary coverage.
func (*BoundaryProfile) Identity ¶ added in v0.12.0
func (p *BoundaryProfile) Identity() string
Identity is the caller-supplied mapping/configuration fingerprint.
type CompletedObservationsError ¶ added in v0.13.0
type CompletedObservationsError struct {
// contains filtered or unexported fields
}
CompletedObservationsError carries explicitly attested observations completed before a processing error. The failed callback's report/output are not evidence. Fields are private; construction and projections snapshot reports without MutatedText. The host trusts adapter code to attest only completed checks, as with capabilities.
func (*CompletedObservationsError) CompletedReport ¶ added in v0.13.0
func (e *CompletedObservationsError) CompletedReport() *Report
CompletedReport returns an independent snapshot, never a transformed value.
func (*CompletedObservationsError) Error ¶ added in v0.13.0
func (*CompletedObservationsError) Error() string
Error exposes a fixed fault category, never the diagnostic cause or observations.
func (*CompletedObservationsError) Unwrap ¶ added in v0.13.0
func (e *CompletedObservationsError) Unwrap() error
Unwrap preserves original typed errors and wrapped cancellation.
type ConfigurationError ¶ added in v0.12.0
ConfigurationError contains a component, field path and diagnostic code. These identifiers must be library-owned; never put caller values in them. Detailed third-party errors may be inspected through Cause, not default Error text.
func (*ConfigurationError) Error ¶ added in v0.12.0
func (e *ConfigurationError) Error() string
Error returns safe configuration identifiers without caller data.
func (*ConfigurationError) Unwrap ¶ added in v0.12.0
func (e *ConfigurationError) Unwrap() error
Unwrap preserves the configuration category and optional diagnostic cause.
type ControlSpec ¶ added in v0.8.0
ControlSpec supplies optional overrides for Report control-flow flags.
type Decision ¶ added in v0.10.0
type Decision struct {
Action Action
Disposition FailureDisposition
Code string
SafeMessage string
RetryFeedback string
PayloadKind PayloadKind
Validator string
Severity Severity
}
Decision is the canonical control-flow contract returned at guardy boundaries. Use it for orchestration and host integration instead of parsing Report text fields.
func DecisionFromReport ¶ added in v0.10.0
DecisionFromReport converts a validator or pipeline report into the canonical host-facing decision contract.
func (Decision) IsRetryable ¶ added in v0.10.0
IsRetryable reports whether retrying with a corrected payload may succeed.
func (Decision) IsSystemFault ¶ added in v0.10.0
IsSystemFault reports whether the decision came from guardy infrastructure or validator failure.
func (Decision) IsTerminal ¶ added in v0.10.0
IsTerminal reports whether the decision is a hard stop.
func (Decision) Route ¶ added in v0.11.0
func (d Decision) Route(policy RemediationPolicy) (GuardRoute, error)
Route projects the decision into a host routing outcome.
Example ¶
package main
import (
"fmt"
"github.com/skosovsky/guardy"
)
func main() {
decision := guardy.DecisionFromReport(guardy.FinishReport(&guardy.Report{
Action: guardy.ActionRetry,
Feedback: "fix the payload",
}, guardy.ControlSpec{Action: guardy.ActionRetry}))
route, err := decision.Route(guardy.RemediationPolicy{RetryAttempt: 1, MaxRetries: 3})
if err != nil {
panic(err)
}
fmt.Println(route.Outcome)
fmt.Println(route.Retryable)
fmt.Println(route.RetryFeedback)
}
Output: retry_correction true fix the payload
type DeliveryClassificationError ¶ added in v0.13.0
type DeliveryClassificationError struct{ Code string }
DeliveryClassificationError contains only a library-owned diagnostic code.
func (*DeliveryClassificationError) Error ¶ added in v0.13.0
func (e *DeliveryClassificationError) Error() string
func (*DeliveryClassificationError) Unwrap ¶ added in v0.13.0
func (e *DeliveryClassificationError) Unwrap() error
type DeliveryClassifier ¶ added in v0.13.0
type DeliveryClassifier func(any) (PayloadKind, error)
DeliveryClassifier classifies the actual destination representation of a value. The caller owns canonicalization/serialization, termination and thread safety. It must not mark unknown representations safe or mutate the value.
type DeliveryPolicy ¶ added in v0.11.0
type DeliveryPolicy struct {
Channel string
AllowedPayloadKinds []PayloadKind
Fallback any
Classifier DeliveryClassifier
// contains filtered or unexported fields
}
DeliveryPolicy requires an explicit destination, allowed kinds and classifier. Generic delivery makes no inference from Go shape or MarshalJSON. UserText shape classification is available separately through NewUserTextPolicy.
func NewDeliveryPolicy ¶ added in v0.11.0
func NewDeliveryPolicy(channel string, opts ...DeliveryPolicyOption) DeliveryPolicy
NewDeliveryPolicy creates a channel-aware delivery policy.
func NewUserTextPolicy ¶ added in v0.13.0
func NewUserTextPolicy(channel string, opts ...DeliveryPolicyOption) DeliveryPolicy
NewUserTextPolicy explicitly selects UserTextClassifier and safe-text eligibility. Other allowed kinds can be selected explicitly for technical destinations.
type DeliveryPolicyOption ¶ added in v0.11.0
type DeliveryPolicyOption func(*DeliveryPolicy)
DeliveryPolicyOption configures DeliveryPolicy.
func WithDeliveryAllowedKinds ¶ added in v0.11.0
func WithDeliveryAllowedKinds(kinds ...PayloadKind) DeliveryPolicyOption
WithDeliveryAllowedKinds allows the listed payload kinds for this delivery policy.
func WithDeliveryClassifier ¶ added in v0.13.0
func WithDeliveryClassifier(classifier DeliveryClassifier) DeliveryPolicyOption
WithDeliveryClassifier binds the caller's destination representation contract.
func WithDeliveryFallback ¶ added in v0.11.0
func WithDeliveryFallback(fallback any) DeliveryPolicyOption
WithDeliveryFallback configures a separately checked fallback for blocked delivery. nil means absent; a typed nil is present and must assert to the pipeline T. Compatibility is checked before processing; eligibility is never assumed.
type DeliveryProjection ¶ added in v0.12.0
type DeliveryProjection[T any] struct { Value T `json:"value"` Channel string `json:"channel"` Fallback bool `json:"fallback"` }
DeliveryProjection is the only object an adapter should serialize to a consumer. It carries no original values, reports, raw payload or correction feedback.
type ExecutionScope ¶ added in v0.9.0
ExecutionScope provides typed lookup for policy and decode phases. Host applications implement this or use MapScope.
type FailureDisposition ¶ added in v0.9.0
type FailureDisposition int
FailureDisposition classifies pipeline outcomes for control flow without parsing Code or Reason.
const ( // DispositionNone indicates pass or successful redact. DispositionNone FailureDisposition = iota // DispositionTerminalDeny indicates a hard deny (block, non-retryable retry, fatal). DispositionTerminalDeny // DispositionRetryableCorrection indicates the orchestrator may retry (ActionRetry && Retryable). DispositionRetryableCorrection // DispositionSystemFault indicates validator or pipeline infrastructure failure. DispositionSystemFault )
func DeriveDisposition ¶ added in v0.9.0
func DeriveDisposition(rep *Report, err error) FailureDisposition
DeriveDisposition computes disposition from report fields and an optional system error.
func (FailureDisposition) String ¶ added in v0.9.0
func (d FailureDisposition) String() string
String returns a stable name for telemetry.
type GuardEvent ¶ added in v0.11.0
type GuardEvent struct {
Scope ExecutionScope
Decision Decision
Report *Report
Phase ValidationPhase
PipelineName string
PayloadKind PayloadKind
Telemetry GuardTelemetry
}
GuardEvent carries explicit observer metadata for a guard report. Decision describes the observed violation without shadow suppression; Report retains ShadowMode.
type GuardOption ¶ added in v0.9.0
type GuardOption func(*guardConfig)
GuardOption configures HTTP Guard middleware.
func WithGuardMaxBodyBytes ¶ added in v0.13.0
func WithGuardMaxBodyBytes(limit int64) GuardOption
WithGuardMaxBodyBytes sets a positive consumed-input cap; default is 1 MiB.
func WithGuardScopeFactory ¶ added in v0.12.0
func WithGuardScopeFactory(scopeFactory ScopeFactory) GuardOption
WithGuardScopeFactory constructs current caller-owned facts for every request, after extraction and immediately before validation. A nil factory means empty scope.
type GuardRoute ¶ added in v0.11.0
type GuardRoute struct {
Outcome GuardRouteOutcome
Retryable bool
Terminal bool
SystemFault bool
Fallback bool
RetryExhausted bool
SafeMessage string
RetryFeedback string
Code string
PayloadKind PayloadKind
}
GuardRoute is guardy's routing projection for a canonical decision.
func RouteDecision ¶ added in v0.11.0
func RouteDecision(decision Decision, policy RemediationPolicy) (GuardRoute, error)
RouteDecision validates host counters and projects a decision without executing retries or delivery. FallbackDelivery requires a separate GuardDelivery check.
type GuardRouteOutcome ¶ added in v0.11.0
type GuardRouteOutcome string
GuardRouteOutcome is the machine-readable remediation outcome for a decision.
const ( GuardRouteAllow GuardRouteOutcome = "allow" GuardRouteRetryCorrection GuardRouteOutcome = "retry_correction" GuardRouteTerminalDeny GuardRouteOutcome = "terminal_deny" GuardRouteSystemFault GuardRouteOutcome = "system_fault" GuardRouteFallbackDelivery GuardRouteOutcome = "fallback_delivery" )
Known remediation outcomes.
type GuardTelemetry ¶ added in v0.11.0
type GuardTelemetry struct {
Action Action
Disposition FailureDisposition
Code string
Validator string
Severity Severity
PayloadKind PayloadKind
}
GuardTelemetry is safe, structured telemetry derived from a guard event.
type GuardedArgs ¶ added in v0.11.0
type GuardedArgs[T any] struct { Value T Raw string SanitizedRaw string Reports []Report Decision Decision PayloadKind PayloadKind ConfigurationID string }
GuardedArgs is the canonical typed argument boundary returned by guardy.
type GuardedArgsHandler ¶ added in v0.11.0
type GuardedArgsHandler[Req, Res any] func(context.Context, GuardedArgs[Req]) (Res, error)
GuardedArgsHandler is a host function shape that receives the full guardy argument boundary instead of only the decoded value.
type GuardedDelivery ¶ added in v0.11.0
type GuardedDelivery[T any] struct { Value T Kind PayloadKind Decision Decision Reports []Report Deliverable bool Channel string Fallback bool ConfigurationID string }
GuardedDelivery is the channel-aware guarded output contract.
func (GuardedDelivery[T]) DeliverableValue ¶ added in v0.11.0
func (o GuardedDelivery[T]) DeliverableValue() (T, bool)
DeliverableValue returns the guarded value only when guardy marked it deliverable.
func (GuardedDelivery[T]) Projection ¶ added in v0.12.0
func (o GuardedDelivery[T]) Projection() (DeliveryProjection[T], bool)
Projection extracts the permitted consumer representation.
type GuardedJSONArgs ¶ added in v0.11.0
type GuardedJSONArgs struct {
Raw string
SanitizedRaw string
Object map[string]any
SchemaID string
Reports []Report
Decision Decision
PayloadKind PayloadKind
ConfigurationID string
}
GuardedJSONArgs is the dynamic JSON argument boundary returned by guardy.
type GuardedJSONArgsHandler ¶ added in v0.11.0
type GuardedJSONArgsHandler[Res any] func(context.Context, GuardedJSONArgs) (Res, error)
GuardedJSONArgsHandler is a host function shape for dynamic JSON argument boundaries.
type Handler ¶ added in v0.10.0
Handler is a generic host function shape guardy can wrap without owning host types.
type JSONArgsMetadata ¶ added in v0.12.0
JSONArgsMetadata describes a caller schema without implying enforcement.
type JSONArgsOption ¶ added in v0.12.0
type JSONArgsOption func(*JSONArgsPipeline)
JSONArgsOption declares final checking and configuration identity.
func WithJSONArgsConfigurationID ¶ added in v0.12.0
func WithJSONArgsConfigurationID(identity string) JSONArgsOption
WithJSONArgsConfigurationID attaches caller policy/configuration identity.
func WithJSONArgsFinalGuard ¶ added in v0.12.0
func WithJSONArgsFinalGuard(final *Pipeline[string]) JSONArgsOption
WithJSONArgsFinalGuard requires final schema/policy checks on canonical bytes.
func WithJSONArgsMetadata ¶ added in v0.12.0
func WithJSONArgsMetadata(metadata JSONArgsMetadata) JSONArgsOption
WithJSONArgsMetadata attaches identity and shape only; it does not install a checker.
type JSONArgsPipeline ¶ added in v0.11.0
type JSONArgsPipeline struct {
// contains filtered or unexported fields
}
JSONArgsPipeline validates raw JSON and keeps the sanitized raw payload, decoded object, schema identity, and decision in one boundary value.
func CompileJSONArgs ¶ added in v0.11.0
func CompileJSONArgs( raw *Pipeline[string], checker JSONArgsValidator, opts ...JSONArgsOption, ) (*JSONArgsPipeline, error)
CompileJSONArgs builds a dynamic JSON arguments pipeline from a raw string guard.
func MustCompileJSONArgs ¶ added in v0.11.0
func MustCompileJSONArgs(raw *Pipeline[string], checker JSONArgsValidator, opts ...JSONArgsOption) *JSONArgsPipeline
MustCompileJSONArgs is like CompileJSONArgs but panics on invalid configuration.
func (*JSONArgsPipeline) RequiredScope ¶ added in v0.11.0
func (p *JSONArgsPipeline) RequiredScope() []ScopeRequirement
RequiredScope returns typed scope requirements from the raw guard.
func (*JSONArgsPipeline) RequiredScopeKeys ¶ added in v0.11.0
func (p *JSONArgsPipeline) RequiredScopeKeys() []string
RequiredScopeKeys returns scope keys from the raw guard.
func (*JSONArgsPipeline) SchemaID ¶ added in v0.11.0
func (p *JSONArgsPipeline) SchemaID() string
SchemaID returns the provider-supplied schema identity, if present.
func (*JSONArgsPipeline) Shape ¶ added in v0.11.0
func (p *JSONArgsPipeline) Shape() (any, bool)
Shape returns optional schema or shape metadata attached at compile time.
func (*JSONArgsPipeline) Validate ¶ added in v0.11.0
func (p *JSONArgsPipeline) Validate(ctx context.Context, scope ExecutionScope, raw string) (GuardedJSONArgs, error)
Validate runs raw validation before decoding into a dynamic JSON object. Context cancellation before/after the schema callback outranks its policy report.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/guardy"
)
func main() {
argsPipeline := guardy.MustCompileJSONArgs(
guardy.MustNewPipeline[string](),
nil,
guardy.WithJSONArgsMetadata(guardy.JSONArgsMetadata{ID: "command.schema"}),
)
args, err := argsPipeline.Validate(context.Background(), nil, `{"name":"Ada"}`)
if err != nil {
panic(err)
}
fmt.Println(args.SchemaID)
fmt.Println(args.Object["name"])
fmt.Println(args.Decision.Action)
}
Output: command.schema Ada pass
type JSONArgsValidator ¶ added in v0.12.0
JSONArgsValidator checks decoded objects using caller-owned rules. Metadata is supplied separately through WithJSONArgsMetadata.
type JSONArgsValidatorFunc ¶ added in v0.12.0
JSONArgsValidatorFunc adapts an executable callback to JSONArgsValidator. CompileJSONArgs rejects a nil function. Callback rules remain caller-owned.
func (JSONArgsValidatorFunc) ValidateJSONArgs ¶ added in v0.12.0
ValidateJSONArgs implements JSONArgsValidator.
type LLMJudge ¶ added in v0.4.0
type LLMJudge struct {
// contains filtered or unexported fields
}
LLMJudge is a Parallel validator that delegates to a Judge.
func MustLLMJudge ¶ added in v0.13.0
MustLLMJudge builds a judge validator or panics on NewLLMJudge's configuration error.
func NewLLMJudge ¶ added in v0.4.0
NewLLMJudge builds a validator that calls j.Evaluate. If shadow is true and the judge returns block, the report is marked ShadowMode.
type MapScope ¶ added in v0.9.0
MapScope is a simple in-memory ExecutionScope.
type Matcher ¶ added in v0.4.0
Matcher returns a similarity score for the text (e.g. from a vector search). Higher score means more likely to block; threshold is applied by SemanticValidator.
type Observer ¶ added in v0.4.1
type Observer func(ctx context.Context, event GuardEvent)
Observer is a callback invoked for non-blocking shadow block reports. It receives a typed event so telemetry does not need to recover scope or pipeline metadata from context wrappers.
type PayloadKind ¶ added in v0.9.0
type PayloadKind int
PayloadKind classifies pipeline output for user-channel filtering and control flow.
const ( // PayloadSafeUserText is safe to expose on the user channel. PayloadSafeUserText PayloadKind = iota // PayloadInternalControlSignal is orchestrator-internal (tool calls, routing). PayloadInternalControlSignal // PayloadTechnicalPayload is technical JSON or similar; must not reach end users. PayloadTechnicalPayload )
func AggregatePayloadKind ¶ added in v0.9.0
func AggregatePayloadKind(reports []Report) PayloadKind
AggregatePayloadKind picks the most restrictive kind from reports. Default is PayloadSafeUserText when no report sets a non-zero kind.
func UserTextClassifier ¶ added in v0.13.0
func UserTextClassifier(value any) (PayloadKind, error)
UserTextClassifier is an opt-in shape recipe, not a proof of serialized safety. Text/bytes (including named types without custom marshalers) are checked for JSON object/array syntax. Maps/slices/arrays/structs are technical. Pointer and interface dereference is bounded to 64 steps. Nil typed pointers use their underlying type; nil interface, unsupported scalars and custom marshalers fault. json.RawMessage is supported explicitly; arbitrary MarshalJSON/MarshalText is never invoked. The host must deliver the checked representation unchanged.
func (PayloadKind) String ¶ added in v0.9.0
func (k PayloadKind) String() string
String returns a stable name for telemetry.
type Pipeline ¶
type Pipeline[T any] struct { // contains filtered or unexported fields }
Pipeline orchestrates the execution of multiple Validators.
THREAD SAFETY: A Pipeline is safe for concurrent use only when its validators, middleware, observers, scopes and caller-owned aliases are concurrency-safe. Parallel validators must not mutate input aliases. Configuration lists are immutable; objects/providers referenced by those lists remain caller-owned. Configuration method Use returns a new instance and never mutates the original pipeline.
func MustNewPipeline ¶ added in v0.13.0
func MustNewPipeline[T any](opts ...PipelineOption[T]) *Pipeline[T]
MustNewPipeline builds a pipeline or panics on NewPipeline's configuration error.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/guardy"
"github.com/skosovsky/guardy/ext"
)
func main() {
regexV, _ := ext.NewRegexValidator(`(?i)(ignore previous|system prompt)`, ext.WithCode("PROMPT_INJECTION"))
lengthV := ext.MustLengthValidator(0, 10000, ext.WithCode("TOO_LONG"))
pipeline := guardy.MustNewPipeline(
guardy.WithSequential(regexV, lengthV),
)
ctx := context.Background()
result, err := pipeline.Run(ctx, nil, "Hello, what is the weather?")
if err != nil {
panic(err)
}
decision := result.PolicyDecision()
switch {
case decision.IsTerminal():
// handle block
case decision.IsRetryable():
_ = decision.RetryFeedback
default:
_ = result.Output
}
fmt.Println("configured")
}
Output: configured
func NewPipeline ¶
func NewPipeline[T any](opts ...PipelineOption[T]) (*Pipeline[T], error)
NewPipeline builds a pipeline, rejecting invalid configuration before Run. Options and RequiredScope callbacks are trusted construction code; panics escape.
func (*Pipeline[T]) GuardDelivery ¶ added in v0.11.0
func (p *Pipeline[T]) GuardDelivery( ctx context.Context, scope ExecutionScope, policy DeliveryPolicy, output T, ) (GuardedDelivery[T], error)
GuardDelivery runs the pipeline and applies a channel-aware delivery policy.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/guardy"
)
func main() {
outputPipeline := guardy.MustNewPipeline[string]()
guarded, _ := outputPipeline.GuardDelivery(
context.Background(),
nil,
guardy.NewUserTextPolicy("external", guardy.WithDeliveryFallback("Blocked.")),
`{"internal":true}`,
)
value, ok := guarded.DeliverableValue()
fmt.Println(value, ok)
fmt.Println(guarded.Kind)
fmt.Println(guarded.Fallback)
}
Output: Blocked. true safe_user_text true
func (*Pipeline[T]) GuardOutput ¶ added in v0.10.0
func (p *Pipeline[T]) GuardOutput(ctx context.Context, scope ExecutionScope, output T) (GuardedDelivery[T], error)
GuardOutput applies the explicit user-text recipe and returns GuardedDelivery. Use GuardDelivery with a caller classifier for other wire representations.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/guardy"
)
func main() {
outputPipeline := guardy.MustNewPipeline(guardy.WithSequential(guardy.ValidatorFunc[string](
func(_ context.Context, input string) (string, *guardy.Report, error) {
return input, guardy.FinishReport(&guardy.Report{
Action: guardy.ActionPass,
Validator: "classifier",
PayloadKind: guardy.PayloadSafeUserText,
}, guardy.ControlSpec{Action: guardy.ActionPass}), nil
},
)))
guarded, err := outputPipeline.GuardOutput(context.Background(), nil, "hello")
if err != nil {
panic(err)
}
value, ok := guarded.DeliverableValue()
fmt.Println(value, ok)
fmt.Println(guarded.Decision.Action)
}
Output: hello true pass
func (*Pipeline[T]) MustUse ¶ added in v0.13.0
func (p *Pipeline[T]) MustUse(mw ...ValidatorMiddleware[T]) *Pipeline[T]
MustUse appends middleware or panics on the same configuration error as Use.
func (*Pipeline[T]) RequiredScope ¶ added in v0.10.0
func (p *Pipeline[T]) RequiredScope() []ScopeRequirement
RequiredScope returns typed scope requirements compiled at pipeline construction.
func (*Pipeline[T]) RequiredScopeKeys ¶ added in v0.9.0
RequiredScopeKeys returns keys compiled at pipeline construction (immutable after clone).
func (*Pipeline[T]) Run ¶
Run executes the pipeline. Block and Retry short-circuit immediately. scope supplies policy keys; fail-closed when compiled required keys are missing.
Example ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/guardy"
"github.com/skosovsky/guardy/ext"
)
func main() {
wordlistV := ext.MustWordlistValidator([]string{"bad"}, ext.Blocklist, ext.WithCode("FORBIDDEN"))
pipeline := guardy.MustNewPipeline(guardy.WithSequential(wordlistV))
ctx := context.Background()
result, err := pipeline.Run(ctx, nil, "this is bad")
if err != nil {
panic(err)
}
decision := result.PolicyDecision()
if decision.IsTerminal() {
fmt.Println("blocked:", decision.Code)
}
}
Output: blocked: FORBIDDEN
Example (WithScope) ¶
package main
import (
"context"
"fmt"
"github.com/skosovsky/guardy"
)
func main() {
roleKey := guardy.NewScopeKey[string]("principal.role")
pipeline := guardy.MustNewPipeline(
guardy.WithPolicyValidators(guardy.MustTypedAttributeEquals[string, string](
roleKey,
"admin",
guardy.WithPolicyCode(guardy.CodeAttributeMismatch),
)),
)
scope := guardy.NewScope(guardy.ScopeValue(roleKey, "viewer"))
result, err := pipeline.Run(context.Background(), scope, "hello")
if err != nil {
panic(err)
}
if result.PolicyDecision().IsTerminal() {
fmt.Println("denied:", result.PolicyDecision().Disposition)
}
}
Output: denied: terminal_deny
func (*Pipeline[T]) Use ¶ added in v0.5.0
func (p *Pipeline[T]) Use(mw ...ValidatorMiddleware[T]) (*Pipeline[T], error)
Use appends middleware and returns a new immutable pipeline instance. The original pipeline is not modified. Validator/provider objects and their internal state are shared, not cloned; Use does not make them concurrency-safe.
type PipelineOption ¶
PipelineOption configures a Pipeline.
func WithObserver ¶ added in v0.4.0
func WithObserver[T any](o Observer) PipelineOption[T]
WithObserver registers a callback for shadow block reports.
func WithParallel ¶ added in v0.13.0
func WithParallel[T any](v ...Validator[T]) PipelineOption[T]
WithParallel adds validators that run in parallel (read-only, no redact).
func WithPipelineName ¶ added in v0.11.0
func WithPipelineName[T any](name string) PipelineOption[T]
WithPipelineName sets a stable identity included in observer events.
func WithPolicyValidators ¶ added in v0.8.0
func WithPolicyValidators[T any](pv ...PolicyValidator[T]) PipelineOption[T]
WithPolicyValidators adds scope-aware policy validators (sequential, after sequential phase). Required scope is compiled once at pipeline construction; Pipeline.Run fails closed when keys are missing.
func WithSequential ¶ added in v0.13.0
func WithSequential[T any](v ...Validator[T]) PipelineOption[T]
WithSequential adds validators that run sequentially and may return redact.
func WithUserChannel ¶ added in v0.9.0
func WithUserChannel[T any]() PipelineOption[T]
WithUserChannel enables terminal filtering: non-safe PayloadKind becomes ActionBlock.
func WithUserChannelFallback ¶ added in v0.9.0
func WithUserChannelFallback[T any](msg string) PipelineOption[T]
WithUserChannelFallback sets the SafeUserMessage when user channel blocks technical output.
type PolicyConfig ¶ added in v0.8.0
type PolicyConfig struct {
Name string
Code string
Severity Severity
Reason string
Retryable *bool
Fatal bool
SafeUserMessage string
}
PolicyConfig configures built-in policy validators.
type PolicyFailure ¶ added in v0.10.0
PolicyFailure exposes a guardy decision as an error contract. It is available through errors.As from guardy boundary errors.
func (*PolicyFailure) Error ¶ added in v0.10.0
func (e *PolicyFailure) Error() string
Error implements error.
func (*PolicyFailure) Unwrap ¶ added in v0.10.0
func (e *PolicyFailure) Unwrap() error
Unwrap returns the underlying sentinel or validator cause.
type PolicyOption ¶ added in v0.8.0
type PolicyOption func(*PolicyConfig)
PolicyOption configures PolicyConfig.
func WithPolicyCode ¶ added in v0.8.0
func WithPolicyCode(code string) PolicyOption
WithPolicyCode sets the machine-readable code.
func WithPolicyFatal ¶ added in v0.8.0
func WithPolicyFatal(fatal bool) PolicyOption
WithPolicyFatal marks a hard escalation.
func WithPolicyName ¶ added in v0.8.0
func WithPolicyName(name string) PolicyOption
WithPolicyName sets the validator name on policy reports.
func WithPolicyReason ¶ added in v0.8.0
func WithPolicyReason(reason string) PolicyOption
WithPolicyReason sets the report reason.
func WithPolicyRetryable ¶ added in v0.8.0
func WithPolicyRetryable(retryable bool) PolicyOption
WithPolicyRetryable overrides default retryability.
func WithPolicySafeUserMessage ¶ added in v0.8.0
func WithPolicySafeUserMessage(msg string) PolicyOption
WithPolicySafeUserMessage sets an end-user safe message.
func WithPolicySeverity ¶ added in v0.8.0
func WithPolicySeverity(sev Severity) PolicyOption
WithPolicySeverity sets severity.
type PolicyValidator ¶ added in v0.8.0
type PolicyValidator[T any] interface { RequiredScope() []ScopeRequirement Validate(ctx context.Context, input T, scope ExecutionScope) (T, *Report, error) }
PolicyValidator runs context-aware rules using ExecutionScope.
func MustPolicyFuncWithScope ¶ added in v0.13.0
func MustPolicyFuncWithScope[T any]( requirements []ScopeRequirement, fn func(context.Context, T, ExecutionScope) (T, *Report, error), ) PolicyValidator[T]
MustPolicyFuncWithScope builds a policy or panics on its configuration error.
func MustTypedAttributeEquals ¶ added in v0.13.0
func MustTypedAttributeEquals[T any, V comparable](key ScopeKey[V], want V, opts ...PolicyOption) PolicyValidator[T]
MustTypedAttributeEquals builds a policy or panics on its configuration error.
func MustTypedAttributePresent ¶ added in v0.13.0
func MustTypedAttributePresent[T any, V any](key ScopeKey[V], opts ...PolicyOption) PolicyValidator[T]
MustTypedAttributePresent builds a policy or panics on its configuration error.
func NewPolicyFuncWithScope ¶ added in v0.10.0
func NewPolicyFuncWithScope[T any]( requirements []ScopeRequirement, fn func(ctx context.Context, input T, scope ExecutionScope) (T, *Report, error), ) (PolicyValidator[T], error)
NewPolicyFuncWithScope builds a PolicyValidator from typed scope requirements.
func NewTypedAttributeEquals ¶ added in v0.10.0
func NewTypedAttributeEquals[T any, V comparable]( key ScopeKey[V], want V, opts ...PolicyOption, ) (PolicyValidator[T], error)
NewTypedAttributeEquals blocks when typed scope[key] != want using Go == semantics. Dynamically incomparable operands (including interface fields containing slices or maps) return ErrAttributeIncomparable, rather than panic or a policy mismatch.
func NewTypedAttributePresent ¶ added in v0.10.0
func NewTypedAttributePresent[T any, V any](key ScopeKey[V], opts ...PolicyOption) (PolicyValidator[T], error)
NewTypedAttributePresent blocks when a typed scope key is absent or has the wrong type.
func WithStreamingPolicyCapabilities ¶ added in v0.12.0
func WithStreamingPolicyCapabilities(v PolicyValidator[string], capability StreamCapabilities) PolicyValidator[string]
WithStreamingPolicyCapabilities declares stage support for a scoped policy.
type PostBindValidator ¶ added in v0.8.0
PostBindValidator is optional domain validation after JSON unmarshal in ArgsPipeline.Validate. Domain errors request correction; cancellation/deadline errors are system faults. Implement on a pointer receiver, for example:
func (u *User) ValidatePostBind(ctx context.Context) error
type ReleaseError ¶ added in v0.12.0
type ReleaseError struct {
Outcome StreamOutcome
Cause error
Failure PolicyFailure
}
ReleaseError preserves the terminal outcome and canonical guard failure.
func (*ReleaseError) As ¶ added in v0.12.0
func (e *ReleaseError) As(target any) bool
func (*ReleaseError) Error ¶ added in v0.12.0
func (e *ReleaseError) Error() string
func (*ReleaseError) Unwrap ¶ added in v0.12.0
func (e *ReleaseError) Unwrap() error
type ReleaseProfile ¶ added in v0.12.0
type ReleaseProfile string
ReleaseProfile is an explicit promise about when bytes become irreversible.
const ( ReleaseWholeResponse ReleaseProfile = "whole_response" ReleaseValidatedUnits ReleaseProfile = "validated_units" ReleaseBestEffort ReleaseProfile = "best_effort" )
type RemediationPolicy ¶ added in v0.11.0
type RemediationPolicy struct {
RetryAttempt int
MaxRetries int
AllowFallback bool
FallbackMessage string
}
RemediationPolicy supplies host-owned routing limits without making guardy own the workflow that executes the route.
type Report ¶
type Report struct {
Action Action // ActionPass, ActionBlock, ActionRedact, ActionRetry
Validator string // Name of the validator that produced this report
Code string // Machine-readable rule code (for alerting/telemetry)
Severity Severity // Risk level for the report
Reason string // Human-readable reason (internal/operator detail)
Feedback string // Message for LLM retry (when Action == ActionRetry)
Score float64 // Confidence or distance (optional)
ShadowMode bool // If true, block was logged but did not stop the pipeline
MutatedText string // Text after redaction (when Action == ActionRedact); for string T mirrors Output
Retryable bool // Whether a retry may succeed (default true for ActionRetry)
Fatal bool // Hard stop for upstream pipeline; spec alias Escalate
SafeUserMessage string // User-facing message without internal details
Disposition FailureDisposition // Control-flow classification; set by FinishReport
PayloadKind PayloadKind // Optional output classification from validator
}
Report is the single result returned by a validator or the pipeline. It maps to security telemetry attributes and control-flow decisions. Route control flow with IsTerminalDeny() and IsRetryableCorrection() — not Reason string parsing. Action, Code, Retryable, and Fatal remain for telemetry and validator semantics. When Action == ActionRetry, Feedback contains the message for the LLM/orchestrator.
func CompletedReportFromError ¶ added in v0.13.0
CompletedReportFromError projects explicitly attested completed observations through ordinary wrappers and all joined branches. A raw failed report is never consulted. A carrier already includes its nested evidence, so its cause is not walked twice. The result is a fresh snapshot; nil means no attested observation.
func ComposeReports ¶ added in v0.12.0
ComposeReports selects the strongest enforcement and preserves the most restrictive payload classification. It returns a new report without mutating its inputs. Shadow policy blocks remain observations; faults always enforce.
func FinishReport ¶ added in v0.8.0
func FinishReport(rep *Report, spec ControlSpec) *Report
FinishReport applies control-flow defaults and disposition to a manually constructed report.
func WithPayloadKind ¶ added in v0.9.0
func WithPayloadKind(rep *Report, kind PayloadKind) *Report
WithPayloadKind is a helper for validators that classify output.
func (*Report) CloneWithoutState ¶ added in v0.6.0
CloneWithoutState returns a copy without input-specific runtime state.
func (*Report) IsObservation ¶ added in v0.12.0
IsObservation reports whether this is a shadow policy block without a fault or escalation. Retry, fatal and invalid results are never observations.
func (*Report) IsRetryableCorrection ¶ added in v0.9.0
IsRetryableCorrection reports whether the orchestrator should attempt correction.
func (*Report) IsSystemFault ¶ added in v0.9.0
IsSystemFault reports whether the outcome is an infrastructure or validator fault.
func (*Report) IsTerminalDeny ¶ added in v0.9.0
IsTerminalDeny reports whether the outcome is a hard deny.
func (*Report) OrchestratorMessage ¶ added in v0.8.0
OrchestratorMessage returns detailed guidance for LLM retry or internal orchestration.
func (*Report) PublicMessage ¶ added in v0.8.0
PublicMessage returns text safe for external APIs and end users. It never exposes Feedback (use Report.OrchestratorMessage for LLM/orchestrator hints).
type RetryError ¶ added in v0.7.0
type RetryError struct {
Feedback string
Failure PolicyFailure
// contains filtered or unexported fields
}
RetryError carries a retryable policy failure from WrapInput, WrapOutput, or typed argument validation.
func (*RetryError) As ¶ added in v0.10.0
func (e *RetryError) As(target any) bool
As exposes the canonical policy failure contract.
func (*RetryError) Error ¶ added in v0.7.0
func (e *RetryError) Error() string
Error implements error without exposing correction feedback.
func (*RetryError) ReportSnapshot ¶ added in v0.10.0
func (e *RetryError) ReportSnapshot() Report
ReportSnapshot returns a validator report snapshot for telemetry.
func (*RetryError) Unwrap ¶ added in v0.7.0
func (e *RetryError) Unwrap() error
Unwrap returns ErrRetryRequested so errors.Is matches *RetryError when the second argument is ErrRetryRequested.
type RunResult ¶ added in v0.5.0
type RunResult[T any] struct { Output T // Mutated output (after redactions) Reports []Report // All validator reports for telemetry // OutputKind is the most restrictive PayloadKind from all reports (incl. user_channel blocks). OutputKind PayloadKind }
RunResult holds the output and all reports from Pipeline.Run.
func (*RunResult[T]) Decision ¶ added in v0.5.0
Decision returns the report that determines the pipeline outcome. Priority: system fault > terminal deny > retryable correction > redact > pass. Shadow block reports are observations and never select an enforcement decision. Reports order is nondeterministic in parallel phase; must scan entire slice.
func (*RunResult[T]) PolicyDecision ¶ added in v0.10.0
PolicyDecision returns the canonical decision for a run result.
type ScopeBinding ¶ added in v0.10.0
type ScopeBinding struct {
// contains filtered or unexported fields
}
ScopeBinding carries one typed scope value for NewScope.
func ScopeValue ¶ added in v0.10.0
func ScopeValue[T any](key ScopeKey[T], value T) ScopeBinding
ScopeValue binds a typed scope key to a value without exposing map keys in host code.
type ScopeFactory ¶ added in v0.12.0
type ScopeFactory func(context.Context) (ExecutionScope, error)
ScopeFactory constructs current request-local policy facts at every invocation, including host-controlled resume. Output wrappers call it after the handler succeeds; input/argument wrappers call it before validation. The host owns a coherent snapshot and revalidation at execution time. Transient facts are borrowed values; a fresh factory call does not deep-copy aliases or provide atomic authorization. Nil means an empty scope, not a cached verdict.
Example (PolicyFacts) ¶
package main
import (
"context"
"fmt"
"strings"
g "github.com/skosovsky/guardy"
)
// These types belong to the caller. Guardy has no trust taxonomy or provenance store.
type boundaryFacts struct {
Sources []string
ConfirmedTrust string
Classification string
Destination string
Transformation string
Contract string
PolicyIdentity string
}
type documentClaims struct {
ClaimedTrust string
Content string
}
func main() {
ctx := context.Background()
factsKey := g.NewScopeKey[boundaryFacts]("policy.facts")
policy := g.MustPolicyFuncWithScope(
[]g.ScopeRequirement{factsKey.Requirement()},
func(_ context.Context, s string, scope g.ExecutionScope) (string, *g.Report, error) {
facts, _ := factsKey.Lookup(scope)
if facts.Contract != "source-destination" {
return s, &g.Report{
Action: g.ActionBlock,
Disposition: g.DispositionSystemFault,
Code: "METADATA_CONTRACT_INCOMPATIBLE",
}, nil
}
if len(facts.Sources) == 0 || facts.Destination == "" || facts.PolicyIdentity == "" {
return s, &g.Report{Action: g.ActionBlock, Code: "MISSING_POLICY_FACT"}, nil
}
// Caller explicitly permits redaction for this destination. There is no
// implicit declassification and validation does not authorize an action.
if facts.Destination == "external" && facts.Classification == "private" {
return strings.ReplaceAll(s, "secret", "[redacted]"), &g.Report{Action: g.ActionRedact}, nil
}
return s, &g.Report{Action: g.ActionPass}, nil
},
)
p := g.MustNewPipeline(g.WithPolicyValidators(policy))
claims := documentClaims{ClaimedTrust: "trusted", Content: "summary: secret"}
// Projection comes from host evidence, never from documentClaims. Summarizing
// changes transformation identity, but keeps the source and confirmed trust.
facts := boundaryFacts{
Sources: []string{"source:document"},
ConfirmedTrust: "untrusted",
Classification: "private",
Destination: "external",
Transformation: "summary",
Contract: "source-destination",
PolicyIdentity: "host-policy",
}
factory := g.ScopeFactory(
func(context.Context) (g.ExecutionScope, error) { return g.NewScope(g.ScopeValue(factsKey, facts)), nil },
)
scope, _ := factory(ctx)
delivery, err := p.GuardDelivery(ctx, scope, g.NewUserTextPolicy("external"), claims.Content)
projection, allowed := delivery.Projection()
fmt.Println(projection.Value, allowed, err == nil)
fmt.Println(facts.Sources[0], facts.ConfirmedTrust)
fmt.Println(claims.ClaimedTrust != facts.ConfirmedTrust)
// Each additional consumer needs its own destination facts and policy check.
facts.Destination = ""
scope, _ = factory(ctx)
blocked, err := p.GuardDelivery(ctx, scope, g.NewUserTextPolicy("external"), claims.Content)
fmt.Println(blocked.Deliverable, err != nil)
}
Output: summary: [redacted] true true source:document untrusted true false true
type ScopeFunc ¶ added in v0.10.0
ScopeFunc adapts a function to ExecutionScope.
type ScopeIncompleteError ¶ added in v0.10.0
type ScopeIncompleteError struct {
Missing []string
MissingRequirements []ScopeRequirement
}
ScopeIncompleteError carries machine-readable missing scope metadata.
func (*ScopeIncompleteError) Error ¶ added in v0.10.0
func (e *ScopeIncompleteError) Error() string
Error implements error.
func (*ScopeIncompleteError) Unwrap ¶ added in v0.10.0
func (e *ScopeIncompleteError) Unwrap() error
Unwrap returns ErrScopeIncomplete so errors.Is keeps working.
type ScopeKey ¶ added in v0.10.0
type ScopeKey[T any] struct { // contains filtered or unexported fields }
ScopeKey names a typed scope value without making guardy own the host type.
Example (SourceTransformArgumentsDestination) ¶
result, err := executeRecipe(
context.Background(),
documentClaims{ClaimedTrust: "trusted", Content: "secret"},
defaultRecipeFacts(),
)
fmt.Println(err == nil, result.Calls, result.Projection.Value)
fmt.Println(result.Facts.ConfirmedTrust, result.Facts.Transformation, len(result.Facts.Sources))
fmt.Println(result.Evidence.Code, result.Evidence.Sources)
Output: true 1 summary: [redacted] untrusted summary 3 HOST_POLICY_CHECKED [src:document src:attachment]
func NewScopeKey ¶ added in v0.10.0
NewScopeKey creates a typed scope key. The name is the stable boundary identifier; T is the expected host value type.
func (ScopeKey[T]) Lookup ¶ added in v0.10.0
func (k ScopeKey[T]) Lookup(scope ExecutionScope) (T, bool)
Lookup reads and type-checks the key from scope.
func (ScopeKey[T]) Requirement ¶ added in v0.10.0
func (k ScopeKey[T]) Requirement() ScopeRequirement
Requirement returns the typed requirement declared by this key. Prechecks use the same type assertion contract as Lookup: concrete types must match exactly, while concrete implementations satisfy interface keys.
type ScopeRequirement ¶ added in v0.10.0
ScopeRequirement describes a typed value required by a pipeline.
func MissingScopeRequirements ¶ added in v0.10.0
func MissingScopeRequirements(err error) []ScopeRequirement
MissingScopeRequirements extracts missing typed scope requirements from an error.
type ScopeTypeError ¶ added in v0.12.0
type ScopeTypeError struct{ Requirement ScopeRequirement }
ScopeTypeError reports the required contract without exposing the supplied value.
func (*ScopeTypeError) Error ¶ added in v0.12.0
func (e *ScopeTypeError) Error() string
func (*ScopeTypeError) Unwrap ¶ added in v0.12.0
func (e *ScopeTypeError) Unwrap() error
type SemanticValidator ¶ added in v0.4.0
type SemanticValidator struct {
// contains filtered or unexported fields
}
SemanticValidator is a Parallel validator that blocks when score exceeds threshold.
func MustSemanticValidator ¶ added in v0.13.0
func MustSemanticValidator(m Matcher, threshold float64, shadow bool) *SemanticValidator
MustSemanticValidator panics when NewSemanticValidator rejects configuration.
func NewSemanticValidator ¶ added in v0.4.0
func NewSemanticValidator(m Matcher, threshold float64, shadow bool) (*SemanticValidator, error)
NewSemanticValidator builds a validator that blocks when m.Match returns score > threshold. If shadow is true, block reports are marked ShadowMode so the pipeline does not short-circuit. Construction rejects non-finite thresholds; Validate rejects non-finite scores. The matcher defines its own finite score range. Pass/block reports preserve the score for caller calibration; it is not a probability or an estimate of detector accuracy.
type Severity ¶ added in v0.6.0
type Severity string
Severity describes risk/importance of a rule hit. It is string-based for interoperability while still supporting typed constants.
type ShapeProvider ¶ added in v0.10.0
ShapeProvider exposes optional schema or shape metadata without tying guardy to a concrete generator.
type ShapeProviderFunc ¶ added in v0.10.0
ShapeProviderFunc adapts a function to ShapeProvider.
func (ShapeProviderFunc[T]) Shape ¶ added in v0.10.0
func (f ShapeProviderFunc[T]) Shape() any
Shape implements ShapeProvider.
type StaticScope ¶ added in v0.10.0
type StaticScope struct {
// contains filtered or unexported fields
}
StaticScope owns an immutable key map built from typed bindings. Bound values are borrowed: maps, slices and pointers retain their aliases and are not frozen. Keep reachable values immutable while the scope is shared; publish a fresh scope for updated facts. NewScope is not a recursive snapshot.
func NewScope ¶ added in v0.10.0
func NewScope(bindings ...ScopeBinding) StaticScope
NewScope creates an ExecutionScope from typed scope bindings.
func (StaticScope) Lookup ¶ added in v0.10.0
func (s StaticScope) Lookup(key string) (any, bool)
Lookup implements ExecutionScope.
type StreamCapabilities ¶ added in v0.12.0
StreamCapabilities declares rule requirements, not a proof of detector quality. The initial unit splitter supports unit-local rules (zero lookbehind/lookahead).
type StreamCategory ¶ added in v0.12.0
type StreamCategory string
StreamCategory is independent of the downstream transport's error text.
const ( StreamSuccess StreamCategory = "success" StreamIncomplete StreamCategory = "incomplete_unit" StreamMalformed StreamCategory = "malformed_unit" StreamLimit StreamCategory = "buffer_limit" StreamTimeout StreamCategory = "validation_timeout" StreamFault StreamCategory = "validator_fault" StreamUnsupported StreamCategory = "unsupported_release_profile" StreamBlocked StreamCategory = "blocked_delivery" StreamTransport StreamCategory = "delivery_failure" )
type StreamConfig ¶ added in v0.12.0
type StreamConfig struct {
Identity string
Profile ReleaseProfile
JSONValues bool // Unit mode frames objects/arrays; whole-response accepts any valid JSON value.
Pipeline *Pipeline[string]
ScopeFactory ScopeFactory
Delivery DeliveryPolicy
MaxInputBytes int64
MaxPendingBytes int
MaxUnitBytes int // Input bound for all profiles; also transformed/fallback output bound for unit/partial release.
MaxOutputBytes int64
ValidationTimeout time.Duration
Observer func(StreamEvent)
}
StreamConfig owns bounded release configuration; all limits count bytes and must be positive. Policy and pipeline remain immutable after compilation. Newline delimiters count toward MaxUnitBytes. An exact-limit unterminated tail waits for Complete; any following byte overflows before appending that byte. Input admission checks each Write atomically against MaxInputBytes. Partition independence applies to admissible input; overbudget partitions may have different irreversible prefixes already delivered by earlier calls.
type StreamEvent ¶ added in v0.12.0
type StreamEvent struct {
Outcome StreamOutcome
Stage StreamStage
}
StreamEvent intentionally has no raw payload or reports. Observers must not reenter.
type StreamOutcome ¶ added in v0.12.0
type StreamOutcome struct {
Identity string
Category StreamCategory
Decision Decision
Sequence uint64
ReleasedBytes int64
ReceivedBytes int64
PeakPendingBytes int
Terminal bool
Fallback bool
}
StreamOutcome is a snapshot. ReleasedBytes measures actual transport writes; Sequence numbers approved attempts, not a claim that failed writes were complete. PeakPendingBytes counts the maximum retained ring allocation, including unused capacity.
type StreamProcessor ¶ added in v0.12.0
type StreamProcessor struct {
// contains filtered or unexported fields
}
StreamProcessor serializes all operations. A trusted Complete is required; Close aborts unfinished input. Processor owns pending bytes; caller owns transport. Scope factory, validators, writer and observer run under the mutex. They must return and must not reenter this processor. Cancellation is cooperative; Abort, Outcome and later calls can wait for a blocked callback to return.
func CompileStream ¶ added in v0.12.0
func CompileStream(writer io.Writer, cfg StreamConfig) (*StreamProcessor, error)
CompileStream fails before delivery for unsupported profiles/capabilities. Whole-response accepts ordinary final-value validators. Unit and incremental rules must explicitly declare their stage. No downgrade is performed.
Example ¶
package main
import (
"context"
"fmt"
"strings"
"time"
"github.com/skosovsky/guardy"
)
func main() {
v := &examplePassValidator{}
pipeline := guardy.MustNewPipeline(guardy.WithSequential(v))
var out strings.Builder
gw, err := guardy.CompileStream(&out, guardy.StreamConfig{
Identity: "response", Profile: guardy.ReleaseWholeResponse, Pipeline: pipeline,
Delivery: guardy.NewUserTextPolicy("external"), MaxInputBytes: 4096,
MaxPendingBytes: 4096, MaxUnitBytes: 4096, MaxOutputBytes: 4096, ValidationTimeout: time.Second,
})
if err != nil {
panic(err)
}
_, _ = gw.Write([]byte("streaming text "))
_, _ = gw.Complete(context.Background())
fmt.Println(out.String())
}
type examplePassValidator struct{}
func (examplePassValidator) Validate(_ context.Context, input string) (string, *guardy.Report, error) {
return input, &guardy.Report{Action: guardy.ActionPass}, nil
}
Output: streaming text
func (*StreamProcessor) Abort ¶ added in v0.12.0
func (s *StreamProcessor) Abort(cause error) (StreamOutcome, error)
Abort discards pending data; it never flushes an incomplete whole response.
func (*StreamProcessor) Close ¶ added in v0.12.0
func (s *StreamProcessor) Close() error
Close marks an unfinished producer as incomplete; use Complete for success.
func (*StreamProcessor) Complete ¶ added in v0.12.0
func (s *StreamProcessor) Complete(ctx context.Context) (StreamOutcome, error)
Complete is a trusted producer success signal. It never derives completion from payload content. Repeated terminal calls return the original outcome.
func (*StreamProcessor) DeliverFallback ¶ added in v0.12.0
func (s *StreamProcessor) DeliverFallback(ctx context.Context) (StreamOutcome, error)
DeliverFallback is a separate, at-most-once checked delivery after policy deny. It cannot turn a validator fault into success. The original outcome remains terminal; the returned outcome records only this additional delivery.
func (*StreamProcessor) Outcome ¶ added in v0.12.0
func (s *StreamProcessor) Outcome() StreamOutcome
Outcome returns a safe snapshot of counters and current/terminal state.
func (*StreamProcessor) Write ¶ added in v0.12.0
func (s *StreamProcessor) Write(p []byte) (int, error)
Write buffers input without exposing a whole-response prefix. Large caller chunks are processed in bounded slices; input size is checked before copying.
func (*StreamProcessor) WriteContext ¶ added in v0.12.0
WriteContext supplies cancellation to all validation triggered by this input.
type StreamStage ¶ added in v0.12.0
type StreamStage string
StreamStage is supplied by trusted processor control, never by input content.
const ( StreamPartial StreamStage = "partial" StreamUnit StreamStage = "unit" StreamFinal StreamStage = "final" )
func StreamValidationStage ¶ added in v0.12.0
func StreamValidationStage(ctx context.Context) StreamStage
StreamValidationStage returns the current trusted validation stage.
type ValidationPhase ¶ added in v0.6.0
type ValidationPhase string
ValidationPhase identifies which pipeline phase is currently executing.
const ( ValidationPhaseSequential ValidationPhase = "sequential" // ValidationPhasePolicy identifies scope-aware policy validators. ValidationPhasePolicy ValidationPhase = "policy" ValidationPhaseParallel ValidationPhase = "parallel" )
Known pipeline phases for telemetry/middleware.
func ValidationPhaseFromContext ¶ added in v0.6.0
func ValidationPhaseFromContext(ctx context.Context) (ValidationPhase, bool)
ValidationPhaseFromContext extracts the current validation phase from context.
type Validator ¶
Validator is the generic contract for validating input of type T. Returns (possibly mutated) input, a Report pointer, and an error for infrastructure failures. Report.Validator should be set by the implementation to identify the validator.
func Map ¶ added in v0.5.0
Map returns a Validator[T] that wraps Validator[U] with extract (getter) and inject (setter). extract and inject must be non-nil (panics if nil). When the inner validator returns ActionRedact, inject is called to apply the mutation to T.
func MapJSONRawMessage ¶ added in v0.8.0
func MapJSONRawMessage[T any]( v Validator[string], extract func(*T) json.RawMessage, inject func(*T, json.RawMessage) *T, ) Validator[T]
MapJSONRawMessage adapts Validator[string] to Validator[T] for a json.RawMessage field on T. Use when T is a struct value (Validator[MyDTO]), not Validator[*MyDTO]. extract and inject must be non-nil (panics if nil). inject must not return nil after ActionRedact. Empty, nil, and exact JSON null literals (not " null " with spaces) skip the inner validator. After ActionRedact, mutated text must be a single JSON document without duplicate keys before inject; otherwise ActionRetry with CodeJSONRedactCorrupted is returned (distinct from CodeJSONInvalid for parse/bind errors).
func WithStreamingCapabilities ¶ added in v0.12.0
func WithStreamingCapabilities(v Validator[string], capability StreamCapabilities) Validator[string]
WithStreamingCapabilities associates a caller-declared capability with a rule. The declaration must reflect the validator's actual contextual requirements.
type ValidatorFaultError ¶ added in v0.9.0
type ValidatorFaultError struct {
Cause error
Failure PolicyFailure
// contains filtered or unexported fields
}
ValidatorFaultError carries system-fault metadata when a validator or pipeline infrastructure fails.
func (*ValidatorFaultError) As ¶ added in v0.10.0
func (e *ValidatorFaultError) As(target any) bool
As exposes the canonical policy failure contract.
func (*ValidatorFaultError) Error ¶ added in v0.9.0
func (e *ValidatorFaultError) Error() string
Error implements error without exposing diagnostic cause text.
func (*ValidatorFaultError) ReportSnapshot ¶ added in v0.10.0
func (e *ValidatorFaultError) ReportSnapshot() Report
ReportSnapshot returns a validator report snapshot for telemetry.
func (*ValidatorFaultError) Unwrap ¶ added in v0.9.0
func (e *ValidatorFaultError) Unwrap() error
Unwrap preserves both the fault category and its original typed cause.
type ValidatorFunc ¶ added in v0.5.0
ValidatorFunc adapts a function to Validator[T] for use in tests and middleware.
type ValidatorMiddleware ¶ added in v0.5.0
ValidatorMiddleware wraps a Validator with cross-cutting logic (metrics, logging). Construction must be deterministic: stream compilation checks the applied wrapper capabilities, including scoped wrappers reconstructed per invocation. Unit/partial streaming requires an explicit declaration on the resulting wrapper.
type ValidatorPanicError ¶ added in v0.13.0
type ValidatorPanicError struct {
// contains filtered or unexported fields
}
ValidatorPanicError is a Validate callback panic. Its default text is safe; trusted diagnostics can explicitly inspect ValidatorPanicError.PanicValue.
func (*ValidatorPanicError) Error ¶ added in v0.13.0
func (e *ValidatorPanicError) Error() string
Error returns a fixed message without formatting caller-controlled panic data.
func (*ValidatorPanicError) PanicValue ¶ added in v0.13.0
func (e *ValidatorPanicError) PanicValue() any
PanicValue returns the original panic value. It may contain sensitive data.
func (*ValidatorPanicError) Unwrap ¶ added in v0.13.0
func (e *ValidatorPanicError) Unwrap() error
Unwrap retains an error-valued panic as its original typed cause.
Source Files
¶
- adapters.go
- args.go
- boundary.go
- codes.go
- completed_observations.go
- configuration.go
- decision.go
- decode.go
- disposition.go
- errors.go
- guarded_output.go
- guardy.go
- http_guard.go
- interceptor.go
- json_args.go
- llm_judge.go
- mapper.go
- observer.go
- payload.go
- phase.go
- pipeline.go
- policy.go
- release.go
- report_control.go
- report_helpers.go
- route.go
- scope.go
- semantic.go
- stream.go
- stream_splitter.go
- validator.go
- validator_panic.go
Directories
¶
| Path | Synopsis |
|---|---|
|
build
module
|
|
|
Package ext provides built-in validators for the guardy pipeline.
|
Package ext provides built-in validators for the guardy pipeline. |
|
guardyotel
module
|
|
|
jsonredact
module
|
|
|
jsonschema
module
|
|
|
Package guardytest provides test helpers for guardy pipelines and validators.
|
Package guardytest provides test helpers for guardy pipelines and validators. |
|
integration
module
|
|
|
downstream
module
|
|
|
internal
|
|
|
jsondoc
Package jsondoc defines the unambiguous JSON decoding contract used by guards.
|
Package jsondoc defines the unambiguous JSON decoding contract used by guards. |