Crate cellstate_core

Crate cellstate_core 

Source
Expand description

CELLSTATE Core - Entity Types

Core domain types and shared logic. All other crates depend on this. Contains domain types, scoring, decay, drift detection, and event-sourcing primitives.

§Type Dictionary

This crate serves as the “type dictionary” for CELLSTATE. All types visible here form the vocabulary of the system:

  • Identity: Type-safe ID newtypes (TenantId, TrajectoryId, etc.), Timestamp, ContentHash
  • Enums: Status types, entity types, categories. DB enum values use snake_case when writing; reading accepts legacy PascalCase/mixed-case via from_db_str (see enums).
  • Entities: Core domain entities (Trajectory, Scope, Artifact, Note, Turn)
  • Typestate: Compile-time safe Lock, Handoff, Delegation lifecycles
  • Events: Event DAG types (EventHeader, DagPosition, EventKind)
  • Effects: Error-as-effects pattern (Effect, ErrorEffect)

Re-exports§

pub use event_sourcing::EventSourced;
pub use filter::*;
pub use drift::*;
pub use sync_pulse::*;
pub use agent_state::*;
pub use web_mcp::*;
pub use scoring::*;
pub use decay::*;
pub use intent::*;

Modules§

agent 🔒
Agent types for multi-agent coordination.
agent_state
Agent state derived from event history (NOT stored in DB)
battle_intel 🔒
Battle Intel features: Edges, Evolution, Summarization
config 🔒
Configuration types
context 🔒
CELLSTATE Context - Context Assembly
credentials
Verifiable Credentials for Agent Identity
decay
Unified parametric decay module.
delegation 🔒
Delegation typestate for compile-time safety of delegation lifecycle.
drift
Composite divergence metric for multi-agent drift detection.
effect 🔒
Effect system for error-as-effects pattern.
embedding 🔒
Embedding vector operations
entities 🔒
Core entity structures
enums 🔒
Enum types for CELLSTATE entities
error 🔒
Error types for CELLSTATE operations
event 🔒
Event types for the Event DAG system.
event_sourcing
Systematic Event Sourcing
filter
Unified filter expressions for search and pack config
handoff 🔒
Handoff typestate for compile-time safety of handoff lifecycle.
health 🔒
Unified health check types
identity 🔒
Identity types for CELLSTATE entities
intent
Intent Engineering - Machine-readable organizational purpose
llm 🔒
LLM-related primitive types and traits.
lock 🔒
Lock typestate for compile-time safety of lock lifecycle.
models
Model discovery types.
prompt_template
Prompt Template — type-safe system prompt construction.
redaction
PII Redaction Types and Verification Registry
scoring
Deterministic scoring formula with transparency
secret 🔒
Secret wrappers for sensitive string material.
session 🔒
Session typestate for compile-time safety of stateful LLM session lifecycle.
sync_pulse
Event-driven synchronization pulse for multi-agent coordination.
web_mcp
WebMCP - Browser-native agent tool discovery primitives.

Structs§

Acquired
Lock is currently held (acquired).
ActionId
Type-safe ID for agent action entities.
Active
Session is active and accepting deltas.
Agent
An agent in the multi-agent system.
AgentAction
An action taken by an agent.
AgentBeliefs
Collection of an agent’s beliefs.
AgentGoal
A goal that an agent is pursuing.
AgentHandoff
A handoff from one agent to another.
AgentId
Type-safe ID for agent entities.
AgentMessage
A message between agents.
AgentObservation
An observation made by an agent after an action.
AgentPlan
A plan to achieve a goal.
AgentWorkingSetEntry
Ephemeral document/KV working memory entry for an agent.
ApiKeyId
Type-safe ID for API key entities.
Artifact
Artifact - typed output preserved across scopes. Artifacts survive scope closure and can be referenced later.
ArtifactId
Type-safe ID for artifact entities.
AssemblyDecision
Decision made during context assembly for audit trail.
Belief
A belief held by an agent.
BeliefId
Type-safe ID for agent belief entities.
Blake3Verifier
Blake3-based event verifier (default, recommended for performance).
Causality
W3C Trace Context compatible distributed tracing.
CellstateConfig
Master configuration struct. ALL values are required - no defaults anywhere.
Checkpoint
Checkpoint for scope recovery.
Closed
Session was closed normally (terminal).
Conflict
A conflict between memory items.
ConflictId
Type-safe ID for conflict entities.
ConflictResolutionRecord
Record of how a conflict was resolved.
ContentHash
SHA-256 content hash for deduplication and integrity verification.
ContextAssembler
Context assembler that builds context windows from packages. Adds sections by priority until budget is exhausted.
ContextAssemblyDefaults
Default values for context assembly operations.
ContextOutline
Lightweight outline of a context package for progressive disclosure.
ContextPackage
Context package - all inputs for assembly. Similar to ContextPackage in the TypeScript CRM pattern.
ContextPageDiff
Diff between two context windows after re-paging.
ContextSection
A section of the assembled context.
ContextWindow
Assembled context window with token budget management.
Created
Session has been created but not yet activated.
DagPosition
Position of an event in the DAG.
DelegatedTask
A delegated task from one agent to another.
Delegation
A delegation with compile-time state tracking.
DelegationAccepted
Delegation was accepted but not yet started.
DelegationCompleted
Delegation was completed successfully (terminal).
DelegationFailed
Delegation failed (terminal).
DelegationId
Type-safe ID for delegation entities.
DelegationRecord
Internal data storage for a delegation, independent of typestate. This is what gets persisted to the database.
DelegationRejected
Delegation was rejected (terminal).
DelegationResult
Result of a completed delegation.
DomainErrorContext
Domain error with event context for correlation and replay.
DurationMs
Duration in milliseconds for TTL and timeout values.
Edge
Edge - graph relationship between entities. Supports both binary edges (A→B) and hyperedges (N-ary relationships).
EdgeId
Type-safe ID for edge entities.
EdgeParticipant
Participant in an edge with optional role. Enables both binary edges (2 participants) and hyperedges (N participants).
EmbeddingVector
Embedding vector with dynamic dimensions. Supports any embedding model dimension (e.g., 384, 768, 1536, 3072).
EnhancedProvenance
Enhanced provenance with evidence chains.
EntityIdParseError
Error type for parsing entity IDs from strings.
EntityRef
Reference to an entity by type and ID.
EnumParseError
Error returned when parsing a DB enum string fails.
Event
A complete event with header and payload.
EventBuilder
Builder for creating events with proper positioning.
EventFlags
Flags for event processing hints.
EventHeader
Event header with all metadata needed for processing.
EventId
Type-safe ID for event entities.
EventKind
Event kind encoded as a 16-bit value.
EvolutionMetrics
Benchmark metrics from an evolution run.
EvolutionSnapshot
Evolution snapshot for pack config benchmarking. Captures a frozen state of configuration for A/B testing.
ExtractedArtifact
An artifact extracted from content.
FlowId
Type-safe ID for flow entities.
FlowStepId
Type-safe ID for flow step entities.
GoalId
Type-safe ID for agent goal entities.
GraphLink
Graph link hint for context assembly (from SQL adjacency projection).
Handoff
A handoff with compile-time state tracking.
HandoffAccepted
Handoff was accepted by the receiving agent.
HandoffCompleted
Handoff has been completed (terminal).
HandoffId
Type-safe ID for handoff entities.
HandoffRecord
Internal data storage for a handoff, independent of typestate. This is what gets persisted to the database.
HashChain
Hash chain for tamper-evident event log.
HealthCheck
Detailed health check result for a component.
HeuristicTokenizer
Heuristic tokenizer using character-to-token ratios.
InProgress
Delegation work is in progress.
Initiated
Handoff has been initiated, waiting for acceptance.
InstanceId
Type-safe ID for API server instance entities.
KernelConfig
Kernel configuration for persona and behavior.
Learning
A learning extracted from an observation.
LearningId
Type-safe ID for agent learning entities.
Lock
A lock with compile-time state tracking.
LockId
Type-safe ID for lock entities.
LockRecord
Internal data storage for a lock, independent of typestate. This is what gets persisted to the database.
MemoryAccess
Memory access configuration for an agent.
MemoryPermission
A single memory permission entry.
MemoryRegionConfig
Configuration for a memory region.
MessageId
Type-safe ID for message entities.
Note
Note - long-term cross-trajectory knowledge. Notes persist beyond individual trajectories.
NoteId
Type-safe ID for note entities.
ObservationId
Type-safe ID for agent observation entities.
PackConfigId
Type-safe ID for pack configuration entities.
Pending
Delegation is pending acceptance.
PlanCost
Cost estimate for a plan.
PlanId
Type-safe ID for agent plan entities.
PlanStep
A single step in a plan.
Principal
Principal identity for ownership and security scoping.
PrincipalId
Type-safe ID for principal entities.
Provenance
Provenance information for an artifact.
ProviderConfig
LLM provider configuration.
Rejected
Handoff was rejected by the receiving agent (terminal).
Released
Lock has been released (for documentation; locks in this state don’t exist at runtime).
RetryConfig
Retry configuration for LLM operations.
RetryPolicy
Policy for retrying failed actions.
Scope
Scope - partitioned context window within a trajectory. Scopes provide isolation and checkpointing boundaries.
ScopeId
Type-safe ID for scope entities.
ScopeSummary
Summary of a scope for context assembly.
SecretString
Sensitive string wrapper with redacted debug/display output.
SectionPriorities
Section priorities for context assembly.
SegmentUsage
Segment usage tracking.
Session
A stateful LLM session with compile-time state tracking.
SessionExpired
Session expired due to TTL (terminal).
SessionId
Type-safe ID for stateful LLM session entities.
SessionMarkers
Session markers for tracking active context.
SessionRecord
Internal data storage for a session, independent of typestate. This is what gets persisted to the database.
Sha256Verifier
SHA-256-based event verifier (for compatibility).
SnapshotId
Type-safe ID for snapshot entities.
SourceRef
Reference to a source entity.
StepId
Type-safe ID for plan step entities.
StoredDelegation
A delegation as stored in the database (status-agnostic).
StoredHandoff
A handoff as stored in the database (status-agnostic).
StoredLock
A lock as stored in the database (status-agnostic).
StoredSession
A session as stored in the database (status-agnostic).
SuccessCriterion
A measurable criterion for goal success.
SummarizationPolicy
Policy for automatic summarization/abstraction. Defines when and how to generate L1/L2 notes from lower levels.
SummarizationPolicyId
Type-safe ID for summarization policy entities.
SummarizationRequestId
Type-safe ID for summarization request entities.
SummarizeConfig
Configuration for summarization requests.
Team
A team within a tenant for group-based access control.
TeamId
Type-safe ID for team entities.
TeamMember
A membership record linking a user to a team.
TenantId
Type-safe ID for tenant entities.
TokenBudget
Segment-based token budget allocation.
TokenBudgetBuilder
Builder for constructing TokenBudget with custom ratios.
ToolExecutionId
Type-safe ID for tool execution entities.
Trajectory
Trajectory - top-level task container. A trajectory represents a complete task or goal being pursued.
TrajectoryId
Type-safe ID for trajectory entities.
TrajectoryOutcome
Outcome of a completed trajectory.
Turn
Turn - ephemeral conversation buffer entry. Turns die with their scope.
TurnId
Type-safe ID for turn entities.
WebhookId
Type-safe ID for webhook entities.
WorkingSetId
Type-safe ID for agent working set entities.

Enums§

AbstractionLevel
Semantic abstraction level for notes (L0 → L1 → L2 hierarchy).
ActionStatus
Status of an action.
ActionType
Type of action an agent can take.
AgentError
Agent coordination errors.
AgentStatus
Status of an agent in the system.
AgentTarget
Target for a message or delegation: either a specific agent by ID or any agent of a given type.
AgentType
Agent type discriminator for registration and message routing. Extensible via Custom for user-defined agent kinds.
ArtifactMetadata
Typed metadata for multimodal artifacts. This enum provides strongly-typed metadata schemas for different artifact types. It can be serialized to/from the generic metadata JSONB field.
ArtifactType
Type of artifact produced during a trajectory.
AssemblyAction
Action taken during context assembly.
BackoffStrategy
Backoff strategy for retries.
BeliefSource
Source of a belief.
BeliefType
Type of belief.
CellstateError
Master error type for all CELLSTATE errors.
CircuitState
Circuit breaker state.
CompensationAction
Action to take for compensating a failed operation.
ConfigError
Configuration errors.
ConflictResolution
Strategy for resolving conflicts.
ConflictStatus
Status of a conflict.
ConflictType
Type of conflict.
ContextPersistence
Context persistence mode.
ContextSegment
Context segment types for budget tracking.
DelegationResultStatus
Status of a delegation result.
DelegationStateError
Errors when transitioning delegation states.
DelegationStatus
Status of a delegation operation.
DomainError
Domain-level errors that affect business logic.
EdgeType
Type of edge relationship between entities.
Effect
An effect represents the outcome of an operation.
EntityType
Entity type discriminator for polymorphic references.
ErrorEffect
An error effect that can be persisted and replayed.
ErrorKind
High-level error categorization for metrics and routing.
EvidenceRef
Evidence reference types for provenance tracking.
EvolutionPhase
Phase of pack config evolution cycle.
ExtractionMethod
Method used to extract an artifact or evidence.
FieldType
Field types for schema definitions. Used by pack compiler and runtime validation.
GoalStatus
Status of an agent goal.
GoalType
Type of goal.
HandoffReason
Reason for a handoff.
HandoffStateError
Errors when transitioning handoff states.
HandoffStatus
Status of a handoff operation.
HashAlgorithm
Hash algorithm for event integrity.
HealthStatus
Health status for a service or component.
LearningType
Type of learning.
LlmError
LLM provider errors.
LoadedDelegation
Enum representing all possible runtime states of a delegation. Use this when you need to handle delegations loaded from the database.
LoadedHandoff
Enum representing all possible runtime states of a handoff. Use this when you need to handle handoffs loaded from the database.
LoadedSession
Enum representing all possible runtime states of a session. Use this when you need to handle sessions loaded from the database.
LockMode
Lock mode determining concurrency behavior.
LockStateError
Errors when transitioning lock states.
MemoryCategory
Memory category for hierarchical memory organization.
MemoryRegion
Type of memory region.
MemoryType
Memory type for permission scoping (artifact, note, turn, working set).
MessagePriority
Priority level for messages.
MessageType
Type of agent message.
NoteType
Type of note (cross-trajectory knowledge).
OperationalError
Operational errors that don’t affect business logic.
OutcomeStatus
Outcome status for completed trajectories.
PermissionScope
Permission scope for memory access.
PlanStatus
Status of a plan.
PrincipalType
Principal type for identity and ownership scoping.
ProviderCapability
Capabilities a provider can offer.
ProviderType
LLM provider type for configuration.
ResolutionStrategy
Strategy for resolving a conflict.
ResourceType
Resource type for lock scoping.
RoutingStrategy
Strategy for routing requests to providers.
SectionType
Type of context section.
SegmentBudgetError
Error type for segment budget violations.
SessionStateError
Errors when transitioning session states.
SessionStatus
Status of a stateful LLM session.
StepStatus
Status of a plan step.
StorageError
Storage layer errors.
SummarizationRequestStatus
Status of a summarization request.
SummarizationTrigger
Trigger condition for auto-summarization policy.
SummarizeStyle
Style of summarization output.
TTL
Time-to-live and retention configuration for memory entries. Supports both time-based expiration and count-based limits.
TeamRole
Role within a team.
ToolExecutionStatus
Status of a tool execution.
TrajectoryStatus
Status of a trajectory (task container).
TurnRole
Role of a turn in conversation.
UpstreamSignal
Signals that can be sent upstream in the DAG (“tram car tracks”).
ValidationError
Validation errors.
ValidationMode
Validation mode for PCP.
VectorError
Vector operation errors.
VerificationStatus
Verification status for evidence.
WaitCondition
Condition that a pending effect is waiting for.

Traits§

DelegationState
Marker trait for delegation states.
EmbeddingProvider
Async trait for embedding providers.
EntityIdType
Trait for type-safe entity IDs.
ErrorClassifiable
Unified error classification for retry/intervention decisions across all error types.
EventDag
Trait for Event DAG operations.
EventDagExt
Extension trait for EventDag with convenience methods.
EventVerifier
Trait for cryptographic event verification.
HandoffState
Marker trait for handoff states.
LockState
Marker trait for lock states.
SessionState
Marker trait for session states.
SummarizationProvider
Async trait for summarization providers.
Tokenizer
Trait for counting tokens in text.

Functions§

compute_content_hash
Compute SHA-256 hash of content.
compute_lock_key
Compute a stable i64 key for advisory locks using FNV-1a hash.
estimate_tokens
Estimate token count using the configured tokenizer if present.
estimate_tokens_heuristic
Estimate token count using the default heuristic tokenizer.
register_global_tokenizer
Register a global tokenizer used by estimate_tokens.
truncate_to_token_budget
Truncate text to fit within token budget. Prefers sentence boundaries, falls back to word boundaries.
validate_event_kind
Validate that an event kind is a recognized, defined variant.

Type Aliases§

CellstateResult
Result type alias for CELLSTATE operations.
RawContent
Raw binary content for BYTEA storage.
Timestamp
Timestamp type using UTC timezone.