guardy

package module
v0.14.3 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 18 Imported by: 6 modules, 2 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.

README

Guardy

Go reference

Guardy validates, transforms and controls delivery of caller-owned values through Pipeline[T]. It runs sequential transformations, caller policies and parallel read-only checks. Bring your own Go types, facts and detectors. Core supplies no agent runtime, trained model, permissions store or retry scheduler.

Requires Go 1.27.1+. Install core alone:

go get github.com/skosovsky/guardy

Quick Start

This root-only example redacts a value and writes only its approved projection. Static configuration uses MustNewPipeline; dynamic configuration should handle NewPipeline's error during setup.

package main

import (
    "context"
    "fmt"
    "strings"

    "github.com/skosovsky/guardy"
)

func main() {
    redact := guardy.ValidatorFunc[string](func(_ context.Context, value string) (string, *guardy.Report, error) {
        clean := strings.ReplaceAll(value, "[email protected]", "[email]")
        return clean, &guardy.Report{Action: guardy.ActionRedact}, nil
    })
    pipeline := guardy.MustNewPipeline(guardy.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]. This literal replacement is an example transformation, not a general email detector. The executable counterpart and outcome matrix are in consumer_docs_example_test.go.

GuardOutput uses the explicit NewUserTextPolicy("user") recipe. Its bounded shape classifier supports known text representations; it does not certify custom serialization or content provenance. For another destination use GuardDelivery with NewDeliveryPolicy(channel, WithDeliveryAllowedKinds(...), WithDeliveryClassifier(...)). Bind the classifier to the actual host wire format. Unknown kinds and unsupported/cyclic representations fault. Core never invokes arbitrary MarshalJSON/MarshalText to infer approval.

Deliver only DeliveryProjection, not the entire GuardedDelivery, original payload, raw reports or correction feedback. Fallback is a separate checked value, allowed after policy rejection only by an explicit contract; faults cannot activate it. A routing proposal is not delivery approval.

Values, decisions and faults

A validator implements Validate(context.Context, T) (T, *Report, error). Returned T and RunResult.Output are authoritative; MutatedText is only an optional diagnostic mirror. Use Map for a struct field and MapJSONRawMessage for a raw JSON field. Setters must copy reachable aliases before mutation: guardy cannot undo external mutations, tool execution or other host effects.

Report is a validator DTO, retained for third-party integration and telemetry. Decision is canonical control flow. Fault outranks deny, which outranks correction. Fatal escalation cannot be hidden by redaction or nonfatal shadow observation. Route with PolicyDecision/PolicyFailure.Decision, not Reason, Code text or locally re-derived report flags. FinishReport applies construction defaults; a raw ActionRetry without explicit retryability is a terminal deny.

Low-level callers must handle both fault channels before using output:

result, err := pipeline.Run(ctx, scope, input)
if err != nil {
    return err // Validate error/panic, cancellation or prerequisite failure
}
decision := result.PolicyDecision()
switch {
case decision.IsSystemFault():
    return errors.New("validation fault") // a report-only fault can have nil err
case decision.IsTerminal():
    return errors.New("blocked")
case decision.IsRetryable():
    return errors.New("correction required")
default:
    consume(result.Output) // host owns destination approval for this low-level use
}

High-level argument, delivery and stream boundaries suppress fault output and expose PolicyFailure through errors.As. Inspect ValidatorFaultError, ValidatorPanicError, CompletedObservationsError and their causes only in trusted operator diagnostics. Default public errors omit raw causes and retry feedback. WithCompletedObservations attests only earlier finished checks; arbitrary reports beside errors are discarded. See CONTRACTS.md.

Pipeline, typed facts and ownership

Phases run sequential → policy → parallel. WithSequential callbacks transform values in order; WithPolicyValidators use typed host facts; WithParallel checks must be read-only. Equal-priority parallel diagnostics may vary; canonical outcome priority remains fixed. Validate panics become safe faults in every phase. Construction, observers and host callbacks outside Validate must not panic.

NewPipeline and Pipeline.Use return (pipeline, error) and reject invalid configuration before processing. MustNewPipeline/MustUse are static wrappers. Nil rules/options/middleware/wrapper layers are errors; WithObserver(nil) explicitly disables observation. Use copies registration slices and shares rule/provider objects.

Declare requirements with ScopeKey[T].Requirement() and supply an ExecutionScope through NewScope(ScopeValue(key, value)) or your own Lookup implementation. Concrete prerequisites require exact dynamic types; interface keys accept implementing types. A nil interface cannot satisfy a typed key. Name-only declarations check presence. Missing/incompatible prerequisites fail before sequential callbacks.

ScopeFactory resolves fresh caller facts at each adapter invocation; output adapters resolve them after a successful handler. Facts are transient borrowed values. Build policy operands, nested scope values and callback/provider objects must stay immutable or have caller synchronization. Publish a fresh pipeline and matching facts as one version for reload; do not mutate retained aliases. The executable atomic reload recipe is in build/ownership_test.go. Fact lookup does not atomically authorize execution or bind an approval.

Identity, source references, confirmed trust, confidentiality, destination and policy identity are separate host facts. Untrusted claims do not upgrade trust; summaries and subagent outputs retain source restrictions. After a pause, refresh facts and revalidate exact canonical arguments. Approval, scheduling, retry counters, rollback, declassification, persistence and vault lifetime remain host-owned. See integration/context_policy_reference_test.go for actual argument/handler/context/persistence/export/delivery fixtures.

Adapters and declared configuration

  • WrapInput checks before execution; WrapGuardedOutput checks the result and supplies a guarded projection. Handler errors suppress partial results. Neither wrapper retries or undoes side effects. WrapOutput is low-level: it returns an unvalidated partial result alongside a handler error; never deliver that value.
  • CompileArgs[T] and CompileJSONArgs produce typed/dynamic canonical argument boundaries. Dispatch approved sanitized arguments, not a local re-decode of raw input. Final guards check canonical output after mutation; ShapeProvider and JSON metadata describe shapes, not enforcement. See examples/agent_tool_args.
  • Optional build.CompileStringGuard compiles a GuardSpec. JSON-schema injection uses build.WithJSONSchema; it does not put an engine in core.
  • CompileBoundaryProfile records declared coverage only. It cannot inspect or install host wiring. Real handler/sink fixtures prove enforcement.
  • Decision.Route(RemediationPolicy) returns (GuardRoute, error); negative counters reject configuration, zero retries means exhausted. The host schedules retries and separately checks proposed fallback delivery.

Optional downstream composition

The separate integration/downstream module provides real execution binders and a producer text stream consumer. It preserves fault causes and canonical sanitized arguments, checks final tool schema before execution, and gates whole-response delivery on successful producer completion. Core remains independent. See the executable example and semantic fixtures there for outcome mapping, post-handler failures and host-owned token restore.

HTTP

Guard(pipeline, extractor, injector, options...) returns (middleware, error); MustGuard is the static alternative. WithGuardScopeFactory refreshes facts after extraction. WithGuardMaxBodyBytes requires a positive consumed-input cap, default 1 MiB; declared ContentLength cannot bypass it. Exact cap is allowed, excess is 413. Read/extraction and missing scope are 400; deny/correction 422; validation faults, cancellation, pre-handoff body-close and injection errors 500 with safe public text.

Pass restores original bytes, length/header and independent GetBody replay. Redaction sends returned T to the format-aware injector, never MutatedText. PlainTextInjector supports string bodies. Guard closes the consumed original wrapper before replacement; extractors/injectors borrow their replay body and transfer current replacements to Guard. Next borrows the captured handed-off body, closed on return. Callbacks own intermediate replacements they remove; handlers own their replacements. GetBody readers are caller-owned. A late close cannot rewrite an already committed response; this is not a universal socket lifecycle promise. The full ownership table is in CONTRACTS.md. See ExampleGuard and http_guard_ownership_test.go.

Streaming

Use CompileStream(writer, StreamConfig) with explicit profile, framing and positive byte budgets. Complete(ctx) is a trusted final boundary; Close aborts. Whole-response buffers and validates the complete value; unit mode requires declared unit-local rules; best-effort releases bounded UTF-8 chunks and makes no whole-value guarantee. No profile silently downgrades. DeliverFallback performs separate checked delivery, never recursive fallback or masking a fault.

Input/output/pending/unit limits count bytes, including UTF-8 and delimiters. Newline exact-limit tails wait for Complete; an extra byte/newline faults before buffering. Unit JSON requires object/array for original, transformed and fallback values; whole-response JSON accepts one valid value, including scalars. Expanded unit output is bounded by MaxUnitBytes and whole output by MaxOutputBytes. JSON framing whitespace counts toward the preceding unit; pending must exceed unit cap by a byte. Transformed/fallback newline output must remain one self-contained unit.

Pending allocation capacity stays within MaxPendingBytes; PeakPendingBytes measures reserved pending capacity, not all process/validator allocations. Incremental framing avoids repeated prefix scans/tail shifts, excluding caller callbacks, JSON syntax checks and transport work. Partition guarantees apply to admissible inputs. Each Write's input-budget admission is atomic; rejected partitions can have different already delivered prefixes. Released bytes are actual transport bytes; short writes terminate without replay, and earlier prefixes cannot be undone.

Callbacks run under the processor mutex and must return without reentry. Abort, Outcome and subsequent calls can wait for them; context cannot interrupt mutex acquisition or forcibly stop a non-cooperative callback. No detached timeout workers. Use ReleaseError categories and errors.Is for malformed/incomplete/limit/transport faults, not diagnostic strings. See CONTRACTS.md, STREAM_MEASUREMENTS.md, examples/streaming_filter and examples/json_streaming.

Packages and optional installation

Import Purpose
github.com/skosovsky/guardy Core BYOT pipeline, typed facts, argument/delivery/HTTP/stream boundaries
github.com/skosovsky/guardy/ext Built-in matchers, classifier/semantic adapter, vault, MapSlice (root module)
github.com/skosovsky/guardy/guardytest Synthetic outcome, boundary and semantic fixtures (root module)
github.com/skosovsky/guardy/build Declarative compiler, separate module
github.com/skosovsky/guardy/ext/jsonredact Recursive JSON leaf redaction, separate module
github.com/skosovsky/guardy/ext/jsonschema Raw/struct-derived JSON Schema validation, separate module
github.com/skosovsky/guardy/ext/guardyotel OTel middleware, separate module

Install and import only the optional module you use:

go get github.com/skosovsky/guardy/build
go get github.com/skosovsky/guardy/ext/jsonredact
go get github.com/skosovsky/guardy/ext/jsonschema
go get github.com/skosovsky/guardy/ext/guardyotel

For example, a host using optional JSON redaction and schema validation imports:

import (
    "github.com/skosovsky/guardy/ext/jsonredact"
    "github.com/skosovsky/guardy/ext/jsonschema"
)

OTel and declarative hosts import "github.com/skosovsky/guardy/ext/guardyotel" and "github.com/skosovsky/guardy/build" respectively.

The corresponding Go imports are exactly the paths in the table. Core imports none of the optional engines. See ext/jsonschema/UPGRADE.md for pinned exact-number, overflow, dialect and reference upgrade probes.

Detector, vault and telemetry limits

Built-in detector and semantic rule constructors return configuration errors; Must variants serve static setup. Regex/wordlist compile at construction. Set bounded stable WithCode identifiers. PII recognizes a finite set of ASCII email, NANP/+7 phone and Visa/MasterCard shapes; it does not certify mailbox/phone issuance, Luhn validity or global PII coverage. Unsupported formats can contain a supported substring and be only partly redacted. Word boundaries, overlaps and generated replacements follow the explicit matcher contract. TagPattern matches configured text patterns, not arbitrary instruction attacks; TechnicalJSONClassifier is a heuristic with false positives/negatives, not trust evidence.

Caller-supplied synchronous TextClassifier/SemanticDetector callbacks are cooperative. Scores/thresholds must be finite; NaN/infinity/error/cancellation faults even for an alleged pass. MapSlice checks independent items, not relationships across messages; its copy is outer-slice only, so setters must use copy-on-write for reachable aliases. JSONRedact visits sorted object keys and array indices, continues after deny/correction to find stronger outcomes, and stops at fault/cancellation. Mandatory outcomes retain the original document and clear MutatedText.

TokenVault.Store returns (token, error); storage error/panic/empty/identity token faults without degrading to irreversible replacement. A token is a lookup key, not a permission grant. Host owns isolation, lifetime, recipient authorization and a final delivery check after restoration; see examples/reversible_redaction.

Optional guardyotel.NewMiddleware returns (middleware, error) on instrument setup failure, with safe ConfigurationError and inspectable original cause. MustMiddleware is static setup; plain nil Meter/Tracer explicitly disables that channel. Runtime metadata allowlists are opt-in, bounded to 128-byte static identifiers. Raw payload capture is opt-in; raw errors/report text are never exported. Canonical disposition, outcome and execution-fault status do not constitute delivery approval or a full audit ledger. Provider lifecycle is host-owned. See examples/otel_integration.

Deterministic fixtures measure conformance, not detector accuracy. Evaluate fixed model/config/dataset identities, benign/adversarial splits, false positives/negatives, task success, latency and faults separately. There is no live-provider safety claim.

Development, measurements and release

Use golangci-lint 2.14.0; CI pins Go 1.27.2. Make discovers every module with GOWORK=off. Run make lint, make test, make test-integration and make test-e2e sequentially. Unit tests include release protocol fixtures; tagged profiles cover actual boundary composition and isolated artifact consumers. See verification for prerequisites and test selection. A root go test ./... alone excludes nested modules. make bench measures local workloads. Historical wordlist comparison names baseline_a16279e_runtime_compile and v2_precompiled are benchmark identifiers, not a module major version:

go test -bench '^BenchmarkWordlist_Blocklist_Redact_BaselineComparison$' -benchmem ./ext -run '^$'

Results depend on machine/workload and do not measure arbitrary callback latency, semantic accuracy or production throughput. Streaming before/after boundaries and partition/work limitations are recorded in STREAM_MEASUREMENTS.md.

Release uses Bash, Git, Make and Go. make release-patch / make release-break validate the selected source in an isolated checkout, prepare internal manifests, and ask before one atomic push: source to main, candidate to exact module tags. Development replacements remain in main. Recovery uses make release-inspect, make release-resume and make release-finish; no production release is needed to run the fixture tests. See the release runbook.

All API changes and earlier transitions are in MIGRATION.md. This guide describes the current candidate, without claiming it has been published.

License.

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

Examples

Constants

View Source
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).

View Source
const DefaultMaxBodyBytes = 1 << 20

DefaultMaxBodyBytes is the default request body size limit for Guard (1 MiB of consumed input).

Variables

View Source
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")
)
View Source
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")
)
View Source
var ErrAttributeIncomparable = errors.New("guardy: attribute equality requires comparable values")

ErrAttributeIncomparable identifies equality operands that cannot safely use Go ==.

View Source
var ErrBoundaryConfiguration = errors.New("guardy: invalid boundary configuration")

ErrBoundaryConfiguration identifies a rejected mapping/coverage contract.

View Source
var ErrConfiguration = errors.New("guardy: invalid configuration")

ErrConfiguration identifies invalid built-in compilation settings.

View Source
var ErrDeliveryClassification = errors.New("guardy: unsupported delivery representation")

ErrDeliveryClassification identifies unsupported or cyclic representations.

View Source
var ErrScopeIncompatible = errors.New("guardy: incompatible scope value")

ErrScopeIncompatible distinguishes incompatible facts from absent facts.

View Source
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

func MissingScopeKeys(err error) []string

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

func PlainTextInjector() func(*http.Request, string) error

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

func WithCompletedObservations(cause error, completed ...*Report) error

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.

const (
	ActionPass   Action = iota // Validation passed
	ActionBlock                // Content should be blocked
	ActionRedact               // Content was redacted (see MutatedText)
	ActionRetry                // Orchestrator should retry with Feedback (e.g. LLM correction)
)

Supported pipeline/validator actions.

func (Action) String added in v0.5.0

func (a Action) String() string

String returns the canonical name for the action.

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.

const (
	BoundaryInput       Boundary = "input"
	BoundaryArgs        Boundary = "arguments"
	BoundaryResult      Boundary = "handler_result"
	BoundaryContext     Boundary = "context"
	BoundaryPersistence Boundary = "persistence"
	BoundaryExport      Boundary = "export"
	BoundaryDelivery    Boundary = "delivery"
)

type BoundaryConfigurationError added in v0.12.0

type BoundaryConfigurationError struct {
	Boundary Boundary
	Code     string
}

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 (*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

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

type ConfigurationError struct {
	Component string
	Field     string
	Code      string
	Cause     error
}

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

type ControlSpec struct {
	Action          Action
	Retryable       *bool
	Fatal           bool
	SafeUserMessage string
}

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

func DecisionFromReport(rep *Report) Decision

DecisionFromReport converts a validator or pipeline report into the canonical host-facing decision contract.

func (Decision) IsRetryable added in v0.10.0

func (d Decision) IsRetryable() bool

IsRetryable reports whether retrying with a corrected payload may succeed.

func (Decision) IsSystemFault added in v0.10.0

func (d Decision) IsSystemFault() bool

IsSystemFault reports whether the decision came from guardy infrastructure or validator failure.

func (Decision) IsTerminal added in v0.10.0

func (d Decision) IsTerminal() bool

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 (*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

type ExecutionScope interface {
	Lookup(key string) (value any, ok bool)
}

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

type Handler[Req, Res any] func(context.Context, Req) (Res, error)

Handler is a generic host function shape guardy can wrap without owning host types.

type JSONArgsMetadata added in v0.12.0

type JSONArgsMetadata struct {
	ID    string
	Shape any
}

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

type JSONArgsValidator interface {
	ValidateJSONArgs(context.Context, map[string]any) *Report
}

JSONArgsValidator checks decoded objects using caller-owned rules. Metadata is supplied separately through WithJSONArgsMetadata.

type JSONArgsValidatorFunc added in v0.12.0

type JSONArgsValidatorFunc func(context.Context, map[string]any) *Report

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

func (f JSONArgsValidatorFunc) ValidateJSONArgs(ctx context.Context, object map[string]any) *Report

ValidateJSONArgs implements JSONArgsValidator.

type Judge added in v0.4.0

type Judge interface {
	Evaluate(ctx context.Context, text string) (Report, error)
}

Judge evaluates text (e.g. via LLM) and returns a Report.

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

func MustLLMJudge(j Judge, shadow bool) *LLMJudge

MustLLMJudge builds a judge validator or panics on NewLLMJudge's configuration error.

func NewLLMJudge added in v0.4.0

func NewLLMJudge(j Judge, shadow bool) (*LLMJudge, error)

NewLLMJudge builds a validator that calls j.Evaluate. If shadow is true and the judge returns block, the report is marked ShadowMode.

func (*LLMJudge) Validate added in v0.4.0

func (l *LLMJudge) Validate(ctx context.Context, input string) (string, *Report, error)

Validate runs the judge and returns its result. Context is checked before/after the synchronous judge. Cancellation prevents a late report; it cannot terminate a non-cooperative judge or undo its side effects.

type MapScope added in v0.9.0

type MapScope map[string]any

MapScope is a simple in-memory ExecutionScope.

func (MapScope) Lookup added in v0.9.0

func (m MapScope) Lookup(key string) (any, bool)

Lookup implements ExecutionScope.

type Matcher added in v0.4.0

type Matcher interface {
	Match(ctx context.Context, text string) (score float64, err error)
}

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

func (p *Pipeline[T]) RequiredScopeKeys() []string

RequiredScopeKeys returns keys compiled at pipeline construction (immutable after clone).

func (*Pipeline[T]) Run

func (p *Pipeline[T]) Run(ctx context.Context, scope ExecutionScope, input T) (RunResult[T], error)

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

type PipelineOption[T any] func(*Pipeline[T])

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

type PolicyFailure struct {
	Decision Decision
	Cause    error
}

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

type PostBindValidator interface {
	ValidatePostBind(ctx context.Context) error
}

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

func CompletedReportFromError(cause error) *Report

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

func ComposeReports(reports ...*Report) *Report

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) Clone added in v0.6.0

func (r *Report) Clone() *Report

Clone returns a shallow copy of report.

func (*Report) CloneWithoutState added in v0.6.0

func (r *Report) CloneWithoutState() *Report

CloneWithoutState returns a copy without input-specific runtime state.

func (*Report) IsObservation added in v0.12.0

func (r *Report) IsObservation() bool

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

func (r *Report) IsRetryableCorrection() bool

IsRetryableCorrection reports whether the orchestrator should attempt correction.

func (*Report) IsSystemFault added in v0.9.0

func (r *Report) IsSystemFault() bool

IsSystemFault reports whether the outcome is an infrastructure or validator fault.

func (*Report) IsTerminalDeny added in v0.9.0

func (r *Report) IsTerminalDeny() bool

IsTerminalDeny reports whether the outcome is a hard deny.

func (*Report) OrchestratorMessage added in v0.8.0

func (r *Report) OrchestratorMessage() string

OrchestratorMessage returns detailed guidance for LLM retry or internal orchestration.

func (*Report) PublicMessage added in v0.8.0

func (r *Report) PublicMessage() string

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

func (r *RunResult[T]) Decision() *Report

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

func (r *RunResult[T]) PolicyDecision() Decision

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

type ScopeFunc func(key string) (value any, ok bool)

ScopeFunc adapts a function to ExecutionScope.

func (ScopeFunc) Lookup added in v0.10.0

func (f ScopeFunc) Lookup(key string) (any, bool)

Lookup implements 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

func NewScopeKey[T any](name string) ScopeKey[T]

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]) Name added in v0.10.0

func (k ScopeKey[T]) Name() string

Name returns the stable scope key name.

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

type ScopeRequirement struct {
	Key  string
	Type string
	// contains filtered or unexported fields
}

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.

func (*SemanticValidator) Validate added in v0.4.0

func (s *SemanticValidator) Validate(ctx context.Context, input string) (string, *Report, error)

Validate runs the matcher and returns block when score > threshold. It checks context before/after the synchronous matcher; cancellation cannot stop a non-cooperative matcher but prevents its late result from becoming a report.

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.

const (
	SeverityLow      Severity = "low"
	SeverityMedium   Severity = "medium"
	SeverityHigh     Severity = "high"
	SeverityCritical Severity = "critical"
)

Canonical severity values for built-in validators and telemetry.

type ShapeProvider added in v0.10.0

type ShapeProvider[T any] interface {
	Shape() any
}

ShapeProvider exposes optional schema or shape metadata without tying guardy to a concrete generator.

type ShapeProviderFunc added in v0.10.0

type ShapeProviderFunc[T any] func() any

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

type StreamCapabilities struct {
	Partial, Unit, Final  bool
	Lookbehind, Lookahead int
}

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

func (s *StreamProcessor) WriteContext(ctx context.Context, p []byte) (int, error)

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

type Validator[T any] interface {
	Validate(ctx context.Context, input T) (T, *Report, error)
}

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

func Map[T any, U any](v Validator[U], extract func(T) U, inject func(T, U) T) Validator[T]

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

type ValidatorFunc[T any] func(ctx context.Context, input T) (T, *Report, error)

ValidatorFunc adapts a function to Validator[T] for use in tests and middleware.

func (ValidatorFunc[T]) Validate added in v0.5.0

func (f ValidatorFunc[T]) Validate(ctx context.Context, input T) (T, *Report, error)

Validate implements Validator[T].

type ValidatorMiddleware added in v0.5.0

type ValidatorMiddleware[T any] func(next Validator[T]) Validator[T]

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.

Directories

Path Synopsis
build module
ext
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.

Jump to

Keyboard shortcuts

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