ctxmgr

package
v1.36.2 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

Index

Constants

View Source
const (
	// Tamanho alvo por chunk (em tokens estimados)
	DefaultChunkTargetTokens = 30000 // ~120KB de texto

	// Tamanho máximo por chunk
	MaxChunkTokens = 50000 // ~200KB de texto

	// Tamanho mínimo para considerar dividir
	MinFilesForChunking = 10
)
View Source
const (
	MaxContextNameLength = 64
	MaxTotalSizeBytes    = 200 * 1024 * 1024 // 200MB
	MinNameLength        = 3
	MaxDescriptionLength = 500
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AttachOptions

type AttachOptions struct {
	Priority       int
	SelectedChunks []int // Vazio = todos os chunks
}

AttachOptions define opções para anexar contextos

type AttachedContext

type AttachedContext struct {
	ContextID      string    `json:"context_id"`                // ID do contexto
	AttachedAt     time.Time `json:"attached_at"`               // Quando foi anexado
	Priority       int       `json:"priority"`                  // Prioridade na ordem de mensagens (menor = primeiro)
	SelectedChunks []int     `json:"selected_chunks,omitempty"` // CORREÇÃO: Adicionado campo para chunks selecionados
}

AttachedContext representa um contexto anexado a uma sessão

type ChunkStrategy

type ChunkStrategy string

ChunkStrategy define a estratégia de divisão

const (
	ChunkByDirectory ChunkStrategy = "directory" // Agrupar por diretório
	ChunkByFileType  ChunkStrategy = "filetype"  // Agrupar por tipo de arquivo
	ChunkBySize      ChunkStrategy = "size"      // Dividir por tamanho
	ChunkSmart       ChunkStrategy = "smart"     // Estratégia inteligente híbrida
)

type Chunker

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

Chunker divide arquivos em chunks inteligentes

func NewChunker

func NewChunker(logger *zap.Logger) *Chunker

NewChunker cria uma nova instância de Chunker

func (*Chunker) DivideIntoChunks

func (c *Chunker) DivideIntoChunks(files []utils.FileInfo, strategy ChunkStrategy) ([]FileChunk, error)

DivideIntoChunks divide arquivos em chunks usando estratégia inteligente

type ContextFilter

type ContextFilter struct {
	Tags          []string       `json:"tags"`           // Filtrar por tags
	Mode          ProcessingMode `json:"mode"`           // Filtrar por modo
	MinSize       int64          `json:"min_size"`       // Tamanho mínimo
	MaxSize       int64          `json:"max_size"`       // Tamanho máximo
	CreatedAfter  *time.Time     `json:"created_after"`  // Criado após
	CreatedBefore *time.Time     `json:"created_before"` // Criado antes
	NamePattern   string         `json:"name_pattern"`   // Padrão regex para nome
}

ContextFilter filtra contextos ao listar

type ContextMetrics

type ContextMetrics struct {
	TotalContexts    int            `json:"total_contexts"`
	AttachedContexts int            `json:"attached_contexts"`
	TotalFiles       int            `json:"total_files"`
	TotalSizeBytes   int64          `json:"total_size_bytes"`
	ContextsByMode   map[string]int `json:"contexts_by_mode"`
	LastUpdated      time.Time      `json:"last_updated"`
	StoragePath      string         `json:"storage_path"`
}

ContextMetrics contém métricas sobre o uso de contextos

type FileChunk

type FileChunk struct {
	Index       int              `json:"index"`        // Índice do chunk (1-based)
	TotalChunks int              `json:"total_chunks"` // Total de chunks
	Files       []utils.FileInfo `json:"files"`        // Arquivos neste chunk
	Description string           `json:"description"`  // Descrição do chunk
	TotalSize   int64            `json:"total_size"`   // Tamanho total
	EstTokens   int              `json:"est_tokens"`   // Tokens estimados
}

FileChunk representa um chunk de arquivos

type FileContext

type FileContext struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Files       []utils.FileInfo  `json:"files"`
	Mode        ProcessingMode    `json:"mode"`
	TotalSize   int64             `json:"total_size"`
	FileCount   int               `json:"file_count"`
	CreatedAt   time.Time         `json:"created_at"`
	UpdatedAt   time.Time         `json:"updated_at"`
	Tags        []string          `json:"tags"`
	Metadata    map[string]string `json:"metadata"`

	ScanOptions         utils.DirectoryScanOptions `json:"-"`
	ScanOptionsMetadata ScanOptionsMetadata        `json:"scan_options_metadata"`

	Chunks        []FileChunk `json:"chunks,omitempty"`         // Chunks divididos (se modo chunked)
	IsChunked     bool        `json:"is_chunked"`               // Se foi dividido em chunks
	ChunkStrategy string      `json:"chunk_strategy,omitempty"` // Estratégia usada
}

FileContext representa um contexto gerenciado contendo arquivos e metadados

type FormatOptions

type FormatOptions struct {
	IncludeMetadata  bool `json:"include_metadata"`  // Incluir metadados no prompt
	IncludeTimestamp bool `json:"include_timestamp"` // Incluir timestamp
	Compact          bool `json:"compact"`           // Formato compacto (sem índice)
}

FormatOptions opções para formatar contexto como prompt

type Manager

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

Manager gerencia contextos de forma thread-safe

func NewManager

func NewManager(logger *zap.Logger) (*Manager, error)

NewManager cria uma nova instância do gerenciador de contextos

func (*Manager) AttachContext

func (m *Manager) AttachContext(sessionID, contextID string, priority int) error

AttachContext anexa um contexto a uma sessão (não envia à LLM ainda)

func (*Manager) AttachContextWithOptions

func (m *Manager) AttachContextWithOptions(sessionID, contextID string, opts AttachOptions) error

CORREÇÃO 1: Função refatorada para usar a estrutura de dados correta do Manager. AttachContextWithOptions anexa contexto com opções avançadas

func (*Manager) BuildPromptMessages

func (m *Manager) BuildPromptMessages(sessionID string, opts FormatOptions) ([]models.Message, error)

CORREÇÃO 2: Refatorada para usar a estrutura de dados correta e lidar com chunks selecionados. BuildPromptMessages agora considera chunks selecionados

func (*Manager) CreateContext

func (m *Manager) CreateContext(name, description string, paths []string, mode ProcessingMode, tags []string, force bool) (*FileContext, error)

CreateContext cria um novo contexto a partir de caminhos de arquivos/diretórios

func (*Manager) DeleteContext

func (m *Manager) DeleteContext(contextID string) error

DeleteContext remove um contexto permanentemente

func (*Manager) DetachContext

func (m *Manager) DetachContext(sessionID, contextID string) error

DetachContext remove um contexto anexado de uma sessão

func (*Manager) GetAttachedContexts

func (m *Manager) GetAttachedContexts(sessionID string) ([]*FileContext, error)

GetAttachedContexts retorna os contextos anexados a uma sessão

func (*Manager) GetContext

func (m *Manager) GetContext(contextID string) (*FileContext, error)

GetContext retorna um contexto pelo ID

func (*Manager) GetContextByName

func (m *Manager) GetContextByName(name string) (*FileContext, error)

GetContextByName retorna um contexto pelo nome

func (*Manager) GetMetrics

func (m *Manager) GetMetrics() *ContextMetrics

GetMetrics retorna métricas sobre os contextos

func (*Manager) ListContexts

func (m *Manager) ListContexts(filter *ContextFilter) ([]*FileContext, error)

ListContexts lista todos os contextos com filtro opcional

func (*Manager) MergeContexts

func (m *Manager) MergeContexts(name, description string, contextIDs []string, opts MergeOptions) (*FileContext, error)

MergeContexts mescla múltiplos contextos em um novo

func (*Manager) UpdateContext added in v1.35.0

func (m *Manager) UpdateContext(name string, newPaths []string, newMode ProcessingMode, newTags []string, newDescription string) (*FileContext, error)

UpdateContext atualiza um contexto existente

type MergeOptions

type MergeOptions struct {
	RemoveDuplicates bool     `json:"remove_duplicates"` // Remove arquivos duplicados
	SortByPath       bool     `json:"sort_by_path"`      // Ordena por caminho
	PreferNewer      bool     `json:"prefer_newer"`      // Prefere versões mais recentes em duplicatas
	Tags             []string `json:"tags"`              // Tags para o contexto mesclado
}

MergeOptions configura como contextos devem ser mesclados

type ProcessingMode

type ProcessingMode string

ProcessingMode define o modo de processamento de arquivos no contexto

const (
	ModeFull    ProcessingMode = "full"    // Conteúdo completo
	ModeSummary ProcessingMode = "summary" // Apenas estrutura
	ModeChunked ProcessingMode = "chunked" // Dividido em chunks
	ModeSmart   ProcessingMode = "smart"   // Seleção inteligente
)

type Processor

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

Processor processa arquivos e diretórios para contextos

func NewProcessor

func NewProcessor(logger *zap.Logger) *Processor

NewProcessor cria uma nova instância de Processor

func (*Processor) EstimateTokenCount

func (p *Processor) EstimateTokenCount(files []utils.FileInfo) int

EstimateTokenCount estima o número de tokens em um conjunto de arquivos

func (*Processor) ProcessPaths

func (p *Processor) ProcessPaths(paths []string, mode ProcessingMode) ([]utils.FileInfo, utils.DirectoryScanOptions, error)

ProcessPaths processa múltiplos caminhos baseado no modo

type ScanOptionsMetadata

type ScanOptionsMetadata struct {
	MaxTotalSize      int64    `json:"max_total_size"`
	MaxFilesToProcess int      `json:"max_files_to_process"`
	Extensions        []string `json:"extensions"`
	ExcludeDirs       []string `json:"exclude_dirs"`
	ExcludePatterns   []string `json:"exclude_patterns"`
	IncludeHidden     bool     `json:"include_hidden"`
}

ScanOptionsMetadata contém versão serializável das opções de scan

type Storage

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

Storage gerencia a persistência de contextos em disco

func NewStorage

func NewStorage(logger *zap.Logger) (*Storage, error)

NewStorage cria uma nova instância de Storage

func (*Storage) DeleteContext

func (s *Storage) DeleteContext(contextID string) error

DeleteContext deleta um contexto do disco

func (*Storage) ExportContext

func (s *Storage) ExportContext(ctx *FileContext, targetPath string) error

ExportContext exporta um contexto para um arquivo específico

func (*Storage) GetStoragePath

func (s *Storage) GetStoragePath() string

GetStoragePath retorna o caminho base de armazenamento

func (*Storage) ImportContext

func (s *Storage) ImportContext(sourcePath string) (*FileContext, error)

ImportContext importa um contexto de um arquivo

func (*Storage) LoadAllContexts

func (s *Storage) LoadAllContexts() ([]*FileContext, error)

LoadAllContexts carrega todos os contextos do disco

func (*Storage) LoadContext

func (s *Storage) LoadContext(contextID string) (*FileContext, error)

LoadContext carrega um contexto do disco

func (*Storage) SaveContext

func (s *Storage) SaveContext(ctx *FileContext) error

SaveContext salva um contexto em disco

type ValidationResult

type ValidationResult struct {
	Valid    bool     `json:"valid"`
	Errors   []string `json:"errors"`
	Warnings []string `json:"warnings"`
}

ValidationResult resultado da validação de um contexto

type Validator

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

Validator valida contextos e suas operações

func NewValidator

func NewValidator(logger *zap.Logger) *Validator

NewValidator cria uma nova instância de Validator

func (*Validator) ValidateContext

func (v *Validator) ValidateContext(ctx *FileContext) *ValidationResult

ValidateContext valida um contexto completo

func (*Validator) ValidateDescription

func (v *Validator) ValidateDescription(description string) error

ValidateDescription valida a descrição de um contexto

func (*Validator) ValidateMode

func (v *Validator) ValidateMode(mode ProcessingMode) error

ValidateMode valida o modo de processamento

func (*Validator) ValidateName

func (v *Validator) ValidateName(name string) error

ValidateName valida o nome de um contexto

func (*Validator) ValidatePriority

func (v *Validator) ValidatePriority(priority int) error

ValidatePriority valida a prioridade de anexação

func (*Validator) ValidateTags

func (v *Validator) ValidateTags(tags []string) error

ValidateTags valida as tags de um contexto

func (*Validator) ValidateTotalSize

func (v *Validator) ValidateTotalSize(size int64) error

ValidateTotalSize valida o tamanho total de arquivos

Jump to

Keyboard shortcuts

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