context

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CacheAnalysis

type CacheAnalysis struct {
	Prompt             string   `json:"prompt"`
	EstimatedTokens    int      `json:"estimated_tokens"`
	HasStablePrefix    bool     `json:"has_stable_prefix"`
	HasTimestampIssues bool     `json:"has_timestamp_issues"`
	HasVariableContent bool     `json:"has_variable_content"`
	CacheabilityScore  float64  `json:"cacheability_score"`
	Recommendations    []string `json:"recommendations"`
}

CacheAnalysis provides detailed analysis of prompt cacheability.

type CacheConfig

type CacheConfig struct {
	StablePrefix         string `json:"stable_prefix"`         // Stable prompt prefix for cache hits
	MaxPrefixSize        int    `json:"max_prefix_size"`       // Maximum size of stable prefix
	BreakpointInterval   int    `json:"breakpoint_interval"`   // Token interval for cache breakpoints
	EnableMetrics        bool   `json:"enable_metrics"`        // Track cache hit/miss metrics
	TimestampGranularity string `json:"timestamp_granularity"` // "day", "hour", "minute" - NEVER "second"
}

CacheConfig controls KV-cache optimization patterns.

type CacheMetrics

type CacheMetrics struct {
	HitRate      float64 `json:"hit_rate"`
	Hits         int64   `json:"hits"`
	Misses       int64   `json:"misses"`
	TokensSaved  int64   `json:"tokens_saved"`
	CostSavings  float64 `json:"cost_savings"`
	PrefixStable bool    `json:"prefix_stable"`
	PrefixSize   int     `json:"prefix_size"`
}

CacheMetrics provides detailed cache performance information.

type CacheOptimizer

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

CacheOptimizer implements Manus-inspired KV-cache optimization patterns. The goal is to maximize cache hit rates for 10x cost reduction on LLM calls.

func NewCacheOptimizer

func NewCacheOptimizer(config CacheConfig) *CacheOptimizer

NewCacheOptimizer creates a new cache optimizer with Manus patterns.

func (*CacheOptimizer) AddCacheBreakpoint

func (co *CacheOptimizer) AddCacheBreakpoint(tokenPosition int)

AddCacheBreakpoint manually inserts cache breakpoints at specific token positions. This is useful for providers that require explicit breakpoint management.

func (*CacheOptimizer) AnalyzePromptForCacheability

func (co *CacheOptimizer) AnalyzePromptForCacheability(prompt string) CacheAnalysis

AnalyzePromptForCacheability analyzes a prompt and suggests optimizations.

func (*CacheOptimizer) EstimateTokens

func (co *CacheOptimizer) EstimateTokens(content string) int

EstimateTokens provides rough token estimation for cache calculations.

func (*CacheOptimizer) GetCacheBreakpoints

func (co *CacheOptimizer) GetCacheBreakpoints() []int

GetCacheBreakpoints returns the current cache breakpoints.

func (*CacheOptimizer) GetCostSavings

func (co *CacheOptimizer) GetCostSavings() float64

GetCostSavings returns the estimated cost savings from cache optimization.

func (*CacheOptimizer) GetHitRate

func (co *CacheOptimizer) GetHitRate() float64

GetHitRate returns the current cache hit rate.

func (*CacheOptimizer) GetMetrics

func (co *CacheOptimizer) GetMetrics() CacheMetrics

GetMetrics returns current cache performance metrics.

func (*CacheOptimizer) GetTokensSaved

func (co *CacheOptimizer) GetTokensSaved() int64

GetTokensSaved returns the total number of tokens saved through caching.

func (*CacheOptimizer) OptimizeForAppendOnly

func (co *CacheOptimizer) OptimizeForAppendOnly(basePrompt string, newContent string) string

OptimizeForAppendOnly ensures the prompt follows append-only semantics for cache efficiency.

func (*CacheOptimizer) OptimizePrompt

func (co *CacheOptimizer) OptimizePrompt(prompt string, timestamp time.Time) string

OptimizePrompt applies Manus cache optimization patterns to maximize KV-cache hits. CRITICAL: This is the core method that achieves 10x cost reduction.

func (*CacheOptimizer) RecordCacheHit

func (co *CacheOptimizer) RecordCacheHit(promptSize int)

RecordCacheHit updates metrics when a cache hit is detected. The promptSize parameter represents the size of the cached portion that was reused.

func (*CacheOptimizer) RecordCacheMiss

func (co *CacheOptimizer) RecordCacheMiss()

RecordCacheMiss updates metrics when a cache miss occurs.

func (*CacheOptimizer) ResetMetrics

func (co *CacheOptimizer) ResetMetrics()

ResetMetrics clears all accumulated metrics.

type CachedContext

type CachedContext struct {
	Content        string                 `json:"content"`
	Checksum       string                 `json:"checksum"`
	Timestamp      time.Time              `json:"timestamp"`
	CacheOptimized bool                   `json:"cache_optimized"`
	Compressed     bool                   `json:"compressed"`
	Diversified    bool                   `json:"diversified"`
	TokenCount     int                    `json:"token_count"`
	ProcessingTime time.Duration          `json:"processing_time"`
	Metadata       map[string]interface{} `json:"metadata"`
}

CachedContext represents a processed context ready for agent consumption.

type CompressibleContent

type CompressibleContent struct {
	Content     string                 `json:"content"`
	ContentType string                 `json:"content_type"`
	Priority    CompressionPriority    `json:"priority"`
	Metadata    map[string]interface{} `json:"metadata"`
	PreserveKey bool                   `json:"preserve_key"` // Keep even if large
}

CompressibleContent represents content that can be compressed or summarized.

type CompressionPriority

type CompressionPriority string

CompressionPriority determines how aggressively content should be compressed.

const (
	PriorityHigh    CompressionPriority = "high"    // Most important, compress minimally
	PriorityMedium  CompressionPriority = "medium"  // Balanced compression
	PriorityLow     CompressionPriority = "low"     // Aggressive compression/summarization
	PriorityMinimal CompressionPriority = "minimal" // Only keep essential summary
)

type CompressionResult

type CompressionResult struct {
	OriginalSize     int64                  `json:"original_size"`
	CompressedSize   int64                  `json:"compressed_size"`
	CompressionRatio float64                `json:"compression_ratio"`
	Method           string                 `json:"method"`
	Summary          string                 `json:"summary,omitempty"`
	Checksum         string                 `json:"checksum"`
	Timestamp        time.Time              `json:"timestamp"`
	Metadata         map[string]interface{} `json:"metadata"`
}

CompressionResult provides detailed information about compression operations.

type Compressor

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

Compressor implements Manus-inspired content compression for context efficiency. Instead of truncating content, we intelligently compress and summarize to maintain all important information while reducing token usage.

func NewCompressor

func NewCompressor(memory *FileSystemMemory, config Config) *Compressor

NewCompressor creates a content compressor optimized for context efficiency.

func (*Compressor) CompressAndStore

func (c *Compressor) CompressAndStore(ctx context.Context, id string, content CompressibleContent) (string, error)

CompressAndStore combines compression with filesystem storage for large content.

func (*Compressor) CompressContent

func (c *Compressor) CompressContent(ctx context.Context, content CompressibleContent) (string, CompressionResult, error)

CompressContent intelligently compresses content based on type and priority. CRITICAL: This maintains information density while reducing token count.

func (*Compressor) DecompressContent

func (c *Compressor) DecompressContent(ctx context.Context, compressedContent string, method string) (string, error)

DecompressContent reverses compression to restore original content.

func (*Compressor) GetCompressionStats

func (c *Compressor) GetCompressionStats() map[string]interface{}

GetCompressionStats returns detailed compression performance metrics.

type Config

type Config struct {
	// Session identification
	SessionID string `json:"session_id"`
	AgentID   string `json:"agent_id"`
	BaseDir   string `json:"base_dir"`

	// Feature toggles for Manus-inspired patterns
	EnableCacheOptimization bool `json:"enable_cache_optimization"`
	EnableFileSystemMemory  bool `json:"enable_filesystem_memory"`
	EnableTodoManagement    bool `json:"enable_todo_management"`
	EnableErrorRetention    bool `json:"enable_error_retention"`
	EnableLogitMasking      bool `json:"enable_logit_masking"`
	EnableCompression       bool `json:"enable_compression"`
	EnableDiversification   bool `json:"enable_diversification"`

	// Performance tuning
	CompressionThreshold int64   `json:"compression_threshold"` // Compress content above this size (bytes)
	MaxMemorySize        int64   `json:"max_memory_size"`       // Maximum filesystem memory usage
	CacheHitTarget       float64 `json:"cache_hit_target"`      // Target cache hit rate (0.0-1.0)
	MaxErrorRetention    int     `json:"max_error_retention"`   // Maximum number of errors to retain

	// Cache configuration
	Cache CacheConfig `json:"cache"`

	// Memory configuration
	Memory MemoryConfig `json:"memory"`

	// Todo management configuration
	Todo TodoConfig `json:"todo"`
}

Config defines the configuration for agent context management. Inspired by Manus's context engineering patterns for production-grade agents.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a production-ready configuration based on Manus patterns.

func DevelopmentConfig

func DevelopmentConfig() Config

DevelopmentConfig returns a configuration suitable for development/testing.

func ProductionConfig

func ProductionConfig() Config

ProductionConfig returns a configuration optimized for production cost efficiency.

func (*Config) GetTimestampFormat

func (c *Config) GetTimestampFormat() string

GetTimestampFormat returns the appropriate timestamp format for cache optimization.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid and returns detailed errors.

type ContextDiversifier

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

ContextDiversifier implements Manus's context diversity patterns to prevent few-shot traps. The key insight: agents get stuck in patterns when they see the same context repeatedly. By rotating context presentations, we maintain performance while preventing overfitting.

func NewContextDiversifier

func NewContextDiversifier(memory *FileSystemMemory, config Config) *ContextDiversifier

NewContextDiversifier creates a diversifier to prevent few-shot pattern traps.

func (*ContextDiversifier) AddCustomTemplate

func (cd *ContextDiversifier) AddCustomTemplate(template ContextTemplate)

AddCustomTemplate allows adding domain-specific templates.

func (*ContextDiversifier) DiversifyContext

func (cd *ContextDiversifier) DiversifyContext(ctx context.Context, content string, contentType string) (string, DiversificationResult, error)

DiversifyContext applies diversity patterns to prevent few-shot traps. CRITICAL: This is the core method that prevents agent stagnation.

func (*ContextDiversifier) GetDiversityHealth

func (cd *ContextDiversifier) GetDiversityHealth() DiversityMetrics

GetDiversityHealth returns current diversity metrics.

func (*ContextDiversifier) PreventStagnation

func (cd *ContextDiversifier) PreventStagnation(ctx context.Context, content string) string

PreventStagnation explicitly forces template rotation to break patterns.

func (*ContextDiversifier) RotateTemplateIfNeeded

func (cd *ContextDiversifier) RotateTemplateIfNeeded(ctx context.Context, currentContent string) (string, bool)

RotateTemplateIfNeeded checks if template rotation is needed and performs it.

type ContextRequest

type ContextRequest struct {
	// Content inputs
	Observations   []string               `json:"observations"`
	CurrentTask    string                 `json:"current_task"`
	AdditionalData map[string]interface{} `json:"additional_data"`

	// Optimization preferences
	PrioritizeCache      bool                `json:"prioritize_cache"`
	CompressionPriority  CompressionPriority `json:"compression_priority"`
	AllowDiversification bool                `json:"allow_diversification"`
	IncludeErrors        bool                `json:"include_errors"`
	IncludeTodos         bool                `json:"include_todos"`

	// Context constraints
	MaxTokens          int     `json:"max_tokens"`
	MinCacheEfficiency float64 `json:"min_cache_efficiency"`
}

ContextRequest specifies how context should be built and optimized.

type ContextResponse

type ContextResponse struct {
	// Optimized context ready for agent
	Context string `json:"context"`

	// Performance metrics
	ProcessingTime   time.Duration `json:"processing_time"`
	TokenCount       int           `json:"token_count"`
	CacheHitRate     float64       `json:"cache_hit_rate"`
	CompressionRatio float64       `json:"compression_ratio"`
	DiversityScore   float64       `json:"diversity_score"`

	// Applied optimizations
	OptimizationsApplied []string `json:"optimizations_applied"`
	CostSavings          float64  `json:"cost_savings"`

	// Metadata
	ContextVersion int64                  `json:"context_version"`
	Metadata       map[string]interface{} `json:"metadata"`
}

ContextResponse provides the optimized context plus detailed metrics.

type ContextTemplate

type ContextTemplate struct {
	ID            string                 `json:"id"`
	Name          string                 `json:"name"`
	Structure     TemplateStructure      `json:"structure"`
	Style         PresentationStyle      `json:"style"`
	UsageCount    int64                  `json:"usage_count"`
	LastUsed      time.Time              `json:"last_used"`
	Effectiveness float64                `json:"effectiveness"`
	Metadata      map[string]interface{} `json:"metadata"`
}

ContextTemplate defines different ways to present the same information.

type ContextUsage

type ContextUsage struct {
	TemplateID      string    `json:"template_id"`
	UsageCount      int64     `json:"usage_count"`
	LastUsed        time.Time `json:"last_used"`
	SuccessRate     float64   `json:"success_rate"`
	AverageLatency  float64   `json:"average_latency"`
	TokenEfficiency float64   `json:"token_efficiency"`
}

ContextUsage tracks how each template performs.

type DiversificationResult

type DiversificationResult struct {
	OriginalTemplate string                 `json:"original_template"`
	NewTemplate      string                 `json:"new_template"`
	Transformation   string                 `json:"transformation"`
	DiversityGain    float64                `json:"diversity_gain"`
	EstimatedImpact  string                 `json:"estimated_impact"`
	Metadata         map[string]interface{} `json:"metadata"`
}

DiversificationResult provides information about context transformation.

type DiversityMetrics

type DiversityMetrics struct {
	TotalTemplates      int     `json:"total_templates"`
	ActiveTemplates     int     `json:"active_templates"`
	TemplateEntropy     float64 `json:"template_entropy"`
	DiversityScore      float64 `json:"diversity_score"`
	RecentRotations     int64   `json:"recent_rotations"`
	PreventedStagnation int64   `json:"prevented_stagnation"`
}

DiversityMetrics tracks overall context diversity health.

type ErrorRecord

type ErrorRecord struct {
	ID         string                 `json:"id"`
	Timestamp  time.Time              `json:"timestamp"`
	ErrorType  string                 `json:"error_type"`
	Message    string                 `json:"message"`
	Context    map[string]interface{} `json:"context"`
	StackTrace string                 `json:"stack_trace,omitempty"`
	Input      string                 `json:"input,omitempty"`
	Attempt    int                    `json:"attempt"`
	Resolution string                 `json:"resolution,omitempty"`
	Severity   ErrorSeverity          `json:"severity"`
	Pattern    string                 `json:"pattern,omitempty"`
	Learned    bool                   `json:"learned"`
}

ErrorRecord captures detailed information about failures for learning.

type ErrorRetainer

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

ErrorRetainer implements Manus's error retention pattern for implicit learning. Instead of hiding errors, we keep them in context so agents learn from failures. This prevents repeated mistakes and improves agent reliability over time.

func NewErrorRetainer

func NewErrorRetainer(memory *FileSystemMemory, config Config) *ErrorRetainer

NewErrorRetainer creates a retainer that learns from errors instead of hiding them.

func (*ErrorRetainer) GetErrorContext

func (er *ErrorRetainer) GetErrorContext() string

GetErrorContext returns error history formatted for agent context inclusion. This is the CORE pattern - making errors visible for learning.

func (*ErrorRetainer) GetErrorPattern

func (er *ErrorRetainer) GetErrorPattern(errorType, message string) (string, int, bool)

GetErrorPattern analyzes if a new error matches known patterns.

func (*ErrorRetainer) GetLearningMetrics

func (er *ErrorRetainer) GetLearningMetrics() map[string]interface{}

GetLearningMetrics returns metrics about error learning effectiveness.

func (*ErrorRetainer) RecordError

func (er *ErrorRetainer) RecordError(ctx context.Context, errorType, message string, severity ErrorSeverity, errorCtx map[string]interface{}) string

RecordError captures an error for learning and pattern recognition. CRITICAL: This makes errors visible to the agent for implicit learning.

func (*ErrorRetainer) RecordSuccess

func (er *ErrorRetainer) RecordSuccess(ctx context.Context, successType, description string, successCtx map[string]interface{}) string

RecordSuccess captures successful resolutions to reinforce positive patterns.

func (*ErrorRetainer) ShouldPreventRetry

func (er *ErrorRetainer) ShouldPreventRetry(errorType, message string, currentAttempt int) bool

ShouldPreventRetry determines if an error pattern suggests stopping retries.

type ErrorSeverity

type ErrorSeverity string

ErrorSeverity categorizes errors for prioritized learning.

const (
	SeverityCritical ErrorSeverity = "critical" // System failures, data corruption
	SeverityHigh     ErrorSeverity = "high"     // Major functionality broken
	SeverityMedium   ErrorSeverity = "medium"   // Degraded performance
	SeverityLow      ErrorSeverity = "low"      // Minor issues, warnings
	SeverityInfo     ErrorSeverity = "info"     // Informational only
)

type FileSystemMemory

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

FileSystemMemory implements Manus's filesystem-as-context pattern. This provides unlimited external memory by storing large observations, contexts, and other data on disk while keeping short references in context.

func NewFileSystemMemory

func NewFileSystemMemory(baseDir, sessionID, agentID string, config MemoryConfig) (*FileSystemMemory, error)

NewFileSystemMemory creates unlimited external memory using the filesystem.

func (*FileSystemMemory) CleanExpired

func (fsm *FileSystemMemory) CleanExpired(ctx context.Context) (int64, error)

CleanExpired removes files older than the retention period.

func (*FileSystemMemory) GetFileCount

func (fsm *FileSystemMemory) GetFileCount() int64

GetFileCount returns the total number of stored files.

func (*FileSystemMemory) GetMetrics

func (fsm *FileSystemMemory) GetMetrics() map[string]interface{}

GetMetrics returns filesystem memory usage metrics.

func (*FileSystemMemory) GetTotalSize

func (fsm *FileSystemMemory) GetTotalSize() int64

GetTotalSize returns the total size of stored content.

func (*FileSystemMemory) ListFiles

func (fsm *FileSystemMemory) ListFiles(contentType string) ([]MemoryReference, error)

ListFiles returns all stored files of a specific type.

func (*FileSystemMemory) RetrieveObservation

func (fsm *FileSystemMemory) RetrieveObservation(ctx context.Context, reference string) (*MemoryContent, error)

RetrieveObservation retrieves a stored observation by its reference.

func (*FileSystemMemory) StoreContext

func (fsm *FileSystemMemory) StoreContext(ctx context.Context, contextID string, data map[string]interface{}) (string, error)

StoreContext stores agent context data for later retrieval.

func (*FileSystemMemory) StoreFile

func (fsm *FileSystemMemory) StoreFile(ctx context.Context, contentType, id string, content []byte, metadata map[string]interface{}) (string, error)

StoreFile stores arbitrary file content with a specific type.

func (*FileSystemMemory) StoreLargeObservation

func (fsm *FileSystemMemory) StoreLargeObservation(ctx context.Context, id string, content []byte, metadata map[string]interface{}) (string, error)

StoreLargeObservation stores large observations externally and returns a short reference. This is the core pattern from Manus - instead of including huge content in context, store it externally and include only a reference.

type Manager

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

Manager orchestrates all Manus-inspired context engineering patterns. This is the unified interface that provides 10x cost reduction through sophisticated context management, KV-cache optimization, and attention manipulation.

func NewManager

func NewManager(sessionID, agentID, baseDir string, config Config) (*Manager, error)

NewManager creates a new context manager with all Manus patterns enabled.

func (*Manager) AddTodo

func (m *Manager) AddTodo(ctx context.Context, description string, priority int) error

AddTodo adds a new task to the attention management system.

func (*Manager) BuildOptimizedContext

func (m *Manager) BuildOptimizedContext(ctx context.Context, request ContextRequest) (*ContextResponse, error)

BuildOptimizedContext is the CORE method that applies all Manus patterns to create highly optimized context for 10x cost reduction.

func (*Manager) CompleteTodo

func (m *Manager) CompleteTodo(ctx context.Context, todoID string) error

CompleteTodo marks a todo as completed and moves it to completed list.

func (*Manager) GetHealthStatus

func (m *Manager) GetHealthStatus() map[string]interface{}

GetHealthStatus returns overall health of the context management system.

func (*Manager) GetPerformanceMetrics

func (m *Manager) GetPerformanceMetrics() map[string]interface{}

GetPerformanceMetrics returns comprehensive performance and cost metrics.

func (*Manager) RecordError

func (m *Manager) RecordError(ctx context.Context, errorType, message string, severity ErrorSeverity, errorCtx map[string]interface{})

RecordError integrates error recording with the error retention system.

func (*Manager) RecordSuccess

func (m *Manager) RecordSuccess(ctx context.Context, successType, description string, successCtx map[string]interface{})

RecordSuccess records successful operations for pattern reinforcement.

func (*Manager) SetActiveTodo

func (m *Manager) SetActiveTodo(ctx context.Context, todoID string) error

SetActiveTodo marks a specific todo as currently active.

func (*Manager) SetEnabled

func (m *Manager) SetEnabled(enabled bool)

Enable/Disable allows toggling context management features.

func (*Manager) UpdateTodos

func (m *Manager) UpdateTodos(ctx context.Context, todos []TodoItem) error

UpdateTodos manages the todo.md attention manipulation system.

type MemoryConfig

type MemoryConfig struct {
	MaxFileSize      int64             `json:"max_file_size"`     // Maximum size per memory file
	RetentionPeriod  time.Duration     `json:"retention_period"`  // How long to keep memory files
	CompressionLevel int               `json:"compression_level"` // 0=none, 1=fast, 9=best
	FilePatterns     map[string]string `json:"file_patterns"`     // Naming patterns for different content types
}

MemoryConfig controls filesystem-based memory patterns.

type MemoryContent

type MemoryContent struct {
	Reference MemoryReference `json:"reference"`
	Content   []byte          `json:"content"`
}

MemoryContent represents content stored in filesystem memory.

type MemoryReference

type MemoryReference struct {
	ID         string                 `json:"id"`
	Type       string                 `json:"type"`
	Path       string                 `json:"path"`
	Size       int64                  `json:"size"`
	Checksum   string                 `json:"checksum"`
	Timestamp  time.Time              `json:"timestamp"`
	Compressed bool                   `json:"compressed"`
	Metadata   map[string]interface{} `json:"metadata"`
}

MemoryReference represents a reference to externally stored content.

type PresentationStyle

type PresentationStyle string

PresentationStyle defines how content is stylistically presented.

const (
	StyleFormal     PresentationStyle = "formal"     // Professional tone
	StyleCasual     PresentationStyle = "casual"     // Conversational tone
	StyleTechnical  PresentationStyle = "technical"  // Developer-focused
	StyleExecutive  PresentationStyle = "executive"  // High-level summary
	StyleDetailed   PresentationStyle = "detailed"   // Comprehensive info
	StyleMinimalist PresentationStyle = "minimalist" // Essential info only
)

type SuccessRecord

type SuccessRecord struct {
	ID          string                 `json:"id"`
	Timestamp   time.Time              `json:"timestamp"`
	SuccessType string                 `json:"success_type"`
	Description string                 `json:"description"`
	Context     map[string]interface{} `json:"context"`
	Input       string                 `json:"input,omitempty"`
	Output      string                 `json:"output,omitempty"`
	PrevErrors  []string               `json:"previous_errors,omitempty"`
	Pattern     string                 `json:"pattern,omitempty"`
	Confidence  float64                `json:"confidence"`
}

SuccessRecord captures successful resolutions for pattern reinforcement.

type TemplateStructure

type TemplateStructure string

TemplateStructure defines how content is organized in the template.

const (
	StructureLinear       TemplateStructure = "linear"        // Traditional top-to-bottom
	StructureHierarchical TemplateStructure = "hierarchical"  // Nested sections
	StructureBulletPoints TemplateStructure = "bullet_points" // Bulleted lists
	StructureTimeline     TemplateStructure = "timeline"      // Chronological order
	StructureMatrix       TemplateStructure = "matrix"        // Table/grid format
	StructureNarrative    TemplateStructure = "narrative"     // Story-like flow
)

type TodoConfig

type TodoConfig struct {
	UpdateInterval    time.Duration `json:"update_interval"`     // How often to rewrite todo.md
	MaxActiveTasks    int           `json:"max_active_tasks"`    // Maximum tasks marked as active
	MaxPendingTasks   int           `json:"max_pending_tasks"`   // Maximum pending tasks to show
	MaxCompletedTasks int           `json:"max_completed_tasks"` // Maximum completed tasks to keep
	EnableEmojis      bool          `json:"enable_emojis"`       // Use emoji markers for attention
}

TodoConfig controls todo.md attention manipulation patterns.

type TodoItem

type TodoItem struct {
	ID          string                 `json:"id"`
	Description string                 `json:"description"`
	Status      TodoStatus             `json:"status"`
	Created     time.Time              `json:"created"`
	Updated     time.Time              `json:"updated"`
	Priority    int                    `json:"priority"`
	Context     map[string]interface{} `json:"context"`
	Progress    float64                `json:"progress"` // 0.0 to 1.0
}

TodoItem represents a task in the todo list.

type TodoManager

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

TodoManager implements Manus's todo.md attention manipulation pattern. This is a brilliant technique: by constantly rewriting a todo.md file, the agent keeps its objectives in the recent attention span, avoiding "lost-in-the-middle" issues and reducing goal misalignment.

func NewTodoManager

func NewTodoManager(memory *FileSystemMemory, config TodoConfig) *TodoManager

NewTodoManager creates a manager for the todo.md attention pattern.

func (*TodoManager) AddTodo

func (tm *TodoManager) AddTodo(ctx context.Context, description string, priority int) error

AddTodo adds a new todo item and updates the attention file.

func (*TodoManager) CompleteTodo

func (tm *TodoManager) CompleteTodo(ctx context.Context, todoID string) error

CompleteTodo marks a todo as completed and moves it to completed list.

func (*TodoManager) GetActiveTodos

func (tm *TodoManager) GetActiveTodos() []TodoItem

GetActiveTodos returns currently active todo items.

func (*TodoManager) GetMetrics

func (tm *TodoManager) GetMetrics() map[string]interface{}

GetMetrics returns todo management metrics.

func (*TodoManager) GetPendingTodos

func (tm *TodoManager) GetPendingTodos() []TodoItem

GetPendingTodos returns pending todo items.

func (*TodoManager) GetTodoContent

func (tm *TodoManager) GetTodoContent() string

GetTodoContent returns the current todo.md content for inclusion in context.

func (*TodoManager) SetActive

func (tm *TodoManager) SetActive(ctx context.Context, todoID string) error

SetActive marks a todo as currently active and updates attention.

func (*TodoManager) UpdateProgress

func (tm *TodoManager) UpdateProgress(ctx context.Context, todoID string, progress float64) error

UpdateProgress updates the progress of a todo item.

func (*TodoManager) UpdateTodos

func (tm *TodoManager) UpdateTodos(ctx context.Context, todos []TodoItem) error

UpdateTodos updates the todo list and triggers attention manipulation. CRITICAL: This method constantly rewrites todo.md to keep objectives in the model's recent attention span.

type TodoStatus

type TodoStatus string

TodoStatus represents the current state of a todo item.

const (
	TodoPending    TodoStatus = "pending"
	TodoInProgress TodoStatus = "in_progress"
	TodoCompleted  TodoStatus = "completed"
	TodoFailed     TodoStatus = "failed"
	TodoBlocked    TodoStatus = "blocked"
)

Jump to

Keyboard shortcuts

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