hooks

package
v0.30.31 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrManagedHookCommandFailed classifies managed execution failures without
	// exposing process errors or output.
	ErrManagedHookCommandFailed = errors.New("managed hook command failed")
	// ErrHookAuditDegraded classifies a required managed-hook audit failure.
	ErrHookAuditDegraded = errors.New("managed hook audit degraded")
)
View Source
var (
	// ErrManagedPolicy identifies a present policy that could not be securely
	// loaded or validated.
	ErrManagedPolicy = errors.New("managed hook policy")
	// ErrManagedPolicyUnsupportedPlatform identifies a platform without a
	// managed-policy trust-boundary implementation.
	ErrManagedPolicyUnsupportedPlatform = errors.New("managed hook policy is unsupported on this platform")
)

AllEvents lists every valid lifecycle event for documentation and validation.

Functions

func DefaultHookAuditPath added in v0.30.31

func DefaultHookAuditPath() (string, error)

DefaultHookAuditPath returns the user-scoped managed hook audit path.

func DefaultHookAuditReadLimit added in v0.30.31

func DefaultHookAuditReadLimit() int

DefaultHookAuditReadLimit returns the operator CLI's default record limit.

func DefaultManagedPolicyPath added in v0.30.31

func DefaultManagedPolicyPath() (string, error)

DefaultManagedPolicyPath returns the fixed platform administrator-policy path.

func DefaultTrustStorePath added in v0.24.0

func DefaultTrustStorePath() string

DefaultTrustStorePath returns the user-scoped hook trust store location.

func MaxHookAuditReadLimit added in v0.30.31

func MaxHookAuditReadLimit() int

MaxHookAuditReadLimit returns the largest accepted operator read limit.

Types

type Event

type Event string

Event is a lifecycle event that can trigger hooks.

const (
	PreEdit             Event = "pre-edit"
	PostEdit            Event = "post-edit"
	PreCommand          Event = "pre-command"
	PostCommand         Event = "post-command"
	PreSession          Event = "pre-session"
	PostSession         Event = "post-session"
	PreCommit           Event = "pre-commit"
	PostCommit          Event = "post-commit"
	OnError             Event = "on-error"
	OnToolCall          Event = "on-tool-call"
	OnPermissionRequest Event = "on-permission-request"

	SessionStart       Event = "session-start"
	SessionEnd         Event = "session-end"
	UserPromptSubmit   Event = "user-prompt-submit"
	Stop               Event = "stop"
	StopFailure        Event = "stop-failure"
	PreToolUse         Event = "pre-tool-use"
	PostToolUse        Event = "post-tool-use"
	PostToolUseFailure Event = "post-tool-use-failure"
	PermissionRequest  Event = "permission-request"
	PermissionDenied   Event = "permission-denied"
	PreCompact         Event = "pre-compact"
	PostCompact        Event = "post-compact"
	SubagentStart      Event = "subagent-start"
	SubagentStop       Event = "subagent-stop"
	WorkflowStart      Event = "workflow-start"
	WorkflowStop       Event = "workflow-stop"
	WorkflowFailure    Event = "workflow-failure"
	Notification       Event = "notification"
	ConfigChange       Event = "config-change"
	FileChanged        Event = "file-changed"

	// Plan lifecycle
	PrePlan  Event = "pre-plan"
	PostPlan Event = "post-plan"

	// Fleet lifecycle
	PreFleet  Event = "pre-fleet"
	PostFleet Event = "post-fleet"

	// Agent lifecycle
	OnAgentSpawn    Event = "on-agent-spawn"
	OnAgentComplete Event = "on-agent-complete"

	// Token and cron events
	OnTokenLimit Event = "on-token-limit"
	OnCronTick   Event = "on-cron-tick"
)

type Hook

type Hook struct {
	Command        string `yaml:"command"`
	CommandWindows string `yaml:"command_windows,omitempty"`
	Glob           string `yaml:"glob,omitempty"`

	Event               Event      `yaml:"-"`
	SourceKind          SourceKind `yaml:"-"`
	SourceID            string     `yaml:"-"`
	SourcePath          string     `yaml:"-"`
	PluginName          string     `yaml:"-"`
	PluginVersion       string     `yaml:"-"`
	Hash                string     `yaml:"-"`
	Trusted             bool       `yaml:"-"`
	Disabled            bool       `yaml:"-"`
	Suppressed          bool       `yaml:"-"`
	UnsupportedPlatform bool       `yaml:"-"`
}

Hook defines a single hook command with an optional glob pattern.

func (Hook) DescriptorHash added in v0.24.0

func (h Hook) DescriptorHash() string

DescriptorHash returns a stable hash for trust decisions. It intentionally excludes SourcePath so trust can move across checkouts and machines.

type HookAudit added in v0.30.31

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

HookAudit stores managed hook metadata as owner-only JSONL.

func NewHookAudit added in v0.30.31

func NewHookAudit(path string) *HookAudit

NewHookAudit creates a managed hook audit at path.

func (*HookAudit) Append added in v0.30.31

func (a *HookAudit) Append(record HookAuditRecord) (err error)

Append validates, appends, and syncs the requested record plus any pending degradation marker.

func (*HookAudit) Path added in v0.30.31

func (a *HookAudit) Path() string

Path returns the configured JSONL path.

func (*HookAudit) Read added in v0.30.31

func (a *HookAudit) Read(limit int) (records []HookAuditRecord, err error)

Read returns at most limit committed records, newest first. A final record without a newline is treated as torn and ignored; malformed committed lines fail the read.

type HookAuditRecord added in v0.30.31

type HookAuditRecord struct {
	Timestamp  time.Time       `json:"timestamp"`
	Event      Event           `json:"event"`
	Hash       string          `json:"hash"`
	Source     SourceKind      `json:"source"`
	Result     HookAuditResult `json:"result"`
	DurationMS int64           `json:"duration_ms"`
}

HookAuditRecord intentionally contains no executable, payload, output, or error text.

type HookAuditResult added in v0.30.31

type HookAuditResult string

HookAuditResult is a metadata-only managed hook execution classification.

const (
	HookAuditStarted       HookAuditResult = "started"
	HookAuditSuccess       HookAuditResult = "success"
	HookAuditCommandFailed HookAuditResult = "command_failed"
	HookAuditDegraded      HookAuditResult = "audit_degraded"
)

type HookAuditWriter added in v0.30.31

type HookAuditWriter interface {
	Append(HookAuditRecord) error
}

HookAuditWriter is the durable append boundary required before managed hook process launch.

type HookConfig

type HookConfig struct {
	Hooks map[Event][]Hook `yaml:"hooks"`
}

HookConfig holds the full hooks configuration.

func Load

func Load(workingDir string) (*HookConfig, error)

Load reads hook configs from ~/.ratchet/hooks.yaml and .ratchet/hooks.yaml. Project-level hooks (.ratchet/hooks.yaml) override global ones.

func LoadWithOptions added in v0.24.0

func LoadWithOptions(opts LoadOptions) (*HookConfig, error)

LoadWithOptions reads hook configs and annotates each hook with source and trust metadata. User hooks remain trusted by default for compatibility.

func (*HookConfig) AnnotateSource added in v0.24.0

func (hc *HookConfig) AnnotateSource(meta SourceMetadata)

AnnotateSource applies stable source and trust metadata to every hook.

func (*HookConfig) ApplyManagedPolicy added in v0.30.31

func (hc *HookConfig) ApplyManagedPolicy(policy *ManagedPolicy)

ApplyManagedPolicy installs the current managed hooks after all local sources are assembled, preserving local hooks for diagnostics and applying mode last.

func (*HookConfig) ApplyTrust added in v0.24.0

func (hc *HookConfig) ApplyTrust(store *TrustStore)

ApplyTrust refreshes hook hashes and trust decisions against the supplied store. This lets long-running daemons observe trust changes without restart.

func (*HookConfig) Run

func (hc *HookConfig) Run(event Event, data map[string]string) error

Run executes all hooks for the given event, expanding templates with data. data keys include: "file", "command", "error", "tool", "session_id", "plan_id", "fleet_id", "agent_name", "agent_role", "cron_id", "tokens_used", "tokens_limit"

func (*HookConfig) RunWithOptions added in v0.30.31

func (hc *HookConfig) RunWithOptions(event Event, data map[string]string, opts RunOptions) error

RunWithOptions executes eligible hooks and durably audits managed hooks.

type LoadOptions added in v0.24.0

type LoadOptions struct {
	WorkingDir  string
	TrustStore  *TrustStore
	SkipUser    bool
	SkipProject bool
	ManagedPath string

	// ManagedReadFile is a test seam. Production callers must leave it nil so
	// administrator policy always passes through the platform secure reader.
	ManagedReadFile func(string) ([]byte, error)
}

LoadOptions controls hook loading and trust annotation.

type ManagedMode added in v0.30.31

type ManagedMode string

ManagedMode controls whether local hook sources may execute alongside administrator-managed hooks.

const (
	ManagedModeAdditive ManagedMode = "additive"
	ManagedModeOnly     ManagedMode = "managed-only"
)

type ManagedPolicy added in v0.30.31

type ManagedPolicy struct {
	Mode  ManagedMode `yaml:"mode"`
	Hooks HookConfig  `yaml:",inline"`
}

ManagedPolicy is the administrator-owned hook policy document.

func LoadManagedPolicy added in v0.30.31

func LoadManagedPolicy(opts LoadOptions) (*ManagedPolicy, error)

LoadManagedPolicy securely reads and validates the administrator-owned policy. A missing file is the normal unmanaged configuration.

type RunOptions added in v0.30.31

type RunOptions struct {
	Audit HookAuditWriter
}

RunOptions supplies execution boundaries for managed hooks.

type SourceKind added in v0.24.0

type SourceKind string

SourceKind identifies where a hook declaration came from.

const (
	SourceUser    SourceKind = "user"
	SourceProject SourceKind = "project"
	SourcePlugin  SourceKind = "plugin"
	SourceManaged SourceKind = "managed"
)

type SourceMetadata added in v0.24.0

type SourceMetadata struct {
	Kind           SourceKind
	ID             string
	Path           string
	PluginName     string
	PluginVersion  string
	TrustByDefault bool
	TrustStore     *TrustStore
}

SourceMetadata describes the source applied to a loaded HookConfig.

type TrustStore added in v0.24.0

type TrustStore struct {
	Trusted  map[string]bool `json:"trusted,omitempty"`
	Disabled map[string]bool `json:"disabled,omitempty"`
	// contains filtered or unexported fields
}

TrustStore persists explicit hook trust and disable decisions by descriptor hash. Disabled hashes always win over trusted hashes.

func LoadTrustStore added in v0.24.0

func LoadTrustStore(path string) (*TrustStore, error)

LoadTrustStore loads hook trust state from path, creating an empty in-memory store when the file does not exist.

func (*TrustStore) Disable added in v0.24.0

func (s *TrustStore) Disable(hash string) error

Disable records hash as disabled and removes any explicit trust.

func (*TrustStore) IsDisabled added in v0.24.0

func (s *TrustStore) IsDisabled(hash string) bool

func (*TrustStore) IsTrusted added in v0.24.0

func (s *TrustStore) IsTrusted(hash string) bool

func (*TrustStore) Trust added in v0.24.0

func (s *TrustStore) Trust(hash string) error

Trust records hash as trusted and removes any disabled marker.

func (*TrustStore) Untrust added in v0.24.0

func (s *TrustStore) Untrust(hash string) error

Untrust removes explicit trust without enabling a disabled hook.

Jump to

Keyboard shortcuts

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