Documentation
¶
Index ¶
- Constants
- Variables
- func ContextFacts(ctx context.Context) map[string]string
- func ContextWithLogger(ctx context.Context, l Logger) context.Context
- func GetParentID(ctx context.Context) (string, bool)
- func IsAlignmentError(err error) bool
- func IsInputError(err error) bool
- func IsPolicyViolationError(err error) bool
- func IsSupervisorError(err error) bool
- func WithFact(ctx context.Context, key, value string) context.Context
- func WithParentID(ctx context.Context, id string) context.Context
- type Action
- type ActionEnvelope
- type ActionMetadata
- type AgentMemory
- type AgentMemoryWithFacts
- type AlignmentError
- type Answer
- type Atom
- type AuditRecord
- type AuditTrail
- type Breaker
- type ConfigEvent
- type ContentType
- type ConversationHistory
- type Decision
- type Document
- type EdgeDef
- type Embedder
- type Envelope
- func (e *Envelope) AddLabel(label string)
- func (e *Envelope) GetFeedback() string
- func (e *Envelope) GetMeta(k string) string
- func (e *Envelope) HasLabel(label string) bool
- func (e *Envelope) MergeLabels(other []string)
- func (e *Envelope) SetFeedback(msg string)
- func (e *Envelope) SetHistory(msgs []Message)
- func (e *Envelope) SetMeta(k string, v any)
- type Evaluator
- type ExecutionContext
- type Extractor
- type FactLoader
- type GenerateOption
- type GenerationConfig
- type HistoryStore
- type InputError
- type IntentStr
- type LLMResponse
- type Logger
- type MemoryMode
- type Message
- type Meter
- type NodeDef
- type NodeResult
- type NopEmbedder
- type NopLogger
- type NopSpan
- type NopStore
- type NopTracer
- type NopVectorStore
- type PolicyViolationError
- type PreProcessor
- type Quad
- type Query
- type ResourceMonitor
- type RiskEngine
- type RuleInference
- type RuleSnapshot
- type SessionState
- type Span
- type StateManager
- type StateProvider
- type StreamChunk
- type SupervisorError
- type TextGenerator
- type Tier
- type Tracer
- type ValidationError
- type VectorStore
- type ViolationRule
- type WorkflowDef
- type WorkflowInstance
- func (wi *WorkflowInstance) GetCounter(name string) int
- func (wi *WorkflowInstance) GetVariable(key string) interface{}
- func (wi *WorkflowInstance) IncrementCounter(name string) int
- func (wi *WorkflowInstance) IsNodeCompleted(nodeID string) bool
- func (wi *WorkflowInstance) MarkNodeCompleted(nodeID string)
- func (wi *WorkflowInstance) MarkNodeFailed(nodeID string)
- func (wi *WorkflowInstance) SessionKey() string
- func (wi *WorkflowInstance) SetCurrentNode(nodeID string)
- func (wi *WorkflowInstance) SetVariable(key string, value interface{})
- type WorkflowInstanceStatus
- type WorkflowResult
- type WorkflowStatus
Constants ¶
const ( // Governance & Routing KeyDecision = "manglekit.decision" // Values: "PROCEED", "HALT", "RETRY", "ROUTE" KeyFeedback = "manglekit.feedback" // Human/LLM readable reason KeyPrevFeedback = "prev_feedback" // Loopback for retry KeyNextStep = "manglekit.next_step" // Next action routing // Risk & Analysis KeyRiskScore = "manglekit.risk_score" // 0-100 // Performance & Observability KeyLatencyMs = "manglekit.latency_ms" KeyTraceID = "manglekit.trace_id" KeyModel = "manglekit.model" KeyHistory = "manglekit_history" KeyContext = "manglekit.context" // RAG data injected here KeySummary = "manglekit.summary" // Conversation summary // Configuration PrefixPromptConfig = "prompt." )
Standard Metadata Keys used for Control Plane signaling.
const ( DecisionProceed = "PROCEED" // Formerly "ALLOW" DecisionHalt = "HALT" // Formerly "DENY" DecisionRetry = "RETRY" DecisionRoute = "ROUTE" )
Standard Decision Values
const ( EntityInput = "Req" // ID for Input Envelope EntityOutput = "Output" // ID for Output Envelope PredHalt = "halt" // Was "deny" or "infeasible" PredRetry = "retry" // Correction signal PredRoute = "route" // Dynamic routing signal PredViolation = "violation_msg" // To extract error messages )
Datalog System Constants
const ( // Span Names SpanPreCheck = "Datalog.Assess" // Formerly "Datalog.PreCheck" SpanPostCheck = "Datalog.Reflect" // Formerly "Datalog.PostCheck" SpanMemory = "Mangle.Recall" // RAG lookup // Attribute Keys AttrPolicyName = "policy.name" AttrPolicyType = "policy.type" AttrDecisionType = "decision.type" AttrOutcome = "outcome" // "PROCEED", "HALT" AttrLabels = "mangle.labels" // Taint Propagation AttrActionName = "action.name" AttrActionType = "action.type" AttrRuleID = "mangle.rule_id" // Replaces AttrPolicyRuleID AttrAttempt = "mangle.attempt" // Replaces AttrPolicyAttempt )
Observability & Trace Attributes
const ( OutcomeProceed = DecisionProceed OutcomeHalt = DecisionHalt OutcomeSuccess = "success" )
Outcome Values (for Tracing) - aliases to Decision constants for compatibility
Variables ¶
var ( // ErrAlignment is returned when a blueprint alignment check blocks an action. ErrAlignment = errors.New("alignment error") // ErrSystemError is returned when an unexpected error occurs. ErrSystemError = errors.New("system error") // ErrInputValidation is returned when input conversion or parsing fails. ErrInputValidation = errors.New("input validation error") // ErrPolicyViolation is returned when a supervisor blocks due to policy violation. ErrPolicyViolation = errors.New("policy violation") // ErrSupervisorFailure is returned when the supervisor itself fails. ErrSupervisorFailure = errors.New("supervisor failure") )
Functions ¶
func ContextFacts ¶
ContextFacts retrieves all injected facts from the context.
func ContextWithLogger ¶
ContextWithLogger injects the provided Logger into the context.
func GetParentID ¶
GetParentID retrieves the ID of the parent data from the context.
Parameters:
- ctx: The context to search.
Returns:
- The parent ID string and true if found, or empty string and false if not.
func IsAlignmentError ¶
IsAlignmentError checks if the error is an AlignmentError.
func IsInputError ¶
IsInputError checks if the error is an InputError.
func IsPolicyViolationError ¶
IsPolicyViolationError checks if the error is a PolicyViolationError.
func IsSupervisorError ¶
IsSupervisorError checks if the error is a SupervisorError.
func WithFact ¶
WithFact injects a key-value pair into the context. These facts are automatically extracted by the Reflector and made available to Datalog policies (e.g., user_role, system_mode).
func WithParentID ¶
WithParentID injects the ID of the parent data into the context. This is used to track the genealogy of data as it flows through the system, enabling lineage tracking and debugging.
Parameters:
- ctx: The parent context.
- id: The unique ID of the parent data envelope or span.
Returns:
- A new context containing the parent ID.
Types ¶
type Action ¶
type Action interface {
// Execute performs the action's logic.
Execute(ctx context.Context, input Envelope) (Envelope, error)
// Metadata returns the action's metadata.
Metadata() ActionMetadata
}
Action defines the interface for a unit of work in the Manglekit system.
type ActionEnvelope ¶
type ActionEnvelope struct {
Name string // Action name matching Registry (e.g., "generate_csd")
Arguments map[string]interface{} // Parameters derived from Datalog bindings
SessionID string // Session ID for accessing TransientStore
}
ActionEnvelope contains the action to be executed and its parameters. This decouples Manglekit's logical decisions from their Go implementations.
func NewActionEnvelope ¶
func NewActionEnvelope(name string, args map[string]interface{}) *ActionEnvelope
NewActionEnvelope creates a new ActionEnvelope.
func (*ActionEnvelope) WithSessionID ¶
func (a *ActionEnvelope) WithSessionID(sessionID string) *ActionEnvelope
WithSessionID sets the session ID for the action envelope.
type ActionMetadata ¶
type ActionMetadata struct {
// Name is the unique identifier for the action.
Name string
// Type describes the category of the action.
Type string
// InputContentType specifies the expected input format.
InputContentType ContentType
// InputType is the string name of the Go input type.
InputType string
// OutputType is the string name of the Go output type.
OutputType string
// IsDynamic indicates if the input type is generic.
IsDynamic bool
}
ActionMetadata provides metadata about an action.
type AgentMemory ¶
type AgentMemory interface {
// --- Sequential History ---
// Read retrieves the chat history for a given session.
Read(ctx context.Context, sessionID string) ([]Message, error)
// Append adds new messages to the history.
Append(ctx context.Context, sessionID string, msgs []Message) error
// --- Semantic Memory (RAG) ---
// Recall retrieves relevant context based on the current query.
Recall(ctx context.Context, query string) (string, error)
// Memorize stores a new interaction (Input/Output) for future recall.
Memorize(ctx context.Context, query string, answer string) error
// Init performs any necessary setup (e.g. connecting to DB).
Init(ctx context.Context) error
}
AgentMemory defines the capability to store and retrieve past experiences. It unifies sequential History (chat logs) and Semantic Memory (RAG).
type AgentMemoryWithFacts ¶
type AgentMemoryWithFacts interface {
AgentMemory
// RecallWithFacts retrieves context and associated metadata (e.g. doc IDs).
RecallWithFacts(ctx context.Context, query string) (string, map[string]any, error)
}
AgentMemoryWithFacts is an optional interface for Memory providers that can return additional metadata (facts) along with the text context.
type AlignmentError ¶
AlignmentError is a structured error that carries a specific intervention message. It wraps ErrAlignment to ensure standard error matching works.
func NewAlignmentError ¶
func NewAlignmentError(message, ruleID string) *AlignmentError
NewAlignmentError creates a new AlignmentError with the given message and rule ID.
func (*AlignmentError) Error ¶
func (e *AlignmentError) Error() string
func (*AlignmentError) Is ¶
func (e *AlignmentError) Is(target error) bool
func (*AlignmentError) Unwrap ¶
func (e *AlignmentError) Unwrap() error
type Atom ¶
type Atom struct {
Predicate string `json:"predicate"`
Subject string `json:"subject"`
Object string `json:"object"`
Weight float64 `json:"weight"` // 1.0 (Fact) to 0.1 (Guess)
OriginIntent IntentStr `json:"origin_intent,omitempty"`
}
Atom is the smallest unit of knowledge (Subject-Predicate-Object).
type AuditRecord ¶
type AuditRecord struct {
Step int `json:"step"`
Rules []RuleSnapshot `json:"rules"`
Outcome string `json:"outcome"` // "PROCEED", "HALT", "RETRY", "ROUTE"
Timestamp string `json:"timestamp"`
LatencyMs int64 `json:"latency_ms"`
FactCount int `json:"fact_count"`
MatchedCount int `json:"matched_count"`
}
AuditRecord is a trimmed, serializable snapshot of AuditTrail for persistence. It captures the essential rule attribution data without internal pointers.
func NewAuditRecordFromTrail ¶
func NewAuditRecordFromTrail(trail *AuditTrail, step int, outcome string) AuditRecord
NewAuditRecordFromTrail creates an AuditRecord from an AuditTrail for the given step.
type AuditTrail ¶
type AuditTrail struct {
MatchedRules []RuleInference // The rules that matched and contributed to the decision
Timestamp time.Time // When the decision was made
EngineID string // Identifier for the policy engine instance
Query string // The original query that was evaluated
FactCount int // Number of facts evaluated
MatchedCount int // Number of matching results
LatencyMs int64 // Time taken to evaluate (for performance monitoring)
}
AuditTrail provides detailed explanation of why a decision was made. It captures which Datalog rules were triggered and their source tier.
func NewAuditTrail ¶
func NewAuditTrail(engineID, query string) *AuditTrail
NewAuditTrail creates a new AuditTrail with default values.
func (*AuditTrail) AddRule ¶
func (a *AuditTrail) AddRule(ruleName, definition, sourceFile, predicate string, tier Tier, bindings map[string]string)
AddRule adds a matched rule to the audit trail.
func (*AuditTrail) Summary ¶
func (a *AuditTrail) Summary() string
Summary returns a human-readable summary of the audit trail.
type ConfigEvent ¶
ConfigEvent: For Hot-Swap mechanisms.
type ContentType ¶
type ContentType string
ContentType defines the nature of the data payload.
const ( // TypeStruct indicates the payload is a strong Go struct. // This is the default mode, optimized for internal services. TypeStruct ContentType = "STRUCT" // TypeJSON indicates the payload is a flexible map[string]any. // This is used for AI agents and external webhooks. TypeJSON ContentType = "JSON" )
type ConversationHistory ¶
type ConversationHistory struct {
// Messages is the ordered list of messages in the conversation.
Messages []Message `json:"messages"`
}
ConversationHistory represents a sequence of messages in a dialogue.
type Decision ¶
type Decision struct {
Outcome string // Matches DecisionProceed, DecisionHalt, etc.
Target string // Used if Outcome == DecisionRoute
Reasons []string // Explanations
Meta map[string]string // Side-channel data (risk scores, latency budget)
AuditTrail *AuditTrail // Detailed execution trace
Action *ActionEnvelope // Action to be executed (decoupled from Go implementation)
}
Decision: Structured result from the Policy Engine.
type Document ¶
type Document struct {
ID string `json:"id,omitempty"`
Content string `json:"content"`
Vector []float32 `json:"vector,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Score float32 `json:"score,omitempty"` // Re-ranking score
}
Document represents a snippet of knowledge/memory.
type Embedder ¶
type Embedder interface {
// Embed generates a vector for a single text string.
Embed(ctx context.Context, text string) ([]float32, error)
// EmbedBatch generates vectors for multiple strings.
EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)
// Dimension returns the vector size (e.g., 768 for Google GenAI).
Dimension() int
}
Embedder defines the contract for converting text to vector representations.
type Envelope ¶
type Envelope struct {
// ID is the unique identifier for this specific data envelope.
ID uuid.UUID `json:"id"`
// Payload is the actual data being transported.
// Note: Field name preserved as Payload for compatibility, tagged as "data".
Payload any `json:"data"`
// Metadata stores key-value pairs for control plane signaling.
Metadata map[string]any `json:"metadata,omitempty"`
// Error stores any error encountered during processing.
Error error `json:"error,omitempty"`
// SecurityLabels holds taint tags (e.g., "secret", "pii") for information flow control.
SecurityLabels []string `json:"security_labels,omitempty"`
// Facts holds structured logical facts extracted from the payload.
Facts []string `json:"facts,omitempty"`
// ContentType indicates whether the payload is a Struct or JSON.
ContentType ContentType `json:"content_type,omitempty"`
// ContextFacts contains flattened quad facts for Datalog evaluation.
ContextFacts []Quad `json:"context_facts,omitempty"`
// Violations holds GenePool axiom violations after Shadow Audit.
Violations []ViolationRule `json:"violations,omitempty"`
}
Envelope: The unified data container.
func NewEnvelope ¶
NewEnvelope creates a new envelope with the provided payload.
func (*Envelope) AddLabel ¶
AddLabel adds a security label to the envelope if it does not already exist.
func (*Envelope) GetFeedback ¶
GetFeedback retrieves the feedback for the "Student" (AI/Logic)
func (*Envelope) GetMeta ¶
GetMeta retrieves a value from the envelope's metadata map as a string. If the value is not a string, it returns an empty string (or simple string representation).
func (*Envelope) HasLabel ¶
HasLabel checks for the existence of a specific security label on the envelope.
func (*Envelope) MergeLabels ¶
MergeLabels appends distinct labels from another source to this one.
func (*Envelope) SetFeedback ¶
SetFeedback injects the "Teacher's" feedback into metadata
func (*Envelope) SetHistory ¶
SetHistory serializes a list of chat messages into the envelope's metadata.
type Evaluator ¶
type Evaluator interface {
// AssessPlan evaluates the policy for a given input (General purpose).
// It returns a Decision struct with the outcome.
// Formerly: Assess
AssessPlan(ctx context.Context, input Envelope) (Decision, error)
// Assess performs the Pre-Check phase (input validation).
// Formerly: Authorize
Assess(ctx context.Context, actionMeta ActionMetadata, input Envelope) error
// Reflect evaluates the outcome of an action (Post-Check).
// Formerly: Validate
Reflect(ctx context.Context, actionMeta ActionMetadata, output Envelope) (Envelope, error)
// EvaluateSteering determines the next step (Retry/Route) based on the output.
EvaluateSteering(ctx context.Context, input Envelope) (string, map[string]string, error)
// GetActionConfig queries the engine for dynamic configuration parameters.
GetActionConfig(ctx context.Context, input Envelope) (map[string]string, error)
// CheckRequirement checks if a capability is needed. e.g., requires(Req, "memory").
CheckRequirement(ctx context.Context, input Envelope, reqName string) (bool, error)
// LoadPolicy loads policy rules from a source string or file content.
LoadPolicy(ctx context.Context, source string) error
// LoadGherkinPolicy loads a Gherkin feature file and compiles it to Datalog.
LoadGherkinPolicy(ctx context.Context, featureContent string) error
// LoadFacts injects dynamic facts into the engine.
LoadFacts(facts []string) error
// RegisterAction registers action metadata for discovery/planning.
RegisterAction(meta ActionMetadata) error
// Query executes a Datalog query and returns all matching solutions.
// It is used by the planner to reason about goals and generate action sequences.
Query(ctx context.Context, facts []string, queryStr string) ([]map[string]string, error)
// Logger returns the engine's logger.
Logger() Logger
}
Evaluator: The Mangle Logic Engine. It defines the contract for policy execution, validation, and steering.
type ExecutionContext ¶
type ExecutionContext struct {
// RetryCount tracks the number of retry attempts for the current action.
RetryCount int `json:"retry_count"`
// FeedbackHistory stores all feedback messages from previous retry attempts.
FeedbackHistory []string `json:"feedback_history,omitempty"`
// CurrentHistory contains the conversation history for this session.
CurrentHistory []Message `json:"current_history,omitempty"`
}
ExecutionContext captures the runtime state of an execution session. This is used by the Durable State Manager to preserve execution continuity across restarts.
type FactLoader ¶
FactLoader loads external data (Graph/RDF) into the Engine.
type GenerateOption ¶
type GenerateOption func(o *GenerationConfig)
GenerateOption is a functional option for text generation.
type GenerationConfig ¶
type GenerationConfig struct {
Temperature float64
MaxTokens int
TopP float64
StopSequences []string
Model string
JSONMode bool
// OutputType is used by Genkit to enforce structured output (schema).
OutputType any
// Metadata stores arbitrary per-request metadata (e.g., middleware config).
Metadata map[string]any
}
GenerationConfig holds standard LLM parameters.
type HistoryStore ¶
type HistoryStore interface {
// Read retrieves the chat history for a given session.
Read(ctx context.Context, sessionID string) ([]Message, error)
// Append adds new messages to the history.
Append(ctx context.Context, sessionID string, msgs []Message) error
}
HistoryStore defines the interface for persistent storage of chat history. Implementations can be anything from in-memory maps to Redis or SQL databases.
type InputError ¶
type InputError struct {
Err error
}
InputError is a structured error that indicates a failure in input validation or fact conversion. It wraps ErrInputValidation to ensure distinction from system errors.
func WrapInputError ¶
func WrapInputError(err error) *InputError
WrapInputError wraps an error as an InputError.
func (*InputError) Error ¶
func (e *InputError) Error() string
func (*InputError) Is ¶
func (e *InputError) Is(target error) bool
func (*InputError) Unwrap ¶
func (e *InputError) Unwrap() error
type LLMResponse ¶
LLMResponse contains the generated text and token usage metadata.
type Logger ¶
type Logger interface {
// Debug records verbose diagnostic information about control flow or
// intermediate state. Arguments are interpreted as key/value pairs.
Debug(msg string, fields ...any)
// Info records high-level lifecycle events such as component start or
// stop. Arguments are interpreted as key/value pairs.
Info(msg string, fields ...any)
// Warn records recoverable issues that deserve operator attention but
// do not stop execution. Arguments are interpreted as key/value pairs.
Warn(msg string, fields ...any)
// Error records failures. Implementations should treat the "error"
// key specially when present. Arguments are interpreted as key/value pairs.
Error(msg string, fields ...any)
// With returns a child logger that automatically appends the supplied
// key/value pairs to every log record.
With(fields ...any) Logger
}
Logger defines a vendor-neutral interface for structured logging. The methods follow a "message + key/value" calling convention so callers can attach context without committing to any specific backend semantics.
All Manglekit components and user applications should use this interface for logging to ensure consistent, structured log output across the system.
func LoggerFromContext ¶
LoggerFromContext retrieves the Logger from the context. If no Logger is found, it returns a NopLogger (safe default).
type MemoryMode ¶
type MemoryMode string
MemoryMode defines the persistence strategy for conversation state.
const ( // MemoryModeNone indicates no state persistence (stateless execution). MemoryModeNone MemoryMode = "none" // MemoryModeTransient indicates in-memory persistence that lasts only for the scope of the loop/process. MemoryModeTransient MemoryMode = "transient" // MemoryModePersist indicates database-backed persistence for long-term state. MemoryModePersist MemoryMode = "persist" )
type Message ¶
type Message struct {
// Role indicates the sender of the message.
Role string `json:"role"`
// Content is the textual body of the message.
Content string `json:"content"`
}
Message represents a single message in a conversation flow.
type Meter ¶
type Meter interface {
Counter(name string, val int64, tags map[string]string)
Histogram(name string, val float64, tags map[string]string)
}
Meter abstracts metrics (Counters, Gauges).
type NodeResult ¶
type NopEmbedder ¶
type NopEmbedder struct{}
NopEmbedder is a no-op implementation of Embedder.
func (NopEmbedder) Dimension ¶
func (n NopEmbedder) Dimension() int
func (NopEmbedder) EmbedBatch ¶
type NopLogger ¶
type NopLogger struct{}
NopLogger is a Logger implementation that discards all log messages. It is useful as a default when no logger is configured.
type NopSpan ¶
type NopSpan struct{}
NopSpan is a no-op implementation of Span for when tracing is disabled.
func (*NopSpan) SetAttributes ¶
SetAttributes is a no-op.
type NopStore ¶
type NopStore struct{}
NopStore is a no-op implementation of HistoryStore for stateless mode. It discards writes and returns empty reads.
type NopTracer ¶
type NopTracer struct{}
NopTracer is a no-op implementation of Tracer for when tracing is disabled. All methods are safe no-ops that maintain the trace interface contract.
type NopVectorStore ¶
type NopVectorStore struct{}
NopVectorStore is a no-op implementation of VectorStore.
type PolicyViolationError ¶
PolicyViolationError indicates the supervisor blocked execution due to a policy violation.
func NewPolicyViolationError ¶
func NewPolicyViolationError(tier, ruleID, violation, suggestion string) *PolicyViolationError
NewPolicyViolationError creates a new PolicyViolationError.
func (*PolicyViolationError) Error ¶
func (e *PolicyViolationError) Error() string
func (*PolicyViolationError) Is ¶
func (e *PolicyViolationError) Is(target error) bool
func (*PolicyViolationError) Unwrap ¶
func (e *PolicyViolationError) Unwrap() error
type PreProcessor ¶
type PreProcessor interface {
Process(ctx context.Context, input Envelope) (map[string]any, error)
}
PreProcessor: Fast/Stateless checks (CEL/Expr).
type Quad ¶
type Quad struct {
Subject string // Source entity (e.g., "User:Bob")
Predicate string // Relationship (e.g., "has_role")
Object string // Target value (e.g., "Admin", "42")
Graph string // Namespace/Context (e.g., "global")
}
Quad represents a discrete Subject-Predicate-Object-Graph truth used in persistent storage.
type ResourceMonitor ¶
type ResourceMonitor interface {
CountTokens(ctx context.Context, text string) (int, error)
CheckBudget(ctx context.Context, key string, cost int) (bool, error)
}
ResourceMonitor: Cost & Rate Limiting.
type RiskEngine ¶
RiskEngine: specialized interface for calculating risk.
type RuleInference ¶
type RuleInference struct {
RuleName string // The name/ID of the rule (e.g., "can_execute")
Tier Tier // The governance tier (T0_Axiom, T1_Governance, T2_Playbook, T3_User)
Definition string // The original Datalog rule definition
SourceFile string // Source file where the rule was defined
Bindings map[string]string // Variable bindings from unification (e.g., X="agent-001")
Predicate string // The predicate name that matched
}
RuleInference represents a single rule that contributed to a decision.
type RuleSnapshot ¶
type RuleSnapshot struct {
RuleName string `json:"rule_name"`
Tier string `json:"tier"`
Definition string `json:"definition,omitempty"`
SourceFile string `json:"source_file,omitempty"`
Predicate string `json:"predicate,omitempty"`
Bindings map[string]string `json:"bindings,omitempty"`
}
RuleSnapshot is a serializable snapshot of a single matched rule.
type SessionState ¶
type SessionState struct {
// SessionID is the unique identifier for the persistent thread.
SessionID string `json:"session_id"`
// ActiveEnvelope is the current envelope including Payload, Metadata, and Labels.
ActiveEnvelope Envelope `json:"active_envelope"`
// ExecutionCtx contains the current RetryCount, FeedbackHistory, and CurrentHistory.
ExecutionCtx ExecutionContext `json:"execution_context"`
// LogicalFacts are the Datalog facts derived during the last successful reflection.
LogicalFacts []string `json:"logical_facts,omitempty"`
// PayloadType stores the Go type name of the payload for reconstruction.
// This is used during hydration to unmarshal the payload back to its original type.
PayloadType string `json:"payload_type,omitempty"`
// AuditRecords captures the governance audit trail across steps.
// Each entry records which rules matched, their tier, and the decision made.
// Appended per step — never overwritten.
AuditRecords []AuditRecord `json:"audit_records,omitempty"`
}
SessionState packages all components needed for full recovery of a Manglekit session. It is used by the Durable State Manager to checkpoint and restore execution state.
func (*SessionState) Clone ¶
func (s *SessionState) Clone() *SessionState
Clone creates a deep copy of the SessionState.
func (*SessionState) MarshalJSON ¶
func (s *SessionState) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for SessionState. It handles the serialization of the Envelope's Payload field, which can be any type.
func (*SessionState) UnmarshalJSON ¶
func (s *SessionState) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for SessionState. It handles the deserialization of the Envelope's Payload field.
func (*SessionState) Validate ¶
func (s *SessionState) Validate() error
Validate checks if the SessionState is valid and complete.
type Span ¶
type Span interface {
End()
SetAttributes(attributes map[string]any)
SetStatus(code string, msg string)
RecordError(err error)
}
Span represents an active operation being traced.
type StateManager ¶
type StateManager interface {
// Hydrate reconstructs a session state from durable storage.
// Returns nil, nil if the session does not exist (first run).
Hydrate(ctx context.Context, sessionID string) (*SessionState, error)
// Checkpoint persists the current session state after a successful execution.
Checkpoint(ctx context.Context, state *SessionState) error
// ExtractFacts extracts Datalog facts from an envelope for persistence.
ExtractFacts(ctx context.Context, envelope Envelope) ([]string, error)
}
StateManager defines the interface for durable session state persistence and recovery. It is used by the SDK to checkpoint and hydrate execution state across restarts. The DurableStateManager implementation is the concrete type returned by the SDK.
type StateProvider ¶
type StateProvider interface {
// Get retrieves the state associated with a session ID.
//
// Parameters:
// - ctx: Context for cancellation.
// - sessionID: The unique identifier for the session.
//
// Returns:
// - The state object (as any), or an error if retrieval fails.
Get(ctx context.Context, sessionID string) (any, error)
// Set stores the state for a session ID.
//
// Parameters:
// - ctx: Context for cancellation.
// - sessionID: The unique identifier for the session.
// - state: The state object to store.
//
// Returns:
// - An error if the operation fails.
Set(ctx context.Context, sessionID string, state any) error
// Delete removes the state for a session ID.
//
// Parameters:
// - ctx: Context for cancellation.
// - sessionID: The unique identifier for the session.
//
// Returns:
// - An error if the operation fails.
Delete(ctx context.Context, sessionID string) error
// Close cleans up any resources held by the provider (e.g., database connections).
//
// Parameters:
// - ctx: Context for cancellation.
//
// Returns:
// - An error if cleanup fails.
Close(ctx context.Context) error
}
StateProvider defines the interface for storing and retrieving arbitrary session state. Unlike MemoryStore (which is specific to chat history), StateProvider handles generic state data.
type StreamChunk ¶
type SupervisorError ¶
type SupervisorError struct {
Reason error
}
SupervisorError indicates a failure in the supervisor itself.
func (*SupervisorError) Error ¶
func (e *SupervisorError) Error() string
func (*SupervisorError) Is ¶
func (e *SupervisorError) Is(target error) bool
func (*SupervisorError) Unwrap ¶
func (e *SupervisorError) Unwrap() error
type TextGenerator ¶
type TextGenerator interface {
// Complete generates text from a prompt.
Complete(ctx context.Context, prompt string) (string, error)
// Generate generates text with options.
Generate(ctx context.Context, prompt string, opts ...GenerateOption) (*LLMResponse, error)
// Stream generates a stream of text.
Stream(ctx context.Context, prompt string) (<-chan StreamChunk, error)
}
TextGenerator abstracts the LLM.
type Tracer ¶
type Tracer interface {
// Start creates a new span with the given name and returns a context and span.
Start(ctx context.Context, name string) (context.Context, Span)
}
Tracer abstracts distributed tracing.
type ValidationError ¶
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type VectorStore ¶
type VectorStore interface {
Upsert(ctx context.Context, id string, content string) error
Search(ctx context.Context, query string, topK int) ([]string, error)
Get(ctx context.Context, id string) (string, error)
}
VectorStore defines the storage and retrieval contract.
type ViolationRule ¶
type ViolationRule struct {
RuleID string `json:"rule_id"`
Description string `json:"description"`
Severity int `json:"severity"` // 0 = Halt, 1 = Retry, 2 = Warn
}
ViolationRule represents a failed policy invariant.
type WorkflowDef ¶
type WorkflowDef struct {
ID string
Name string
Version string
RootNodeID string
Nodes map[string]NodeDef
Edges []EdgeDef
}
func (*WorkflowDef) FindStartNode ¶
func (w *WorkflowDef) FindStartNode() *NodeDef
func (*WorkflowDef) GetNode ¶
func (w *WorkflowDef) GetNode(nodeID string) *NodeDef
func (*WorkflowDef) GetOutgoingEdges ¶
func (w *WorkflowDef) GetOutgoingEdges(nodeID string) []EdgeDef
func (*WorkflowDef) Validate ¶
func (w *WorkflowDef) Validate() error
type WorkflowInstance ¶
type WorkflowInstance struct {
WorkflowID string // Reference to WorkflowDef
SessionID string // Unique session identifier
CurrentNodeID string // Current node being executed
Variables map[string]interface{} // Session variables (transient)
Metadata map[string]string // Execution metadata
LoopCounters map[string]int // Loop/iteration counters
CompletedNodes []string // Nodes that have completed
FailedNodes []string // Nodes that failed
Status WorkflowInstanceStatus
StartedAt time.Time
UpdatedAt time.Time
}
WorkflowInstance represents the dynamic state of a workflow execution. This is separate from WorkflowDef (which is immutable once hydrated). WorkflowInstance is stored in Session Memory (RAM) and NOT persisted to MEB.
func NewWorkflowInstance ¶
func NewWorkflowInstance(workflowID, sessionID string) *WorkflowInstance
NewWorkflowInstance creates a new workflow instance with default values.
func (*WorkflowInstance) GetCounter ¶
func (wi *WorkflowInstance) GetCounter(name string) int
GetCounter returns the current value of a counter.
func (*WorkflowInstance) GetVariable ¶
func (wi *WorkflowInstance) GetVariable(key string) interface{}
GetVariable returns a session variable.
func (*WorkflowInstance) IncrementCounter ¶
func (wi *WorkflowInstance) IncrementCounter(name string) int
IncrementCounter increments a loop counter.
func (*WorkflowInstance) IsNodeCompleted ¶
func (wi *WorkflowInstance) IsNodeCompleted(nodeID string) bool
IsNodeCompleted checks if a node has been completed.
func (*WorkflowInstance) MarkNodeCompleted ¶
func (wi *WorkflowInstance) MarkNodeCompleted(nodeID string)
MarkNodeCompleted marks a node as completed.
func (*WorkflowInstance) MarkNodeFailed ¶
func (wi *WorkflowInstance) MarkNodeFailed(nodeID string)
MarkNodeFailed marks a node as failed.
func (*WorkflowInstance) SessionKey ¶
func (wi *WorkflowInstance) SessionKey() string
SessionKey returns the key for storing this instance in session memory.
func (*WorkflowInstance) SetCurrentNode ¶
func (wi *WorkflowInstance) SetCurrentNode(nodeID string)
SetCurrentNode updates the current node and marks the previous node as completed.
func (*WorkflowInstance) SetVariable ¶
func (wi *WorkflowInstance) SetVariable(key string, value interface{})
SetVariable sets a session variable.
type WorkflowInstanceStatus ¶
type WorkflowInstanceStatus string
const ( WorkflowInstanceStatusPending WorkflowInstanceStatus = "pending" WorkflowInstanceStatusRunning WorkflowInstanceStatus = "running" WorkflowInstanceStatusPaused WorkflowInstanceStatus = "paused" WorkflowInstanceStatusCompleted WorkflowInstanceStatus = "completed" WorkflowInstanceStatusFailed WorkflowInstanceStatus = "failed" )
type WorkflowResult ¶
type WorkflowResult struct {
WorkflowID string
Status WorkflowStatus
Output interface{}
NodeResults map[string]*NodeResult
Error error
StartTime time.Time
EndTime time.Time
}
type WorkflowStatus ¶
type WorkflowStatus string
const ( WorkflowStatusPending WorkflowStatus = "pending" WorkflowStatusRunning WorkflowStatus = "running" WorkflowStatusCompleted WorkflowStatus = "completed" WorkflowStatusFailed WorkflowStatus = "failed" WorkflowStatusCancelled WorkflowStatus = "cancelled" )