Documentation
¶
Overview ¶
Package shield provides composable AI safety and governance for Go.
Shield models safety through human-centric primitives: Instincts, Awareness, Boundaries, Values, Judgment, and Reflexes, composed into SafetyProfiles.
Index ¶
- Constants
- Variables
- func AppFromContext(ctx context.Context) string
- func TenantFromContext(ctx context.Context) string
- func WithApp(ctx context.Context, appID string) context.Context
- func WithTenant(ctx context.Context, tenantID string) context.Context
- type Config
- type Entity
- type ID
- type Option
- func WithAwareness(names ...string) Option
- func WithBoundaries(names ...string) Option
- func WithConfig(cfg Config) Option
- func WithInstincts(names ...string) Option
- func WithJudgments(names ...string) Option
- func WithProfile(name string) Option
- func WithReflexes(names ...string) Option
- func WithValues(names ...string) Option
- type Options
- type Prefix
Constants ¶
const ( DefaultMaxScanBytes = 1 << 20 DefaultProfileCacheTTL = 30 * time.Second DefaultJudgeTimeout = 5 * time.Second DefaultJudgeConcurrency = 8 )
Defaults for the scan limits.
const Version = "0.1.0"
Version is the current Shield library version.
Variables ¶
var ( // Store errors. ErrNoStore = errors.New("shield: no store configured") ErrStoreClosed = errors.New("shield: store is closed") ErrMigrateFailed = errors.New("shield: migration failed") // Entity not-found errors. ErrScanNotFound = errors.New("shield: scan not found") ErrPolicyNotFound = errors.New("shield: policy not found") ErrInstinctNotFound = errors.New("shield: instinct not found") ErrJudgmentNotFound = errors.New("shield: judgment not found") ErrAwarenessNotFound = errors.New("shield: awareness not found") ErrValueNotFound = errors.New("shield: value not found") ErrReflexNotFound = errors.New("shield: reflex not found") ErrBoundaryNotFound = errors.New("shield: boundary not found") ErrProfileNotFound = errors.New("shield: safety profile not found") ErrPIITokenNotFound = errors.New("shield: pii token not found") ErrComplianceNotFound = errors.New("shield: compliance report not found") // Tenancy errors. ErrTenantRequired = errors.New("shield: tenant is required") ErrTenantMismatch = errors.New("shield: tenant does not match the context tenant") // Duplicate errors. ErrAlreadyExists = errors.New("shield: entity already exists") // Scan errors. ErrInputBlocked = errors.New("shield: input blocked by safety scan") ErrOutputBlocked = errors.New("shield: output blocked by safety scan") // Engine errors. ErrNoProfile = errors.New("shield: no safety profile configured") ErrInvalidConfig = errors.New("shield: invalid configuration") // Evaluation errors. ErrProfileInvalid = errors.New("shield: safety profile is invalid") ErrInputTooLarge = errors.New("shield: input exceeds the scan size limit") ErrInvalidInput = errors.New("shield: invalid scan input") // PII errors. ErrEncryptionKeyMissing = errors.New("shield: pii encryption key not configured") // State errors. ErrInvalidState = errors.New("shield: invalid state transition") )
Sentinel errors for the Shield library.
Functions ¶
func AppFromContext ¶
AppFromContext extracts the app ID from context. Returns empty string if not set.
func TenantFromContext ¶
TenantFromContext extracts the tenant ID from context. Returns empty string if not set.
Types ¶
type Config ¶
type Config struct {
// DefaultProfile is the safety profile to use when none is specified.
DefaultProfile string `json:"default_profile,omitempty"`
// ShutdownTimeout is the maximum time to wait for graceful shutdown.
ShutdownTimeout time.Duration `json:"shutdown_timeout,omitempty"`
// ScanConcurrency controls how many scan operations can run in parallel.
ScanConcurrency int `json:"scan_concurrency,omitempty"`
// EnableShortCircuit allows layers to stop execution when a block decision
// is reached, skipping deeper layers. Enabled by default.
EnableShortCircuit bool `json:"enable_short_circuit,omitempty"`
// MaxScanBytes is the largest text a scan accepts. A longer text fails
// with ErrInputTooLarge before any layer runs. Zero means 1 MiB.
MaxScanBytes int `json:"max_scan_bytes,omitempty"`
// ProfileCacheTTL is how long a compiled safety profile is reused before
// it is loaded again. Zero means 30 seconds; a negative value disables
// the cache, so every scan loads its profile.
ProfileCacheTTL time.Duration `json:"profile_cache_ttl,omitempty"`
// StoreRedacted keeps Result.Redacted on persisted scans. By default the
// stored row drops it.
StoreRedacted bool `json:"store_redacted,omitempty"`
// ModelJudge lets a judgment's model assessor call the judge registered
// with engine.WithJudge. It is off by default, and a decision never
// needs it: the judge can only raise a judgment's risk.
ModelJudge bool `json:"model_judge,omitempty"`
// JudgeTimeout bounds one judge call. Zero means 5 seconds.
JudgeTimeout time.Duration `json:"judge_timeout,omitempty"`
// JudgeConcurrency caps the judge calls in flight across the engine.
// A scan that cannot get a slot before its context or JudgeTimeout ends
// goes without the judge. A judge that ignores its context keeps its
// slot until it returns. Zero means 8.
JudgeConcurrency int `json:"judge_concurrency,omitempty"`
}
Config holds global configuration for the Shield engine.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
type Entity ¶
type Entity struct {
CreatedAt time.Time `json:"created_at" bun:",nullzero,notnull,default:current_timestamp"`
UpdatedAt time.Time `json:"updated_at" bun:",nullzero,notnull,default:current_timestamp"`
}
Entity is the base type embedded by all Shield domain objects. It provides automatic timestamp tracking.
type Option ¶
type Option func(*Options)
Option configures the Shield library at the top level. These options are used when constructing Shield via New().
func WithAwareness ¶
WithAwareness adds inline awareness detector names.
func WithBoundaries ¶
WithBoundaries adds inline boundary names for hard limits.
func WithInstincts ¶
WithInstincts adds inline instinct names for safety evaluation.
func WithJudgments ¶
WithJudgments adds inline judgment names for risk assessment.
func WithProfile ¶
WithProfile sets the default safety profile to resolve from the store.
func WithReflexes ¶
WithReflexes adds inline reflex names for condition→action rules.
func WithValues ¶
WithValues adds inline value names for ethical evaluation.
type Options ¶
type Options struct {
Config Config
Profile string // default safety profile name
Instincts []string // inline instinct names
Awareness []string // inline awareness names
Values []string // inline value names
Boundaries []string // inline boundary names
Judgments []string // inline judgment names
Reflexes []string // inline reflex names
}
Options holds resolved top-level Shield configuration.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package admin validates dashboard operations before touching scoped stores.
|
Package admin validates dashboard operations before touching scoped stores. |
|
Package audithook bridges Shield lifecycle events to an audit trail backend.
|
Package audithook bridges Shield lifecycle events to an audit trail backend. |
|
Package awareness models what an agent pays attention to in content.
|
Package awareness models what an agent pays attention to in content. |
|
perception
Package perception holds the deterministic awareness detectors: personal data, secrets and topics, plus the placeholders that redact what they find.
|
Package perception holds the deterministic awareness detectors: personal data, secrets and topics, plus the placeholders that redact what they find. |
|
Package boundary models hard safety limits that cannot be crossed.
|
Package boundary models hard safety limits that cannot be crossed. |
|
Package compliance provides compliance reporting for regulatory frameworks.
|
Package compliance provides compliance reporting for regulatory frameworks. |
|
Package engine provides the layered safety execution engine.
|
Package engine provides the layered safety execution engine. |
|
Package extension provides the Forge extension adapter for Shield.
|
Package extension provides the Forge extension adapter for Shield. |
|
contract
Package contract registers Shield's authenticated dashboard contract.
|
Package contract registers Shield's authenticated dashboard contract. |
|
Package id defines TypeID-based identity types for all Shield entities.
|
Package id defines TypeID-based identity types for all Shield entities. |
|
Package instinct models hardwired, automatic safety responses.
|
Package instinct models hardwired, automatic safety responses. |
|
detection
Package detection holds the deterministic prompt-injection detectors that instincts run: a pattern corpus grouped into families, heuristics for hidden and encoded text, and canary tokens.
|
Package detection holds the deterministic prompt-injection detectors that instincts run: a pattern corpus grouped into families, heuristics for hidden and encoded text, and canary tokens. |
|
integrations
|
|
|
nexusguard
module
|
|
|
internal
|
|
|
scoring
Package scoring holds the score arithmetic the detectors and engine layers share, so every caller combines independent signals the same way.
|
Package scoring holds the score arithmetic the detectors and engine layers share, so every caller combines independent signals the same way. |
|
shieldtest
Package shieldtest builds the store and context that engine, admin and extension tests share: a migrated in-memory SQLite store and a context carrying a tenant and an app.
|
Package shieldtest builds the store and context that engine, admin and extension tests share: a migrated in-memory SQLite store and a context carrying a tenant and an app. |
|
telemetry
Package telemetry holds the tracing and metric helpers the engine, the plugin registry and the admin service share.
|
Package telemetry holds the tracing and metric helpers the engine, the plugin registry and the admin service share. |
|
textnorm
Package textnorm folds text into one canonical form for pattern matching and maps every folded byte back to the original text, so a detector can match the folded form and still redact the exact original bytes.
|
Package textnorm folds text into one canonical form for pattern matching and maps every folded byte back to the original text, so a detector can match the folded form and still redact the exact original bytes. |
|
Package judgment models the learned ability to assess risk in context.
|
Package judgment models the learned ability to assess risk in context. |
|
Package observability used to hold Shield's metrics plugin.
|
Package observability used to hold Shield's metrics plugin. |
|
Package pii provides PII vault functionality for secure storage and restoration of personally identifiable information.
|
Package pii provides PII vault functionality for secure storage and restoration of personally identifiable information. |
|
Package plugin defines the Shield plugin system with opt-in lifecycle hooks.
|
Package plugin defines the Shield plugin system with opt-in lifecycle hooks. |
|
Package policy provides administrative governance over safety rules.
|
Package policy provides administrative governance over safety rules. |
|
Package presets holds ready-made safety configurations a host seeds for each of its tenants.
|
Package presets holds ready-made safety configurations a host seeds for each of its tenants. |
|
Package profile models a complete safety identity composed from primitives.
|
Package profile models a complete safety identity composed from primitives. |
|
Package redteam holds red-team fixtures for an infra agent.
|
Package redteam holds red-team fixtures for an infra agent. |
|
Package reflex models condition-triggered safety responses.
|
Package reflex models condition-triggered safety responses. |
|
Package scan defines the input/output types and results for safety scans.
|
Package scan defines the input/output types and results for safety scans. |
|
Package store defines the composite store interface for Shield.
|
Package store defines the composite store interface for Shield. |
|
mongo
Package mongo provides a MongoDB implementation of the Shield composite store using grove ORM with index-based migrations.
|
Package mongo provides a MongoDB implementation of the Shield composite store using grove ORM with index-based migrations. |
|
postgres
Package postgres provides a PostgreSQL implementation of the Shield composite store using grove ORM with Go-based migrations.
|
Package postgres provides a PostgreSQL implementation of the Shield composite store using grove ORM with Go-based migrations. |
|
sqlite
Package sqlite provides a SQLite implementation of the Shield composite store using grove ORM with Go-based migrations.
|
Package sqlite provides a SQLite implementation of the Shield composite store using grove ORM with Go-based migrations. |
|
Package values models the moral compass and ethical guidelines of an agent.
|
Package values models the moral compass and ethical guidelines of an agent. |
|
principles
Package principles holds the built-in detectors of the values layer: a curated lexicon for the safety principle (destructive infrastructure commands, the shell ones taken from instinct/detection) and the toxicity principle (abuse and threats aimed at people), and the score that turns pattern matches into a violation score.
|
Package principles holds the built-in detectors of the values layer: a curated lexicon for the safety principle (destructive infrastructure commands, the shell ones taken from instinct/detection) and the toxicity principle (abuse and threats aimed at people), and the score that turns pattern matches into a violation score. |